exports.id = 464; exports.ids = [464]; exports.modules = { /***/ 28231: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const GraphemeSplitter = __webpack_require__(30323); const ANSI_SEQUENCE = /^(.*?)(\x1b\[[^m]+m|\x1b\]8;;.*?(\x1b\\|\u0007))/; const splitter = new GraphemeSplitter(); module.exports = (orig, at = 0, until = orig.length) => { // Because to do this we'd need to know the printable length of the string, // which would require to do two passes (or would complexify the main one) if (at < 0 || until < 0) throw new RangeError(`Negative indices aren't supported by this implementation`); const length = until - at; let output = ``; let skipped = 0; let visible = 0; while (orig.length > 0) { const lookup = orig.match(ANSI_SEQUENCE) || [orig, orig, undefined]; let graphemes = splitter.splitGraphemes(lookup[1]); const skipping = Math.min(at - skipped, graphemes.length); graphemes = graphemes.slice(skipping); const displaying = Math.min(length - visible, graphemes.length); output += graphemes.slice(0, displaying).join(``); skipped += skipping; visible += displaying; if (typeof lookup[2] !== `undefined`) output += lookup[2]; orig = orig.slice(lookup[0].length); } return output; }; /***/ }), /***/ 54916: /***/ ((__unused_webpack_module, exports) => { exports.file = `# Write glob rules for ignored files. # Check syntax on https://deepcode.freshdesk.com/support/solutions/articles/60000531055-how-can-i-ignore-files-or-directories- # Check examples on https://github.com/github/gitignore `; /***/ }), /***/ 78105: /***/ ((__unused_webpack_module, exports) => { exports.file = `# Write glob rules for ignored files. # Check syntax on https://deepcode.freshdesk.com/support/solutions/articles/60000531055-how-can-i-ignore-files-or-directories- # Check examples on https://github.com/github/gitignore # Hidden directories .*/ # Julia deps/downloads/ deps/usr/ docs/build/ docs/site/ # CakePHP /vendor/* /tmp/cache/models/* !/tmp/cache/models/empty /tmp/cache/persistent/* !/tmp/cache/persistent/empty /tmp/cache/views/* !/tmp/cache/views/empty /tmp/sessions/* !/tmp/sessions/empty /tmp/tests/* !/tmp/tests/empty /logs/* !/logs/empty /app/tmp/* /vendors/* # KiCad *~ _autosave-* fp-info-cache # Dart build/ doc/api/ # PlayFramework bin/ /db /lib/ /logs/ /modules /project/project /project/target /target tmp/ test-result /dist/ # Zephir ext/build/ ext/modules/ ext/Makefile* ext/config* ext/autom4te* ext/install-sh ext/missing ext/mkinstalldirs ext/libtool # RhodesRhomobile rholog-* sim-* bin/libs bin/RhoBundle bin/tmp bin/target # AppEngine appengine-generated/ # Textpattern rpc/ sites/site*/admin/ sites/site*/private/ sites/site*/public/admin/ sites/site*/public/setup/ sites/site*/public/theme/ textpattern/ # ExpressionEngine images/avatars/ images/captchas/ images/smileys/ images/member_photos/ images/signature_attachments/ images/pm_attachments/ sized/ thumbs/ _thumbs/ */expressionengine/cache/* # CMake CMakeFiles CMakeScripts Testing Makefile _deps # Qt Makefile* *build-* # Yeoman node_modules/ bower_components/ build/ dist/ # ExtJs build/ ext/ # R /*.Rcheck/ *_cache/ /cache/ docs/ po/*~ # Python __pycache__/ build/ develop-eggs/ dist/ downloads/ eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ share/python-wheels/ *.egg-info/ MANIFEST htmlcov/ cover/ instance/ docs/_build/ target/ profile_default/ __pypackages__/ celerybeat-schedule env/ venv/ ENV/ env.bak/ venv.bak/ /site cython_debug/ # Magento /media/* !/media/customer /media/customer/* !/media/dhl /media/dhl/* !/media/downloadable /media/downloadable/* !/media/xmlconnect /media/xmlconnect/* !/media/xmlconnect/custom /media/xmlconnect/custom/* !/media/xmlconnect/original /media/xmlconnect/original/* !/media/xmlconnect/system /media/xmlconnect/system/* /var/* !/var/package /var/package/* # CodeIgniter */config/development */cache/* application/logs/* /vendor/ # Haskell dist dist-* cabal-dev # ArchLinuxPackages pkg/ # Elm elm-stuff repl-temp-* # Lithium libraries/* resources/tmp/* # Erlang rel/example_project deps _build/ _checkouts/ # ForceDotCom Referenced Packages # Plone bin/ build/ develop-eggs/ downloads/ eggs/ fake-eggs/ parts/ dist/ var/ # AppceleratorTitanium build/ # ChefCookbook /cookbooks bin/* # Objective-C xcuserdata/ build/ DerivedData/ Carthage/Build/ fastlane/test_output iOSInjectionProject/ # Opa _build _tracks opa-debug-js # Smalltalk /package-cache /play-cache /play-stash /github-cache # SeamGen /bootstrap/data /bootstrap/tmp /classes/ /dist/ /exploded-archives/ /test-build/ /test-output/ /test-report/ /target/ # Xilinx *_synth_* */*/bd/*/hdl */*/*/bd/*/hdl */*/bd/*/ip/*/*/ */*/*/bd/*/ip/*/*/ hw_handoff ipshared # Strapi Icon *~ $RECYCLE.BIN/ *# nbproject lib-cov pids logs results build node_modules testApp coverage cypress/screenshots cypress/videos dist packages/strapi-generate-new/files/public/ # Snap parts/ prime/ stage/ # Logtalk lgt_tmp/ logtalk_tester_logs/ logtalk_doclet_logs/ # SPFx logs node_modules dist lib solution temp coverage bin obj # Vue docs/_book test/ # NWjs locales/ pnacl/ # Cordova /platforms # Bazel /bazel-* # AltiumDesigner History __Previews Project\ Logs* Project\ Outputs* # ThinkPHP /Application/Runtime/ # Jigsaw build_* # Bitrix /bitrix/* !/bitrix/templates !/bitrix/components /bitrix/components/bitrix !/bitrix/gadgets /bitrix/gadgets/bitrix !/bitrix/php_interface/ /upload/ # CodeSniffer /wpcs/* # Pimcore /pimcore /website/var/assets/* /website/var/backup/* /website/var/cache/* /website/var/classes/Object* !/website/var/classes/objectbricks /website/var/config/Geo* /website/var/config/object/* /website/var/config/portal/* /website/var/config/sqlreport/* /website/var/email/* /website/var/recyclebin/* /website/var/search/* /website/var/system/* /website/var/tmp/* /website/var/versions/asset/* /website/var/versions/document/* /website/var/versions/object/* /website/var/user-image/* # Magento1 /media/* !/media/customer /media/customer/* !/media/dhl /media/dhl/* !/media/downloadable /media/downloadable/* !/media/xmlconnect /media/xmlconnect/* !/media/xmlconnect/custom /media/xmlconnect/custom/* !/media/xmlconnect/original /media/xmlconnect/original/* !/media/xmlconnect/system /media/xmlconnect/system/* /var/* !/var/package /var/package/* # Magento2 /sitemap /pub/sitemap /app/config_sandbox /app/code/Magento/TestModule* /pub/media/attribute/* /pub/media/analytics/* /pub/media/catalog/* /pub/media/customer/* /pub/media/downloadable/* /pub/media/favicon/* /pub/media/import/* /pub/media/logo/* /pub/media/theme/* /pub/media/theme_customization/* /pub/media/wysiwyg/* /pub/media/tmp/* /pub/media/captcha/* /pub/static/* /var/* /vendor/* /generated/* # Drupal7 files/ sites/*/files sites/*/private sites/*/translations /includes /misc /modules /profiles /scripts /themes # InforCMS [Mm]odel/[Dd]eployment !Model/Portal/*/SupportFiles/[Bb]in/ !Model/Portal/PortalTemplates/*/SupportFiles/[Bb]in # Kentico !CMS/CMSAdminControls/*/ !CMS/CMSModules/System/*/ !CMS/App_Data/CIRepository/** CMS/App_Data/AzureCache CMS/App_Data/AzureTemp CMS/App_Data/CMSTemp CMS/App_Data/Persistent CMS/CMSSiteUtils/Export CMS/CMSSiteUtils/Import CMS/App_Data/CMSModules/SmartSearch/** !CMS/App_Data/CMSModules/SmartSearch/*/ !CMS/App_Data/CMSModules/SmartSearch/_StopWords/** !CMS/App_Data/CMSModules/SmartSearch/_Synonyms/** CMS/App_Data/DancingGoat CMS/App_Data/Templates/CommunitySite CMS/App_Data/Templates/CorporateSite CMS/App_Data/Templates/DancingGoat CMS/App_Data/Templates/EcommerceSite CMS/App_Data/Templates/IntranetPortal CMS/App_Data/Templates/PersonalSite CMS/App_Themes/CommunitySite CMS/App_Themes/CorporateSite CMS/App_Themes/EcommerceSite CMS/App_Themes/IntranetPortal* CMS/App_Themes/PersonalSite CMS/CMSTemplates/CorporateSite CMS/CommunitySite CMS/CorporateSite CMS/DancingGoat CMS/EcommerceSite CMS/IntranetPortal CMS/PersonalSite # ROS2 install/ log/ build/ qtcreator-* *~ COLCON_IGNORE AMENT_IGNORE # Splunk local # Racket compiled/ # JupyterNotebooks profile_default/ # Nikola cache/ output/ # Red quick-test/runnable/ system/tests/source/units/auto-tests/ tests/source/units/auto-tests/ # AtmelStudio [Dd]ebug/ [Rr]elease/ # IAR_EWARM EWARM/**/Obj EWARM/**/List EWARM/**/Exe EWARM/settings # esp-idf build/ sdkconfig # Phoenix /tmp /node_modules /assets/node_modules /priv/static/ /installer/_build /installer/tmp /installer/doc /installer/deps # JBoss4 /server/all/data /server/all/log /server/all/tmp /server/all/work /server/default/data /server/default/log /server/default/tmp /server/default/work /server/minimal/data /server/minimal/log /server/minimal/tmp /server/minimal/work # JBoss6 /server/all/data /server/all/log /server/all/tmp /server/all/work /server/default/data /server/default/log /server/default/tmp /server/default/work /server/minimal/data /server/minimal/log /server/minimal/tmp /server/minimal/work /server/jbossweb-standalone/data /server/jbossweb-standalone/log /server/jbossweb-standalone/tmp /server/jbossweb-standalone/work /server/standard/data /server/standard/log /server/standard/tmp /server/standard/work # Hugo /public/ /resources/_gen/ # Puppet pkg/* spec/fixtures/* coverage/* vendor/* # Kotlin hs_err_pid* # Composer /vendor/ # Android bin/ gen/ out/ build/ proguard/ captures/ freeline/ fastlane/screenshots fastlane/test_output lint/intermediates/ lint/generated/ lint/outputs/ lint/tmp/ # Nim nimcache/ nimblecache/ htmldocs/ # Actionscript bin-debug/ bin-release/ [Oo]bj/ [Bb]in/ # Maven target/ # Agda MAlonzo/** # Unity /[Ll]ibrary/ /[Tt]emp/ /[Oo]bj/ /[Bb]uild/ /[Bb]uilds/ /[Ll]ogs/ /[Uu]ser[Ss]ettings/ /[Mm]emoryCaptures/ /[Aa]ssets/Plugins/Editor/JetBrains* ExportedObj/ /[Aa]ssets/[Ss]treamingAssets/aa/* # GWT war/gwt_bree/ gwt-unitCache/ war/WEB-INF/deploy/ war/WEB-INF/classes/ www-test/ # VirtualEnv [Bb]in [Ii]nclude [Ll]ib [Ll]ib64 [Ll]ocal [Ss]cripts # SBT dist/* target/ lib_managed/ project/boot/ project/plugins/project/ # PSoCCreator Debug/ Release/ Export/ */codegentemp */Generated_Source # TextMate tmtags # MonoDevelop test-results/ # SublimeText Package Control.cache/ Package Control.ca-certs/ # Dreamweaver _notes _compareTemp configs/ # NetBeans **/nbproject/private/ build/ nbbuild/ dist/ nbdist/ # Windows $RECYCLE.BIN/ # MATLAB helpsearch*/ slprj/ sccprj/ codegen/ octave-workspace # Octave helpsearch*/ slprj/ sccprj/ codegen/ octave-workspace # FlexBuilder bin/ bin-debug/ bin-release/ # Xcode xcuserdata/ build/ DerivedData/ # Lazarus backup/ lib/ *.app/ # CVS /CVS/* **/CVS/* # Eclipse bin/ tmp/ # Momentics x86/ arm/ arm-p/ # Linux *~ # Virtuoso lvsRunDir/* drcRunDir/* # Emacs *~ \#*\# auto-save-list tramp *_archive /eshell/history /eshell/lastdir /elpa/ /auto/ dist/ /server/ # EiffelStudio EIFGENs # macOS Icon Network Trash Folder Temporary Items # XilinxISE iseconfig/ xlnx_auto_0_xdb/ xst/ _ngo/ _xmsgs/ # CodeKit /min # SynopsysVCS simv simv.daidir/ simv.db.dir/ simv.vdb/ urgReport/ DVEfiles/ # Tags TAGS !TAGS/ tags !tags/ GTAGS GRTAGS GPATH GSYMS # ModelSim [_@]* wlf* cov*/ transcript* # JetBrains cmake-build-*/ out/ # WebMethods **/IntegrationServer/datastore/ **/IntegrationServer/db/ **/IntegrationServer/DocumentStore/ **/IntegrationServer/lib/ **/IntegrationServer/logs/ **/IntegrationServer/replicate/ **/IntegrationServer/sdk/ **/IntegrationServer/support/ **/IntegrationServer/update/ **/IntegrationServer/userFtpRoot/ **/IntegrationServer/web/ **/IntegrationServer/WmRepository4/ **/IntegrationServer/XAStore/ **/IntegrationServer/packages/Wm*/ # Vim *~ tags # Calabash rerun/ reports/ screenshots/ test-servers/ vendor # JDeveloper temp/ classes/ deploy/ javadoc/ # Drupal /sites/*/files /sites/*/public /sites/*/private /sites/*/files-public /sites/*/files-private /sites/*/translations /sites/*/tmp /sites/*/cache /sites/simpletest /core /vendor # UnrealEngine Binaries/* Plugins/*/Binaries/* Build/* !Build/*/ Build/*/** Saved/* Intermediate/* Plugins/*/Intermediate/* DerivedDataCache/* # Symfony /app/cache/* /app/logs/* /app/spool/* /var/cache/* /var/logs/* /var/sessions/* /var/log/* /bin/* !bin/console !bin/symfony_requirements /vendor/ /web/bundles/ /web/uploads/ /build/ **/Entity/*~ # JBoss jboss/server/all/tmp/**/* jboss/server/all/data/**/* jboss/server/all/work/**/* jboss/server/default/tmp/**/* jboss/server/default/data/**/* jboss/server/default/work/**/* jboss/server/minimal/tmp/**/* jboss/server/minimal/data/**/* jboss/server/minimal/work/**/* # SugarCRM /cache/* /custom/history/ /custom/modulebuilder/ /custom/working/ /custom/modules/*/Ext/ /custom/application/Ext/ /upload/* /upload_backup/ # Leiningen /lib/ /classes/ /target/ /checkouts/ # OpenCart download/ image/data/ image/cache/ system/cache/ system/logs/ system/storage/ vqmod/logs/* vqmod/vqcache/* # VVVV bin/ # Gradle **/build/ # FuelPHP /fuel/vendor /docs/ /fuel/app/logs/*/*/* /fuel/app/cache/*/* # Autotools /ar-lib /mdate-sh /py-compile /test-driver /ylwrap /compile /configure /depcomp /install-sh /missing /stamp-h1 Makefile # Delphi __history/ __recovery/ modules/ # GitBook node_modules _book # Prestashop /cache/* !/cache/push/activity !/cache/push/trends /download/* /img/* !/img/jquery-ui !/img/scenes /upload/* /vendor/* /docs/phpdoc-sf/ /admin-dev/autoupgrade/* /admin-dev/backups/* /admin-dev/import/* /admin-dev/export/* themes/*/cache/* config/xml/* config/themes/* modules/* override/* themes/*/ !themes/classic !themes/_core !themes/_libraries bower_components/ node_modules/ php-cs-fixer translations/* mails/* !mails/themes/ !mails/_partials/ themes/default-bootstrap/lang/* themes/default-bootstrap/mails/* !themes/default-bootstrap/mails/en/ themes/default-bootstrap/modules/*/mails/* !themes/default-bootstrap/modules/*/mails/en /bin/ /app/Resources/translations/* !/app/Resources/translations/default /build/ /var/* !/var/cache /var/cache/* !/var/logs /var/logs/* !/var/sessions /var/sessions/* /vendor/ /web/bundles/ # Xojo Builds* Debug*/Debug*\ Libs # WordPress !wp-content/ wp-content/* !wp-content/mu-plugins/ !wp-content/plugins/ !wp-content/themes/ wp-content/themes/twenty*/ node_modules/ # ROS devel/ logs/ build/ bin/ lib/ msg_gen/ srv_gen/ build_isolated/ devel_isolated/ /cfg/cpp/ qtcreator-* /planning/cfg /planning/docs *~ CATKIN_IGNORE # Scala hs_err_pid* # VisualStudio [Dd]ebug/ [Dd]ebugPublic/ [Rr]elease/ [Rr]eleases/ x64/ x86/ [Ww][Ii][Nn]32/ [Aa][Rr][Mm]/ [Aa][Rr][Mm]64/ bld/ [Bb]in/ [Oo]bj/ [Ll]og/ [Ll]ogs/ Generated\ Files/ [Tt]est[Rr]esult*/ [Dd]ebugPS/ [Rr]eleasePS/ BenchmarkDotNet.Artifacts/ artifacts/ _Chutzpah* ipch/ $tf/ _ReSharper*/ _TeamCity* _NCrunch_* nCrunchTemp_* AutoTest.Net/ [Ee]xpress/ DocProject/buildhelp/ DocProject/Help/Html2 DocProject/Help/html publish/ PublishScripts/ **/[Pp]ackages/* !**/[Pp]ackages/build/ csx/ ecf/ rcf/ AppPackages/ BundleArtifacts/ !?*.[Cc]ache/ ClientBin/ ~$* *~ Generated_Code/ _UpgradeReport_Files/ Backup*/ ServiceFabricBackup/ FakesAssemblies/ node_modules/ **/*.HTMLClient/GeneratedArtifacts **/*.DesktopClient/GeneratedArtifacts **/*.Server/GeneratedArtifacts _Pvt_Extensions paket-files/ __pycache__/ OpenCover/ ASALocalRun/ healthchecksdb MigrationBackup/ # Qooxdoo cache cache-downloads inspector api # Concrete5 error_log files/cache/* files/tmp/* /application/files/* /updates/* # Grails /web-app/WEB-INF/classes /test/reports /logs /plugins /web-app/plugins /target # Stella obj/ # Processing applet out # Rails /public/system /coverage/ /spec/tmp /log/* /tmp/* /vendor/bundle /vendor/assets/bower_components node_modules/ /public/packs /public/packs-test /public/assets /storage/* /public/uploads # PureScript bower_components node_modules output # Laravel /vendor/ node_modules/ app/storage/ public/storage public/hot public_html/storage public_html/hot # TwinCAT3 _Boot/ _CompileInfo/ _Libraries/ # Elixir /_build /cover /deps /doc # TurboGears2 data/* dist build # Godot data_*/ # Java hs_err_pid* # Swift xcuserdata/ build/ DerivedData/ Carthage/Build/ Dependencies/ fastlane/test_output iOSInjectionProject/ # Lilypond *~ # Joomla /administrator/cache/* /administrator/components/com_actionlogs/* /administrator/components/com_admin/* /administrator/components/com_ajax/* /administrator/components/com_associations/* /administrator/components/com_banners/* /administrator/components/com_cache/* /administrator/components/com_categories/* /administrator/components/com_checkin/* /administrator/components/com_config/* /administrator/components/com_contact/* /administrator/components/com_content/* /administrator/components/com_contenthistory/* /administrator/components/com_cpanel/* /administrator/components/com_fields/* /administrator/components/com_finder/* /administrator/components/com_installer/* /administrator/components/com_joomlaupdate/* /administrator/components/com_languages/* /administrator/components/com_login/* /administrator/components/com_media/* /administrator/components/com_menus/* /administrator/components/com_messages/* /administrator/components/com_modules/* /administrator/components/com_newsfeeds/* /administrator/components/com_plugins/* /administrator/components/com_postinstall/* /administrator/components/com_privacy/* /administrator/components/com_redirect/* /administrator/components/com_search/* /administrator/components/com_tags/* /administrator/components/com_templates/* /administrator/components/com_users/* /administrator/help/* /administrator/includes/* /administrator/language/overrides/* /administrator/logs/* /administrator/modules/mod_custom/* /administrator/modules/mod_feed/* /administrator/modules/mod_latest/* /administrator/modules/mod_latestactions/* /administrator/modules/mod_logged/* /administrator/modules/mod_login/* /administrator/modules/mod_menu/* /administrator/modules/mod_multilangstatus/* /administrator/modules/mod_online/* /administrator/modules/mod_popular/* /administrator/modules/mod_privacy_dashboard/* /administrator/modules/mod_quickicon/* /administrator/modules/mod_sampledata/* /administrator/modules/mod_stats_admin/* /administrator/modules/mod_status/* /administrator/modules/mod_submenu/* /administrator/modules/mod_title/* /administrator/modules/mod_toolbar/* /administrator/modules/mod_unread/* /administrator/modules/mod_version/* /administrator/templates/hathor/* /administrator/templates/isis/* /administrator/templates/system/* /bin/* /cache/* /cli/* /components/com_ajax/* /components/com_banners/* /components/com_config/* /components/com_contact/* /components/com_content/* /components/com_contenthistory/* /components/com_fields/* /components/com_finder/* /components/com_mailto/* /components/com_media/* /components/com_menus/* /components/com_modules/* /components/com_newsfeeds/* /components/com_privacy/* /components/com_search/* /components/com_tags/* /components/com_users/* /components/com_wrapper/* /images/banners/* /images/headers/* /images/sampledata/* /images/joomla* /includes/* /installation/* /language/overrides/* /layouts/joomla/* /layouts/libraries/* /layouts/plugins/* /libraries/cms/* /libraries/fof/* /libraries/idna_convert/* /libraries/joomla/* /libraries/legacy/* /libraries/php-encryption/* /libraries/phpass/* /libraries/phpmailer/* /libraries/phputf8/* /libraries/simplepie/* /libraries/vendor/* /media/cms/* /media/com_associations/* /media/com_contact/* /media/com_content/* /media/com_contenthistory/* /media/com_fields/* /media/com_finder/* /media/com_joomlaupdate/* /media/com_menus/* /media/com_modules/* /media/com_wrapper/* /media/contacts/* /media/editors/* /media/jui/* /media/mailto/* /media/media/* /media/mod_languages/* /media/mod_sampledata/* /media/overrider/* /media/plg_captcha_recaptcha/* /media/plg_captcha_recaptcha_invisible/* /media/plg_quickicon_extensionupdate/* /media/plg_quickicon_joomlaupdate/* /media/plg_quickicon_privacycheck/* /media/plg_system_highlight/* /media/plg_system_stats/* /media/plg_twofactorauth_totp/* /media/system/* /modules/mod_articles_archive/* /modules/mod_articles_categories/* /modules/mod_articles_category/* /modules/mod_articles_latest/* /modules/mod_articles_news/* /modules/mod_articles_popular/* /modules/mod_banners/* /modules/mod_breadcrumbs/* /modules/mod_custom/* /modules/mod_feed/* /modules/mod_finder/* /modules/mod_footer/* /modules/mod_languages/* /modules/mod_login/* /modules/mod_menu/* /modules/mod_random_image/* /modules/mod_related_items/* /modules/mod_search/* /modules/mod_stats/* /modules/mod_syndicate/* /modules/mod_tags_popular/* /modules/mod_tags_similar/* /modules/mod_users_latest/* /modules/mod_whosonline/* /modules/mod_wrapper/* /plugins/actionlog/joomla/* /plugins/authentication/cookie/* /plugins/authentication/example/* /plugins/authentication/gmail/* /plugins/authentication/joomla/* /plugins/authentication/ldap/* /plugins/captcha/recaptcha/* /plugins/captcha/recaptcha_invisible/* /plugins/content/confirmconsent/* /plugins/content/contact/* /plugins/content/emailcloak/* /plugins/content/example/* /plugins/content/fields/* /plugins/content/finder/* /plugins/content/geshi/* /plugins/content/joomla/* /plugins/content/loadmodule/* /plugins/content/pagebreak/* /plugins/content/pagenavigation/* /plugins/content/vote/* /plugins/editors/codemirror/* /plugins/editors/none/* /plugins/editors/tinymce/* /plugins/editors-xtd/article/* /plugins/editors-xtd/contact/* /plugins/editors-xtd/fields/* /plugins/editors-xtd/image/* /plugins/editors-xtd/menu/* /plugins/editors-xtd/module/* /plugins/editors-xtd/pagebreak/* /plugins/editors-xtd/readmore/* /plugins/extension/example/* /plugins/extension/joomla/* /plugins/fields/calendar/* /plugins/fields/checkboxes/* /plugins/fields/color/* /plugins/fields/editor/* /plugins/fields/imagelist/* /plugins/fields/integer/* /plugins/fields/list/* /plugins/fields/media/* /plugins/fields/radio/* /plugins/fields/repeatable/* /plugins/fields/sql/* /plugins/fields/text/* /plugins/fields/textarea/* /plugins/fields/url/* /plugins/fields/user/* /plugins/fields/usergrouplist/* /plugins/finder/categories/* /plugins/finder/contacts/* /plugins/finder/content/* /plugins/finder/newsfeeds/* /plugins/finder/tags/* /plugins/installer/folderinstaller/* /plugins/installer/packageinstaller/* /plugins/installer/urlinstaller/* /plugins/privacy/actionlogs/* /plugins/privacy/consents/* /plugins/privacy/contact/* /plugins/privacy/content/* /plugins/privacy/message/* /plugins/privacy/user/* /plugins/quickicon/extensionupdate/* /plugins/quickicon/joomlaupdate/* /plugins/quickicon/phpversioncheck/* /plugins/quickicon/privacycheck/* /plugins/sampledata/blog/* /plugins/search/categories/* /plugins/search/contacts/* /plugins/search/content/* /plugins/search/newsfeeds/* /plugins/search/tags/* /plugins/search/weblinks/* /plugins/system/actionlogs/* /plugins/system/cache/* /plugins/system/debug/* /plugins/system/fields/* /plugins/system/highlight/* /plugins/system/languagecode/* /plugins/system/languagefilter/* /plugins/system/log/* /plugins/system/logout/* /plugins/system/logrotation/* /plugins/system/p3p/* /plugins/system/privacyconsent/* /plugins/system/redirect/* /plugins/system/remember/* /plugins/system/sef/* /plugins/system/sessiongc/* /plugins/system/stats/* /plugins/system/updatenotification/* /plugins/twofactorauth/totp/* /plugins/twofactorauth/yubikey/* /plugins/user/contactcreator/* /plugins/user/example/* /plugins/user/joomla/* /plugins/user/profile/* /plugins/user/terms/* /templates/beez3/* /templates/protostar/* /templates/system/* /tmp/* # SymphonyCMS manifest/cache/ manifest/logs/ manifest/tmp/ symphony/ workspace/uploads/ # ZendFramework vendor/ data/logs/ data/cache/ data/sessions/ data/tmp/ temp/ data/DoctrineORMModule/Proxy/ data/DoctrineORMModule/cache/ demos/ extras/documentation # C *.dSYM/ # Node logs pids lib-cov coverage bower_components build/Release node_modules/ jspm_packages/ web_modules/ out dist # LemonStand /config/* /controllers/* /init/* /logs/* /phproad/* /temp/* /uploaded/* /installer_files/* /modules/backend/* /modules/blog/* /modules/cms/* /modules/core/* /modules/session/* /modules/shop/* /modules/system/* /modules/users/* # Waf waf-*-*/ waf3-*-*/ # TeX latex.out/ *-gnuplottex-* *-tikzDictionary _minted* sympy-plots-for-*.tex/ pythontex-files-*/ TSWLatexianTemp* *~[0-9]* # Rust debug/ target/ # Yii assets/* protected/runtime/* themes/classic/views/ # Mercury Mercury/ # Scrivener */QuickLook/ # Clojure /lib/ /classes/ /target/ /checkouts/ # Phalcon /cache/ /config/development/ # Typo3 /fileadmin/user_upload/ /fileadmin/_temp_/ /fileadmin/_processed_/ /uploads/ /typo3conf/temp_CACHED* /typo3conf/ENABLE_INSTALL_TOOL /FIRST_INSTALL /typo3 /Packages /typo3temp/ # JENKINS_HOME !/jobs jobs/** !jobs/**/ builds indexing jobs/**/*workspace # MetaProgrammingSystem classes_gen source_gen test_gen # CraftCMS /craft/storage/* !/craft/storage/rebrand # CFWheels plugins/**/* files db/sql javascripts/bundles stylesheets/bundles # OCaml _build/ _opam/ # Ruby /coverage/ /InstalledFiles /pkg/ /spec/reports/ /test/tmp/ /test/version_tmp/ /tmp/ build/ build-iPhoneOS/ build-iPhoneSimulator/ /_yardoc/ /doc/ /rdoc/ /vendor/bundle /lib/bundler/man/ # Perl !Build/ cover_db/ _build/ Build inc/ /blib/ /_eumm/ /Makefile /pm_to_blib # Elisp *~ # Jekyll _site/ # D docs/ # Packer packer_cache/ # Umbraco **/App_Data/Logs/ **/App_Data/[Pp]review/ **/App_Data/TEMP/ **/App_Data/NuGetBackup/ !**/App_Data/[Pp]ackages/* !**/[Uu]mbraco/[Dd]eveloper/[Pp]ackages/* !**/[Uu]mbraco/[Vv]iews/[Pp]ackages/* **/App_Data/cache/ # Kohana application/cache/* application/logs/* # Nanoc output/ tmp/nanoc/ `; /***/ }), /***/ 55086: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const { file: DefaultDCIgnore } = __webpack_require__(78105); const { file: CustomDCIgnore } = __webpack_require__(54916); module.exports = { DefaultDCIgnore, CustomDCIgnore, }; /***/ }), /***/ 98925: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const f = __webpack_require__(98633) const DateTime = global.Date class Date extends DateTime { constructor (value) { super(value) this.isDate = true } toISOString () { return `${this.getUTCFullYear()}-${f(2, this.getUTCMonth() + 1)}-${f(2, this.getUTCDate())}` } } module.exports = value => { const date = new Date(value) /* istanbul ignore if */ if (isNaN(date)) { throw new TypeError('Invalid Datetime') } else { return date } } /***/ }), /***/ 58904: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const f = __webpack_require__(98633) class FloatingDateTime extends Date { constructor (value) { super(value + 'Z') this.isFloating = true } toISOString () { const date = `${this.getUTCFullYear()}-${f(2, this.getUTCMonth() + 1)}-${f(2, this.getUTCDate())}` const time = `${f(2, this.getUTCHours())}:${f(2, this.getUTCMinutes())}:${f(2, this.getUTCSeconds())}.${f(3, this.getUTCMilliseconds())}` return `${date}T${time}` } } module.exports = value => { const date = new FloatingDateTime(value) /* istanbul ignore if */ if (isNaN(date)) { throw new TypeError('Invalid Datetime') } else { return date } } /***/ }), /***/ 76114: /***/ ((module) => { "use strict"; module.exports = value => { const date = new Date(value) /* istanbul ignore if */ if (isNaN(date)) { throw new TypeError('Invalid Datetime') } else { return date } } /***/ }), /***/ 99439: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const f = __webpack_require__(98633) class Time extends Date { constructor (value) { super(`0000-01-01T${value}Z`) this.isTime = true } toISOString () { return `${f(2, this.getUTCHours())}:${f(2, this.getUTCMinutes())}:${f(2, this.getUTCSeconds())}.${f(3, this.getUTCMilliseconds())}` } } module.exports = value => { const date = new Time(value) /* istanbul ignore if */ if (isNaN(date)) { throw new TypeError('Invalid Datetime') } else { return date } } /***/ }), /***/ 98633: /***/ ((module) => { "use strict"; module.exports = (d, num) => { num = String(num) while (num.length < d) num = '0' + num return num } /***/ }), /***/ 98818: /***/ ((module) => { "use strict"; const ParserEND = 0x110000 class ParserError extends Error { /* istanbul ignore next */ constructor (msg, filename, linenumber) { super('[ParserError] ' + msg, filename, linenumber) this.name = 'ParserError' this.code = 'ParserError' if (Error.captureStackTrace) Error.captureStackTrace(this, ParserError) } } class State { constructor (parser) { this.parser = parser this.buf = '' this.returned = null this.result = null this.resultTable = null this.resultArr = null } } class Parser { constructor () { this.pos = 0 this.col = 0 this.line = 0 this.obj = {} this.ctx = this.obj this.stack = [] this._buf = '' this.char = null this.ii = 0 this.state = new State(this.parseStart) } parse (str) { /* istanbul ignore next */ if (str.length === 0 || str.length == null) return this._buf = String(str) this.ii = -1 this.char = -1 let getNext while (getNext === false || this.nextChar()) { getNext = this.runOne() } this._buf = null } nextChar () { if (this.char === 0x0A) { ++this.line this.col = -1 } ++this.ii this.char = this._buf.codePointAt(this.ii) ++this.pos ++this.col return this.haveBuffer() } haveBuffer () { return this.ii < this._buf.length } runOne () { return this.state.parser.call(this, this.state.returned) } finish () { this.char = ParserEND let last do { last = this.state.parser this.runOne() } while (this.state.parser !== last) this.ctx = null this.state = null this._buf = null return this.obj } next (fn) { /* istanbul ignore next */ if (typeof fn !== 'function') throw new ParserError('Tried to set state to non-existent state: ' + JSON.stringify(fn)) this.state.parser = fn } goto (fn) { this.next(fn) return this.runOne() } call (fn, returnWith) { if (returnWith) this.next(returnWith) this.stack.push(this.state) this.state = new State(fn) } callNow (fn, returnWith) { this.call(fn, returnWith) return this.runOne() } return (value) { /* istanbul ignore next */ if (this.stack.length === 0) throw this.error(new ParserError('Stack underflow')) if (value === undefined) value = this.state.buf this.state = this.stack.pop() this.state.returned = value } returnNow (value) { this.return(value) return this.runOne() } consume () { /* istanbul ignore next */ if (this.char === ParserEND) throw this.error(new ParserError('Unexpected end-of-buffer')) this.state.buf += this._buf[this.ii] } error (err) { err.line = this.line err.col = this.col err.pos = this.pos return err } /* istanbul ignore next */ parseStart () { throw new ParserError('Must declare a parseStart method') } } Parser.END = ParserEND Parser.Error = ParserError module.exports = Parser /***/ }), /***/ 8676: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* eslint-disable no-new-wrappers, no-eval, camelcase, operator-linebreak */ module.exports = makeParserClass(__webpack_require__(98818)) module.exports.makeParserClass = makeParserClass class TomlError extends Error { constructor (msg) { super(msg) this.name = 'TomlError' /* istanbul ignore next */ if (Error.captureStackTrace) Error.captureStackTrace(this, TomlError) this.fromTOML = true this.wrapped = null } } TomlError.wrap = err => { const terr = new TomlError(err.message) terr.code = err.code terr.wrapped = err return terr } module.exports.TomlError = TomlError const createDateTime = __webpack_require__(76114) const createDateTimeFloat = __webpack_require__(58904) const createDate = __webpack_require__(98925) const createTime = __webpack_require__(99439) const CTRL_I = 0x09 const CTRL_J = 0x0A const CTRL_M = 0x0D const CTRL_CHAR_BOUNDARY = 0x1F // the last non-character in the latin1 region of unicode, except DEL const CHAR_SP = 0x20 const CHAR_QUOT = 0x22 const CHAR_NUM = 0x23 const CHAR_APOS = 0x27 const CHAR_PLUS = 0x2B const CHAR_COMMA = 0x2C const CHAR_HYPHEN = 0x2D const CHAR_PERIOD = 0x2E const CHAR_0 = 0x30 const CHAR_1 = 0x31 const CHAR_7 = 0x37 const CHAR_9 = 0x39 const CHAR_COLON = 0x3A const CHAR_EQUALS = 0x3D const CHAR_A = 0x41 const CHAR_E = 0x45 const CHAR_F = 0x46 const CHAR_T = 0x54 const CHAR_U = 0x55 const CHAR_Z = 0x5A const CHAR_LOWBAR = 0x5F const CHAR_a = 0x61 const CHAR_b = 0x62 const CHAR_e = 0x65 const CHAR_f = 0x66 const CHAR_i = 0x69 const CHAR_l = 0x6C const CHAR_n = 0x6E const CHAR_o = 0x6F const CHAR_r = 0x72 const CHAR_s = 0x73 const CHAR_t = 0x74 const CHAR_u = 0x75 const CHAR_x = 0x78 const CHAR_z = 0x7A const CHAR_LCUB = 0x7B const CHAR_RCUB = 0x7D const CHAR_LSQB = 0x5B const CHAR_BSOL = 0x5C const CHAR_RSQB = 0x5D const CHAR_DEL = 0x7F const SURROGATE_FIRST = 0xD800 const SURROGATE_LAST = 0xDFFF const escapes = { [CHAR_b]: '\u0008', [CHAR_t]: '\u0009', [CHAR_n]: '\u000A', [CHAR_f]: '\u000C', [CHAR_r]: '\u000D', [CHAR_QUOT]: '\u0022', [CHAR_BSOL]: '\u005C' } function isDigit (cp) { return cp >= CHAR_0 && cp <= CHAR_9 } function isHexit (cp) { return (cp >= CHAR_A && cp <= CHAR_F) || (cp >= CHAR_a && cp <= CHAR_f) || (cp >= CHAR_0 && cp <= CHAR_9) } function isBit (cp) { return cp === CHAR_1 || cp === CHAR_0 } function isOctit (cp) { return (cp >= CHAR_0 && cp <= CHAR_7) } function isAlphaNumQuoteHyphen (cp) { return (cp >= CHAR_A && cp <= CHAR_Z) || (cp >= CHAR_a && cp <= CHAR_z) || (cp >= CHAR_0 && cp <= CHAR_9) || cp === CHAR_APOS || cp === CHAR_QUOT || cp === CHAR_LOWBAR || cp === CHAR_HYPHEN } function isAlphaNumHyphen (cp) { return (cp >= CHAR_A && cp <= CHAR_Z) || (cp >= CHAR_a && cp <= CHAR_z) || (cp >= CHAR_0 && cp <= CHAR_9) || cp === CHAR_LOWBAR || cp === CHAR_HYPHEN } const _type = Symbol('type') const _declared = Symbol('declared') const hasOwnProperty = Object.prototype.hasOwnProperty const defineProperty = Object.defineProperty const descriptor = {configurable: true, enumerable: true, writable: true, value: undefined} function hasKey (obj, key) { if (hasOwnProperty.call(obj, key)) return true if (key === '__proto__') defineProperty(obj, '__proto__', descriptor) return false } const INLINE_TABLE = Symbol('inline-table') function InlineTable () { return Object.defineProperties({}, { [_type]: {value: INLINE_TABLE} }) } function isInlineTable (obj) { if (obj === null || typeof (obj) !== 'object') return false return obj[_type] === INLINE_TABLE } const TABLE = Symbol('table') function Table () { return Object.defineProperties({}, { [_type]: {value: TABLE}, [_declared]: {value: false, writable: true} }) } function isTable (obj) { if (obj === null || typeof (obj) !== 'object') return false return obj[_type] === TABLE } const _contentType = Symbol('content-type') const INLINE_LIST = Symbol('inline-list') function InlineList (type) { return Object.defineProperties([], { [_type]: {value: INLINE_LIST}, [_contentType]: {value: type} }) } function isInlineList (obj) { if (obj === null || typeof (obj) !== 'object') return false return obj[_type] === INLINE_LIST } const LIST = Symbol('list') function List () { return Object.defineProperties([], { [_type]: {value: LIST} }) } function isList (obj) { if (obj === null || typeof (obj) !== 'object') return false return obj[_type] === LIST } // in an eval, to let bundlers not slurp in a util proxy let _custom try { const utilInspect = eval("require('util').inspect") _custom = utilInspect.custom } catch (_) { /* eval require not available in transpiled bundle */ } /* istanbul ignore next */ const _inspect = _custom || 'inspect' class BoxedBigInt { constructor (value) { try { this.value = global.BigInt.asIntN(64, value) } catch (_) { /* istanbul ignore next */ this.value = null } Object.defineProperty(this, _type, {value: INTEGER}) } isNaN () { return this.value === null } /* istanbul ignore next */ toString () { return String(this.value) } /* istanbul ignore next */ [_inspect] () { return `[BigInt: ${this.toString()}]}` } valueOf () { return this.value } } const INTEGER = Symbol('integer') function Integer (value) { let num = Number(value) // -0 is a float thing, not an int thing if (Object.is(num, -0)) num = 0 /* istanbul ignore else */ if (global.BigInt && !Number.isSafeInteger(num)) { return new BoxedBigInt(value) } else { /* istanbul ignore next */ return Object.defineProperties(new Number(num), { isNaN: {value: function () { return isNaN(this) }}, [_type]: {value: INTEGER}, [_inspect]: {value: () => `[Integer: ${value}]`} }) } } function isInteger (obj) { if (obj === null || typeof (obj) !== 'object') return false return obj[_type] === INTEGER } const FLOAT = Symbol('float') function Float (value) { /* istanbul ignore next */ return Object.defineProperties(new Number(value), { [_type]: {value: FLOAT}, [_inspect]: {value: () => `[Float: ${value}]`} }) } function isFloat (obj) { if (obj === null || typeof (obj) !== 'object') return false return obj[_type] === FLOAT } function tomlType (value) { const type = typeof value if (type === 'object') { /* istanbul ignore if */ if (value === null) return 'null' if (value instanceof Date) return 'datetime' /* istanbul ignore else */ if (_type in value) { switch (value[_type]) { case INLINE_TABLE: return 'inline-table' case INLINE_LIST: return 'inline-list' /* istanbul ignore next */ case TABLE: return 'table' /* istanbul ignore next */ case LIST: return 'list' case FLOAT: return 'float' case INTEGER: return 'integer' } } } return type } function makeParserClass (Parser) { class TOMLParser extends Parser { constructor () { super() this.ctx = this.obj = Table() } /* MATCH HELPER */ atEndOfWord () { return this.char === CHAR_NUM || this.char === CTRL_I || this.char === CHAR_SP || this.atEndOfLine() } atEndOfLine () { return this.char === Parser.END || this.char === CTRL_J || this.char === CTRL_M } parseStart () { if (this.char === Parser.END) { return null } else if (this.char === CHAR_LSQB) { return this.call(this.parseTableOrList) } else if (this.char === CHAR_NUM) { return this.call(this.parseComment) } else if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) { return null } else if (isAlphaNumQuoteHyphen(this.char)) { return this.callNow(this.parseAssignStatement) } else { throw this.error(new TomlError(`Unknown character "${this.char}"`)) } } // HELPER, this strips any whitespace and comments to the end of the line // then RETURNS. Last state in a production. parseWhitespaceToEOL () { if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) { return null } else if (this.char === CHAR_NUM) { return this.goto(this.parseComment) } else if (this.char === Parser.END || this.char === CTRL_J) { return this.return() } else { throw this.error(new TomlError('Unexpected character, expected only whitespace or comments till end of line')) } } /* ASSIGNMENT: key = value */ parseAssignStatement () { return this.callNow(this.parseAssign, this.recordAssignStatement) } recordAssignStatement (kv) { let target = this.ctx let finalKey = kv.key.pop() for (let kw of kv.key) { if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) { throw this.error(new TomlError("Can't redefine existing key")) } target = target[kw] = target[kw] || Table() } if (hasKey(target, finalKey)) { throw this.error(new TomlError("Can't redefine existing key")) } // unbox our numbers if (isInteger(kv.value) || isFloat(kv.value)) { target[finalKey] = kv.value.valueOf() } else { target[finalKey] = kv.value } return this.goto(this.parseWhitespaceToEOL) } /* ASSSIGNMENT expression, key = value possibly inside an inline table */ parseAssign () { return this.callNow(this.parseKeyword, this.recordAssignKeyword) } recordAssignKeyword (key) { if (this.state.resultTable) { this.state.resultTable.push(key) } else { this.state.resultTable = [key] } return this.goto(this.parseAssignKeywordPreDot) } parseAssignKeywordPreDot () { if (this.char === CHAR_PERIOD) { return this.next(this.parseAssignKeywordPostDot) } else if (this.char !== CHAR_SP && this.char !== CTRL_I) { return this.goto(this.parseAssignEqual) } } parseAssignKeywordPostDot () { if (this.char !== CHAR_SP && this.char !== CTRL_I) { return this.callNow(this.parseKeyword, this.recordAssignKeyword) } } parseAssignEqual () { if (this.char === CHAR_EQUALS) { return this.next(this.parseAssignPreValue) } else { throw this.error(new TomlError('Invalid character, expected "="')) } } parseAssignPreValue () { if (this.char === CHAR_SP || this.char === CTRL_I) { return null } else { return this.callNow(this.parseValue, this.recordAssignValue) } } recordAssignValue (value) { return this.returnNow({key: this.state.resultTable, value: value}) } /* COMMENTS: #...eol */ parseComment () { do { if (this.char === Parser.END || this.char === CTRL_J) { return this.return() } } while (this.nextChar()) } /* TABLES AND LISTS, [foo] and [[foo]] */ parseTableOrList () { if (this.char === CHAR_LSQB) { this.next(this.parseList) } else { return this.goto(this.parseTable) } } /* TABLE [foo.bar.baz] */ parseTable () { this.ctx = this.obj return this.goto(this.parseTableNext) } parseTableNext () { if (this.char === CHAR_SP || this.char === CTRL_I) { return null } else { return this.callNow(this.parseKeyword, this.parseTableMore) } } parseTableMore (keyword) { if (this.char === CHAR_SP || this.char === CTRL_I) { return null } else if (this.char === CHAR_RSQB) { if (hasKey(this.ctx, keyword) && (!isTable(this.ctx[keyword]) || this.ctx[keyword][_declared])) { throw this.error(new TomlError("Can't redefine existing key")) } else { this.ctx = this.ctx[keyword] = this.ctx[keyword] || Table() this.ctx[_declared] = true } return this.next(this.parseWhitespaceToEOL) } else if (this.char === CHAR_PERIOD) { if (!hasKey(this.ctx, keyword)) { this.ctx = this.ctx[keyword] = Table() } else if (isTable(this.ctx[keyword])) { this.ctx = this.ctx[keyword] } else if (isList(this.ctx[keyword])) { this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1] } else { throw this.error(new TomlError("Can't redefine existing key")) } return this.next(this.parseTableNext) } else { throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]')) } } /* LIST [[a.b.c]] */ parseList () { this.ctx = this.obj return this.goto(this.parseListNext) } parseListNext () { if (this.char === CHAR_SP || this.char === CTRL_I) { return null } else { return this.callNow(this.parseKeyword, this.parseListMore) } } parseListMore (keyword) { if (this.char === CHAR_SP || this.char === CTRL_I) { return null } else if (this.char === CHAR_RSQB) { if (!hasKey(this.ctx, keyword)) { this.ctx[keyword] = List() } if (isInlineList(this.ctx[keyword])) { throw this.error(new TomlError("Can't extend an inline array")) } else if (isList(this.ctx[keyword])) { const next = Table() this.ctx[keyword].push(next) this.ctx = next } else { throw this.error(new TomlError("Can't redefine an existing key")) } return this.next(this.parseListEnd) } else if (this.char === CHAR_PERIOD) { if (!hasKey(this.ctx, keyword)) { this.ctx = this.ctx[keyword] = Table() } else if (isInlineList(this.ctx[keyword])) { throw this.error(new TomlError("Can't extend an inline array")) } else if (isInlineTable(this.ctx[keyword])) { throw this.error(new TomlError("Can't extend an inline table")) } else if (isList(this.ctx[keyword])) { this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1] } else if (isTable(this.ctx[keyword])) { this.ctx = this.ctx[keyword] } else { throw this.error(new TomlError("Can't redefine an existing key")) } return this.next(this.parseListNext) } else { throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]')) } } parseListEnd (keyword) { if (this.char === CHAR_RSQB) { return this.next(this.parseWhitespaceToEOL) } else { throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]')) } } /* VALUE string, number, boolean, inline list, inline object */ parseValue () { if (this.char === Parser.END) { throw this.error(new TomlError('Key without value')) } else if (this.char === CHAR_QUOT) { return this.next(this.parseDoubleString) } if (this.char === CHAR_APOS) { return this.next(this.parseSingleString) } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) { return this.goto(this.parseNumberSign) } else if (this.char === CHAR_i) { return this.next(this.parseInf) } else if (this.char === CHAR_n) { return this.next(this.parseNan) } else if (isDigit(this.char)) { return this.goto(this.parseNumberOrDateTime) } else if (this.char === CHAR_t || this.char === CHAR_f) { return this.goto(this.parseBoolean) } else if (this.char === CHAR_LSQB) { return this.call(this.parseInlineList, this.recordValue) } else if (this.char === CHAR_LCUB) { return this.call(this.parseInlineTable, this.recordValue) } else { throw this.error(new TomlError('Unexpected character, expecting string, number, datetime, boolean, inline array or inline table')) } } recordValue (value) { return this.returnNow(value) } parseInf () { if (this.char === CHAR_n) { return this.next(this.parseInf2) } else { throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"')) } } parseInf2 () { if (this.char === CHAR_f) { if (this.state.buf === '-') { return this.return(-Infinity) } else { return this.return(Infinity) } } else { throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"')) } } parseNan () { if (this.char === CHAR_a) { return this.next(this.parseNan2) } else { throw this.error(new TomlError('Unexpected character, expected "nan"')) } } parseNan2 () { if (this.char === CHAR_n) { return this.return(NaN) } else { throw this.error(new TomlError('Unexpected character, expected "nan"')) } } /* KEYS, barewords or basic, literal, or dotted */ parseKeyword () { if (this.char === CHAR_QUOT) { return this.next(this.parseBasicString) } else if (this.char === CHAR_APOS) { return this.next(this.parseLiteralString) } else { return this.goto(this.parseBareKey) } } /* KEYS: barewords */ parseBareKey () { do { if (this.char === Parser.END) { throw this.error(new TomlError('Key ended without value')) } else if (isAlphaNumHyphen(this.char)) { this.consume() } else if (this.state.buf.length === 0) { throw this.error(new TomlError('Empty bare keys are not allowed')) } else { return this.returnNow() } } while (this.nextChar()) } /* STRINGS, single quoted (literal) */ parseSingleString () { if (this.char === CHAR_APOS) { return this.next(this.parseLiteralMultiStringMaybe) } else { return this.goto(this.parseLiteralString) } } parseLiteralString () { do { if (this.char === CHAR_APOS) { return this.return() } else if (this.atEndOfLine()) { throw this.error(new TomlError('Unterminated string')) } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I)) { throw this.errorControlCharInString() } else { this.consume() } } while (this.nextChar()) } parseLiteralMultiStringMaybe () { if (this.char === CHAR_APOS) { return this.next(this.parseLiteralMultiString) } else { return this.returnNow() } } parseLiteralMultiString () { if (this.char === CTRL_M) { return null } else if (this.char === CTRL_J) { return this.next(this.parseLiteralMultiStringContent) } else { return this.goto(this.parseLiteralMultiStringContent) } } parseLiteralMultiStringContent () { do { if (this.char === CHAR_APOS) { return this.next(this.parseLiteralMultiEnd) } else if (this.char === Parser.END) { throw this.error(new TomlError('Unterminated multi-line string')) } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M)) { throw this.errorControlCharInString() } else { this.consume() } } while (this.nextChar()) } parseLiteralMultiEnd () { if (this.char === CHAR_APOS) { return this.next(this.parseLiteralMultiEnd2) } else { this.state.buf += "'" return this.goto(this.parseLiteralMultiStringContent) } } parseLiteralMultiEnd2 () { if (this.char === CHAR_APOS) { return this.return() } else { this.state.buf += "''" return this.goto(this.parseLiteralMultiStringContent) } } /* STRINGS double quoted */ parseDoubleString () { if (this.char === CHAR_QUOT) { return this.next(this.parseMultiStringMaybe) } else { return this.goto(this.parseBasicString) } } parseBasicString () { do { if (this.char === CHAR_BSOL) { return this.call(this.parseEscape, this.recordEscapeReplacement) } else if (this.char === CHAR_QUOT) { return this.return() } else if (this.atEndOfLine()) { throw this.error(new TomlError('Unterminated string')) } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I)) { throw this.errorControlCharInString() } else { this.consume() } } while (this.nextChar()) } recordEscapeReplacement (replacement) { this.state.buf += replacement return this.goto(this.parseBasicString) } parseMultiStringMaybe () { if (this.char === CHAR_QUOT) { return this.next(this.parseMultiString) } else { return this.returnNow() } } parseMultiString () { if (this.char === CTRL_M) { return null } else if (this.char === CTRL_J) { return this.next(this.parseMultiStringContent) } else { return this.goto(this.parseMultiStringContent) } } parseMultiStringContent () { do { if (this.char === CHAR_BSOL) { return this.call(this.parseMultiEscape, this.recordMultiEscapeReplacement) } else if (this.char === CHAR_QUOT) { return this.next(this.parseMultiEnd) } else if (this.char === Parser.END) { throw this.error(new TomlError('Unterminated multi-line string')) } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M)) { throw this.errorControlCharInString() } else { this.consume() } } while (this.nextChar()) } errorControlCharInString () { let displayCode = '\\u00' if (this.char < 16) { displayCode += '0' } displayCode += this.char.toString(16) return this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${displayCode} instead`)) } recordMultiEscapeReplacement (replacement) { this.state.buf += replacement return this.goto(this.parseMultiStringContent) } parseMultiEnd () { if (this.char === CHAR_QUOT) { return this.next(this.parseMultiEnd2) } else { this.state.buf += '"' return this.goto(this.parseMultiStringContent) } } parseMultiEnd2 () { if (this.char === CHAR_QUOT) { return this.return() } else { this.state.buf += '""' return this.goto(this.parseMultiStringContent) } } parseMultiEscape () { if (this.char === CTRL_M || this.char === CTRL_J) { return this.next(this.parseMultiTrim) } else if (this.char === CHAR_SP || this.char === CTRL_I) { return this.next(this.parsePreMultiTrim) } else { return this.goto(this.parseEscape) } } parsePreMultiTrim () { if (this.char === CHAR_SP || this.char === CTRL_I) { return null } else if (this.char === CTRL_M || this.char === CTRL_J) { return this.next(this.parseMultiTrim) } else { throw this.error(new TomlError("Can't escape whitespace")) } } parseMultiTrim () { // explicitly whitespace here, END should follow the same path as chars if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) { return null } else { return this.returnNow() } } parseEscape () { if (this.char in escapes) { return this.return(escapes[this.char]) } else if (this.char === CHAR_u) { return this.call(this.parseSmallUnicode, this.parseUnicodeReturn) } else if (this.char === CHAR_U) { return this.call(this.parseLargeUnicode, this.parseUnicodeReturn) } else { throw this.error(new TomlError('Unknown escape character: ' + this.char)) } } parseUnicodeReturn (char) { try { const codePoint = parseInt(char, 16) if (codePoint >= SURROGATE_FIRST && codePoint <= SURROGATE_LAST) { throw this.error(new TomlError('Invalid unicode, character in range 0xD800 - 0xDFFF is reserved')) } return this.returnNow(String.fromCodePoint(codePoint)) } catch (err) { throw this.error(TomlError.wrap(err)) } } parseSmallUnicode () { if (!isHexit(this.char)) { throw this.error(new TomlError('Invalid character in unicode sequence, expected hex')) } else { this.consume() if (this.state.buf.length >= 4) return this.return() } } parseLargeUnicode () { if (!isHexit(this.char)) { throw this.error(new TomlError('Invalid character in unicode sequence, expected hex')) } else { this.consume() if (this.state.buf.length >= 8) return this.return() } } /* NUMBERS */ parseNumberSign () { this.consume() return this.next(this.parseMaybeSignedInfOrNan) } parseMaybeSignedInfOrNan () { if (this.char === CHAR_i) { return this.next(this.parseInf) } else if (this.char === CHAR_n) { return this.next(this.parseNan) } else { return this.callNow(this.parseNoUnder, this.parseNumberIntegerStart) } } parseNumberIntegerStart () { if (this.char === CHAR_0) { this.consume() return this.next(this.parseNumberIntegerExponentOrDecimal) } else { return this.goto(this.parseNumberInteger) } } parseNumberIntegerExponentOrDecimal () { if (this.char === CHAR_PERIOD) { this.consume() return this.call(this.parseNoUnder, this.parseNumberFloat) } else if (this.char === CHAR_E || this.char === CHAR_e) { this.consume() return this.next(this.parseNumberExponentSign) } else { return this.returnNow(Integer(this.state.buf)) } } parseNumberInteger () { if (isDigit(this.char)) { this.consume() } else if (this.char === CHAR_LOWBAR) { return this.call(this.parseNoUnder) } else if (this.char === CHAR_E || this.char === CHAR_e) { this.consume() return this.next(this.parseNumberExponentSign) } else if (this.char === CHAR_PERIOD) { this.consume() return this.call(this.parseNoUnder, this.parseNumberFloat) } else { const result = Integer(this.state.buf) /* istanbul ignore if */ if (result.isNaN()) { throw this.error(new TomlError('Invalid number')) } else { return this.returnNow(result) } } } parseNoUnder () { if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD || this.char === CHAR_E || this.char === CHAR_e) { throw this.error(new TomlError('Unexpected character, expected digit')) } else if (this.atEndOfWord()) { throw this.error(new TomlError('Incomplete number')) } return this.returnNow() } parseNoUnderHexOctBinLiteral () { if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD) { throw this.error(new TomlError('Unexpected character, expected digit')) } else if (this.atEndOfWord()) { throw this.error(new TomlError('Incomplete number')) } return this.returnNow() } parseNumberFloat () { if (this.char === CHAR_LOWBAR) { return this.call(this.parseNoUnder, this.parseNumberFloat) } else if (isDigit(this.char)) { this.consume() } else if (this.char === CHAR_E || this.char === CHAR_e) { this.consume() return this.next(this.parseNumberExponentSign) } else { return this.returnNow(Float(this.state.buf)) } } parseNumberExponentSign () { if (isDigit(this.char)) { return this.goto(this.parseNumberExponent) } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) { this.consume() this.call(this.parseNoUnder, this.parseNumberExponent) } else { throw this.error(new TomlError('Unexpected character, expected -, + or digit')) } } parseNumberExponent () { if (isDigit(this.char)) { this.consume() } else if (this.char === CHAR_LOWBAR) { return this.call(this.parseNoUnder) } else { return this.returnNow(Float(this.state.buf)) } } /* NUMBERS or DATETIMES */ parseNumberOrDateTime () { if (this.char === CHAR_0) { this.consume() return this.next(this.parseNumberBaseOrDateTime) } else { return this.goto(this.parseNumberOrDateTimeOnly) } } parseNumberOrDateTimeOnly () { // note, if two zeros are in a row then it MUST be a date if (this.char === CHAR_LOWBAR) { return this.call(this.parseNoUnder, this.parseNumberInteger) } else if (isDigit(this.char)) { this.consume() if (this.state.buf.length > 4) this.next(this.parseNumberInteger) } else if (this.char === CHAR_E || this.char === CHAR_e) { this.consume() return this.next(this.parseNumberExponentSign) } else if (this.char === CHAR_PERIOD) { this.consume() return this.call(this.parseNoUnder, this.parseNumberFloat) } else if (this.char === CHAR_HYPHEN) { return this.goto(this.parseDateTime) } else if (this.char === CHAR_COLON) { return this.goto(this.parseOnlyTimeHour) } else { return this.returnNow(Integer(this.state.buf)) } } parseDateTimeOnly () { if (this.state.buf.length < 4) { if (isDigit(this.char)) { return this.consume() } else if (this.char === CHAR_COLON) { return this.goto(this.parseOnlyTimeHour) } else { throw this.error(new TomlError('Expected digit while parsing year part of a date')) } } else { if (this.char === CHAR_HYPHEN) { return this.goto(this.parseDateTime) } else { throw this.error(new TomlError('Expected hyphen (-) while parsing year part of date')) } } } parseNumberBaseOrDateTime () { if (this.char === CHAR_b) { this.consume() return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerBin) } else if (this.char === CHAR_o) { this.consume() return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerOct) } else if (this.char === CHAR_x) { this.consume() return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerHex) } else if (this.char === CHAR_PERIOD) { return this.goto(this.parseNumberInteger) } else if (isDigit(this.char)) { return this.goto(this.parseDateTimeOnly) } else { return this.returnNow(Integer(this.state.buf)) } } parseIntegerHex () { if (isHexit(this.char)) { this.consume() } else if (this.char === CHAR_LOWBAR) { return this.call(this.parseNoUnderHexOctBinLiteral) } else { const result = Integer(this.state.buf) /* istanbul ignore if */ if (result.isNaN()) { throw this.error(new TomlError('Invalid number')) } else { return this.returnNow(result) } } } parseIntegerOct () { if (isOctit(this.char)) { this.consume() } else if (this.char === CHAR_LOWBAR) { return this.call(this.parseNoUnderHexOctBinLiteral) } else { const result = Integer(this.state.buf) /* istanbul ignore if */ if (result.isNaN()) { throw this.error(new TomlError('Invalid number')) } else { return this.returnNow(result) } } } parseIntegerBin () { if (isBit(this.char)) { this.consume() } else if (this.char === CHAR_LOWBAR) { return this.call(this.parseNoUnderHexOctBinLiteral) } else { const result = Integer(this.state.buf) /* istanbul ignore if */ if (result.isNaN()) { throw this.error(new TomlError('Invalid number')) } else { return this.returnNow(result) } } } /* DATETIME */ parseDateTime () { // we enter here having just consumed the year and about to consume the hyphen if (this.state.buf.length < 4) { throw this.error(new TomlError('Years less than 1000 must be zero padded to four characters')) } this.state.result = this.state.buf this.state.buf = '' return this.next(this.parseDateMonth) } parseDateMonth () { if (this.char === CHAR_HYPHEN) { if (this.state.buf.length < 2) { throw this.error(new TomlError('Months less than 10 must be zero padded to two characters')) } this.state.result += '-' + this.state.buf this.state.buf = '' return this.next(this.parseDateDay) } else if (isDigit(this.char)) { this.consume() } else { throw this.error(new TomlError('Incomplete datetime')) } } parseDateDay () { if (this.char === CHAR_T || this.char === CHAR_SP) { if (this.state.buf.length < 2) { throw this.error(new TomlError('Days less than 10 must be zero padded to two characters')) } this.state.result += '-' + this.state.buf this.state.buf = '' return this.next(this.parseStartTimeHour) } else if (this.atEndOfWord()) { return this.returnNow(createDate(this.state.result + '-' + this.state.buf)) } else if (isDigit(this.char)) { this.consume() } else { throw this.error(new TomlError('Incomplete datetime')) } } parseStartTimeHour () { if (this.atEndOfWord()) { return this.returnNow(createDate(this.state.result)) } else { return this.goto(this.parseTimeHour) } } parseTimeHour () { if (this.char === CHAR_COLON) { if (this.state.buf.length < 2) { throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters')) } this.state.result += 'T' + this.state.buf this.state.buf = '' return this.next(this.parseTimeMin) } else if (isDigit(this.char)) { this.consume() } else { throw this.error(new TomlError('Incomplete datetime')) } } parseTimeMin () { if (this.state.buf.length < 2 && isDigit(this.char)) { this.consume() } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) { this.state.result += ':' + this.state.buf this.state.buf = '' return this.next(this.parseTimeSec) } else { throw this.error(new TomlError('Incomplete datetime')) } } parseTimeSec () { if (isDigit(this.char)) { this.consume() if (this.state.buf.length === 2) { this.state.result += ':' + this.state.buf this.state.buf = '' return this.next(this.parseTimeZoneOrFraction) } } else { throw this.error(new TomlError('Incomplete datetime')) } } parseOnlyTimeHour () { /* istanbul ignore else */ if (this.char === CHAR_COLON) { if (this.state.buf.length < 2) { throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters')) } this.state.result = this.state.buf this.state.buf = '' return this.next(this.parseOnlyTimeMin) } else { throw this.error(new TomlError('Incomplete time')) } } parseOnlyTimeMin () { if (this.state.buf.length < 2 && isDigit(this.char)) { this.consume() } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) { this.state.result += ':' + this.state.buf this.state.buf = '' return this.next(this.parseOnlyTimeSec) } else { throw this.error(new TomlError('Incomplete time')) } } parseOnlyTimeSec () { if (isDigit(this.char)) { this.consume() if (this.state.buf.length === 2) { return this.next(this.parseOnlyTimeFractionMaybe) } } else { throw this.error(new TomlError('Incomplete time')) } } parseOnlyTimeFractionMaybe () { this.state.result += ':' + this.state.buf if (this.char === CHAR_PERIOD) { this.state.buf = '' this.next(this.parseOnlyTimeFraction) } else { return this.return(createTime(this.state.result)) } } parseOnlyTimeFraction () { if (isDigit(this.char)) { this.consume() } else if (this.atEndOfWord()) { if (this.state.buf.length === 0) throw this.error(new TomlError('Expected digit in milliseconds')) return this.returnNow(createTime(this.state.result + '.' + this.state.buf)) } else { throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z')) } } parseTimeZoneOrFraction () { if (this.char === CHAR_PERIOD) { this.consume() this.next(this.parseDateTimeFraction) } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) { this.consume() this.next(this.parseTimeZoneHour) } else if (this.char === CHAR_Z) { this.consume() return this.return(createDateTime(this.state.result + this.state.buf)) } else if (this.atEndOfWord()) { return this.returnNow(createDateTimeFloat(this.state.result + this.state.buf)) } else { throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z')) } } parseDateTimeFraction () { if (isDigit(this.char)) { this.consume() } else if (this.state.buf.length === 1) { throw this.error(new TomlError('Expected digit in milliseconds')) } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) { this.consume() this.next(this.parseTimeZoneHour) } else if (this.char === CHAR_Z) { this.consume() return this.return(createDateTime(this.state.result + this.state.buf)) } else if (this.atEndOfWord()) { return this.returnNow(createDateTimeFloat(this.state.result + this.state.buf)) } else { throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z')) } } parseTimeZoneHour () { if (isDigit(this.char)) { this.consume() // FIXME: No more regexps if (/\d\d$/.test(this.state.buf)) return this.next(this.parseTimeZoneSep) } else { throw this.error(new TomlError('Unexpected character in datetime, expected digit')) } } parseTimeZoneSep () { if (this.char === CHAR_COLON) { this.consume() this.next(this.parseTimeZoneMin) } else { throw this.error(new TomlError('Unexpected character in datetime, expected colon')) } } parseTimeZoneMin () { if (isDigit(this.char)) { this.consume() if (/\d\d$/.test(this.state.buf)) return this.return(createDateTime(this.state.result + this.state.buf)) } else { throw this.error(new TomlError('Unexpected character in datetime, expected digit')) } } /* BOOLEAN */ parseBoolean () { /* istanbul ignore else */ if (this.char === CHAR_t) { this.consume() return this.next(this.parseTrue_r) } else if (this.char === CHAR_f) { this.consume() return this.next(this.parseFalse_a) } } parseTrue_r () { if (this.char === CHAR_r) { this.consume() return this.next(this.parseTrue_u) } else { throw this.error(new TomlError('Invalid boolean, expected true or false')) } } parseTrue_u () { if (this.char === CHAR_u) { this.consume() return this.next(this.parseTrue_e) } else { throw this.error(new TomlError('Invalid boolean, expected true or false')) } } parseTrue_e () { if (this.char === CHAR_e) { return this.return(true) } else { throw this.error(new TomlError('Invalid boolean, expected true or false')) } } parseFalse_a () { if (this.char === CHAR_a) { this.consume() return this.next(this.parseFalse_l) } else { throw this.error(new TomlError('Invalid boolean, expected true or false')) } } parseFalse_l () { if (this.char === CHAR_l) { this.consume() return this.next(this.parseFalse_s) } else { throw this.error(new TomlError('Invalid boolean, expected true or false')) } } parseFalse_s () { if (this.char === CHAR_s) { this.consume() return this.next(this.parseFalse_e) } else { throw this.error(new TomlError('Invalid boolean, expected true or false')) } } parseFalse_e () { if (this.char === CHAR_e) { return this.return(false) } else { throw this.error(new TomlError('Invalid boolean, expected true or false')) } } /* INLINE LISTS */ parseInlineList () { if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) { return null } else if (this.char === Parser.END) { throw this.error(new TomlError('Unterminated inline array')) } else if (this.char === CHAR_NUM) { return this.call(this.parseComment) } else if (this.char === CHAR_RSQB) { return this.return(this.state.resultArr || InlineList()) } else { return this.callNow(this.parseValue, this.recordInlineListValue) } } recordInlineListValue (value) { if (this.state.resultArr) { const listType = this.state.resultArr[_contentType] const valueType = tomlType(value) if (listType !== valueType) { throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${listType} and ${valueType}`)) } } else { this.state.resultArr = InlineList(tomlType(value)) } if (isFloat(value) || isInteger(value)) { // unbox now that we've verified they're ok this.state.resultArr.push(value.valueOf()) } else { this.state.resultArr.push(value) } return this.goto(this.parseInlineListNext) } parseInlineListNext () { if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) { return null } else if (this.char === CHAR_NUM) { return this.call(this.parseComment) } else if (this.char === CHAR_COMMA) { return this.next(this.parseInlineList) } else if (this.char === CHAR_RSQB) { return this.goto(this.parseInlineList) } else { throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])')) } } /* INLINE TABLE */ parseInlineTable () { if (this.char === CHAR_SP || this.char === CTRL_I) { return null } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) { throw this.error(new TomlError('Unterminated inline array')) } else if (this.char === CHAR_RCUB) { return this.return(this.state.resultTable || InlineTable()) } else { if (!this.state.resultTable) this.state.resultTable = InlineTable() return this.callNow(this.parseAssign, this.recordInlineTableValue) } } recordInlineTableValue (kv) { let target = this.state.resultTable let finalKey = kv.key.pop() for (let kw of kv.key) { if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) { throw this.error(new TomlError("Can't redefine existing key")) } target = target[kw] = target[kw] || Table() } if (hasKey(target, finalKey)) { throw this.error(new TomlError("Can't redefine existing key")) } if (isInteger(kv.value) || isFloat(kv.value)) { target[finalKey] = kv.value.valueOf() } else { target[finalKey] = kv.value } return this.goto(this.parseInlineTableNext) } parseInlineTableNext () { if (this.char === CHAR_SP || this.char === CTRL_I) { return null } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) { throw this.error(new TomlError('Unterminated inline array')) } else if (this.char === CHAR_COMMA) { return this.next(this.parseInlineTable) } else if (this.char === CHAR_RCUB) { return this.goto(this.parseInlineTable) } else { throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])')) } } } return TOMLParser } /***/ }), /***/ 22950: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = parseAsync const TOMLParser = __webpack_require__(8676) const prettyError = __webpack_require__(22418) function parseAsync (str, opts) { if (!opts) opts = {} const index = 0 const blocksize = opts.blocksize || 40960 const parser = new TOMLParser() return new Promise((resolve, reject) => { setImmediate(parseAsyncNext, index, blocksize, resolve, reject) }) function parseAsyncNext (index, blocksize, resolve, reject) { if (index >= str.length) { try { return resolve(parser.finish()) } catch (err) { return reject(prettyError(err, str)) } } try { parser.parse(str.slice(index, index + blocksize)) setImmediate(parseAsyncNext, index + blocksize, blocksize, resolve, reject) } catch (err) { reject(prettyError(err, str)) } } } /***/ }), /***/ 22418: /***/ ((module) => { "use strict"; module.exports = prettyError function prettyError (err, buf) { /* istanbul ignore if */ if (err.pos == null || err.line == null) return err let msg = err.message msg += ` at row ${err.line + 1}, col ${err.col + 1}, pos ${err.pos}:\n` /* istanbul ignore else */ if (buf && buf.split) { const lines = buf.split(/\n/) const lineNumWidth = String(Math.min(lines.length, err.line + 3)).length let linePadding = ' ' while (linePadding.length < lineNumWidth) linePadding += ' ' for (let ii = Math.max(0, err.line - 1); ii < Math.min(lines.length, err.line + 2); ++ii) { let lineNum = String(ii + 1) if (lineNum.length < lineNumWidth) lineNum = ' ' + lineNum if (err.line === ii) { msg += lineNum + '> ' + lines[ii] + '\n' msg += linePadding + ' ' for (let hh = 0; hh < err.col; ++hh) { msg += ' ' } msg += '^\n' } else { msg += lineNum + ': ' + lines[ii] + '\n' } } } err.message = msg + '\n' return err } /***/ }), /***/ 6435: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = parseStream const stream = __webpack_require__(12781) const TOMLParser = __webpack_require__(8676) function parseStream (stm) { if (stm) { return parseReadable(stm) } else { return parseTransform(stm) } } function parseReadable (stm) { const parser = new TOMLParser() stm.setEncoding('utf8') return new Promise((resolve, reject) => { let readable let ended = false let errored = false function finish () { ended = true if (readable) return try { resolve(parser.finish()) } catch (err) { reject(err) } } function error (err) { errored = true reject(err) } stm.once('end', finish) stm.once('error', error) readNext() function readNext () { readable = true let data while ((data = stm.read()) !== null) { try { parser.parse(data) } catch (err) { return error(err) } } readable = false /* istanbul ignore if */ if (ended) return finish() /* istanbul ignore if */ if (errored) return stm.once('readable', readNext) } }) } function parseTransform () { const parser = new TOMLParser() return new stream.Transform({ objectMode: true, transform (chunk, encoding, cb) { try { parser.parse(chunk.toString(encoding)) } catch (err) { this.emit('error', err) } cb() }, flush (cb) { try { this.push(parser.finish()) } catch (err) { this.emit('error', err) } cb() } }) } /***/ }), /***/ 56530: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = parseString const TOMLParser = __webpack_require__(8676) const prettyError = __webpack_require__(22418) function parseString (str) { if (global.Buffer && global.Buffer.isBuffer(str)) { str = str.toString('utf8') } const parser = new TOMLParser() try { parser.parse(str) return parser.finish() } catch (err) { throw prettyError(err, str) } } /***/ }), /***/ 83512: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = __webpack_require__(56530) module.exports.async = __webpack_require__(22950) module.exports.stream = __webpack_require__(6435) module.exports.prettyError = __webpack_require__(22418) /***/ }), /***/ 36921: /***/ ((module) => { "use strict"; module.exports = stringify module.exports.value = stringifyInline function stringify (obj) { if (obj === null) throw typeError('null') if (obj === void (0)) throw typeError('undefined') if (typeof obj !== 'object') throw typeError(typeof obj) if (typeof obj.toJSON === 'function') obj = obj.toJSON() if (obj == null) return null const type = tomlType(obj) if (type !== 'table') throw typeError(type) return stringifyObject('', '', obj) } function typeError (type) { return new Error('Can only stringify objects, not ' + type) } function arrayOneTypeError () { return new Error("Array values can't have mixed types") } function getInlineKeys (obj) { return Object.keys(obj).filter(key => isInline(obj[key])) } function getComplexKeys (obj) { return Object.keys(obj).filter(key => !isInline(obj[key])) } function toJSON (obj) { let nobj = Array.isArray(obj) ? [] : Object.prototype.hasOwnProperty.call(obj, '__proto__') ? {['__proto__']: undefined} : {} for (let prop of Object.keys(obj)) { if (obj[prop] && typeof obj[prop].toJSON === 'function' && !('toISOString' in obj[prop])) { nobj[prop] = obj[prop].toJSON() } else { nobj[prop] = obj[prop] } } return nobj } function stringifyObject (prefix, indent, obj) { obj = toJSON(obj) var inlineKeys var complexKeys inlineKeys = getInlineKeys(obj) complexKeys = getComplexKeys(obj) var result = [] var inlineIndent = indent || '' inlineKeys.forEach(key => { var type = tomlType(obj[key]) if (type !== 'undefined' && type !== 'null') { result.push(inlineIndent + stringifyKey(key) + ' = ' + stringifyAnyInline(obj[key], true)) } }) if (result.length > 0) result.push('') var complexIndent = prefix && inlineKeys.length > 0 ? indent + ' ' : '' complexKeys.forEach(key => { result.push(stringifyComplex(prefix, complexIndent, key, obj[key])) }) return result.join('\n') } function isInline (value) { switch (tomlType(value)) { case 'undefined': case 'null': case 'integer': case 'nan': case 'float': case 'boolean': case 'string': case 'datetime': return true case 'array': return value.length === 0 || tomlType(value[0]) !== 'table' case 'table': return Object.keys(value).length === 0 /* istanbul ignore next */ default: return false } } function tomlType (value) { if (value === undefined) { return 'undefined' } else if (value === null) { return 'null' /* eslint-disable valid-typeof */ } else if (typeof value === 'bigint' || (Number.isInteger(value) && !Object.is(value, -0))) { return 'integer' } else if (typeof value === 'number') { return 'float' } else if (typeof value === 'boolean') { return 'boolean' } else if (typeof value === 'string') { return 'string' } else if ('toISOString' in value) { return isNaN(value) ? 'undefined' : 'datetime' } else if (Array.isArray(value)) { return 'array' } else { return 'table' } } function stringifyKey (key) { var keyStr = String(key) if (/^[-A-Za-z0-9_]+$/.test(keyStr)) { return keyStr } else { return stringifyBasicString(keyStr) } } function stringifyBasicString (str) { return '"' + escapeString(str).replace(/"/g, '\\"') + '"' } function stringifyLiteralString (str) { return "'" + str + "'" } function numpad (num, str) { while (str.length < num) str = '0' + str return str } function escapeString (str) { return str.replace(/\\/g, '\\\\') .replace(/[\b]/g, '\\b') .replace(/\t/g, '\\t') .replace(/\n/g, '\\n') .replace(/\f/g, '\\f') .replace(/\r/g, '\\r') /* eslint-disable no-control-regex */ .replace(/([\u0000-\u001f\u007f])/, c => '\\u' + numpad(4, c.codePointAt(0).toString(16))) /* eslint-enable no-control-regex */ } function stringifyMultilineString (str) { let escaped = str.split(/\n/).map(str => { return escapeString(str).replace(/"(?="")/g, '\\"') }).join('\n') if (escaped.slice(-1) === '"') escaped += '\\\n' return '"""\n' + escaped + '"""' } function stringifyAnyInline (value, multilineOk) { let type = tomlType(value) if (type === 'string') { if (multilineOk && /\n/.test(value)) { type = 'string-multiline' } else if (!/[\b\t\n\f\r']/.test(value) && /"/.test(value)) { type = 'string-literal' } } return stringifyInline(value, type) } function stringifyInline (value, type) { /* istanbul ignore if */ if (!type) type = tomlType(value) switch (type) { case 'string-multiline': return stringifyMultilineString(value) case 'string': return stringifyBasicString(value) case 'string-literal': return stringifyLiteralString(value) case 'integer': return stringifyInteger(value) case 'float': return stringifyFloat(value) case 'boolean': return stringifyBoolean(value) case 'datetime': return stringifyDatetime(value) case 'array': return stringifyInlineArray(value.filter(_ => tomlType(_) !== 'null' && tomlType(_) !== 'undefined' && tomlType(_) !== 'nan')) case 'table': return stringifyInlineTable(value) /* istanbul ignore next */ default: throw typeError(type) } } function stringifyInteger (value) { /* eslint-disable security/detect-unsafe-regex */ return String(value).replace(/\B(?=(\d{3})+(?!\d))/g, '_') } function stringifyFloat (value) { if (value === Infinity) { return 'inf' } else if (value === -Infinity) { return '-inf' } else if (Object.is(value, NaN)) { return 'nan' } else if (Object.is(value, -0)) { return '-0.0' } var chunks = String(value).split('.') var int = chunks[0] var dec = chunks[1] || 0 return stringifyInteger(int) + '.' + dec } function stringifyBoolean (value) { return String(value) } function stringifyDatetime (value) { return value.toISOString() } function isNumber (type) { return type === 'float' || type === 'integer' } function arrayType (values) { var contentType = tomlType(values[0]) if (values.every(_ => tomlType(_) === contentType)) return contentType // mixed integer/float, emit as floats if (values.every(_ => isNumber(tomlType(_)))) return 'float' return 'mixed' } function validateArray (values) { const type = arrayType(values) if (type === 'mixed') { throw arrayOneTypeError() } return type } function stringifyInlineArray (values) { values = toJSON(values) const type = validateArray(values) var result = '[' var stringified = values.map(_ => stringifyInline(_, type)) if (stringified.join(', ').length > 60 || /\n/.test(stringified)) { result += '\n ' + stringified.join(',\n ') + '\n' } else { result += ' ' + stringified.join(', ') + (stringified.length > 0 ? ' ' : '') } return result + ']' } function stringifyInlineTable (value) { value = toJSON(value) var result = [] Object.keys(value).forEach(key => { result.push(stringifyKey(key) + ' = ' + stringifyAnyInline(value[key], false)) }) return '{ ' + result.join(', ') + (result.length > 0 ? ' ' : '') + '}' } function stringifyComplex (prefix, indent, key, value) { var valueType = tomlType(value) /* istanbul ignore else */ if (valueType === 'array') { return stringifyArrayOfTables(prefix, indent, key, value) } else if (valueType === 'table') { return stringifyComplexTable(prefix, indent, key, value) } else { throw typeError(valueType) } } function stringifyArrayOfTables (prefix, indent, key, values) { values = toJSON(values) validateArray(values) var firstValueType = tomlType(values[0]) /* istanbul ignore if */ if (firstValueType !== 'table') throw typeError(firstValueType) var fullKey = prefix + stringifyKey(key) var result = '' values.forEach(table => { if (result.length > 0) result += '\n' result += indent + '[[' + fullKey + ']]\n' result += stringifyObject(fullKey + '.', indent, table) }) return result } function stringifyComplexTable (prefix, indent, key, value) { var fullKey = prefix + stringifyKey(key) var result = '' if (getInlineKeys(value).length > 0) { result += indent + '[' + fullKey + ']\n' } return result + stringifyObject(fullKey + '.', indent, value) } /***/ }), /***/ 5022: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; exports.parse = __webpack_require__(83512) exports.stringify = __webpack_require__(36921) /***/ }), /***/ 18185: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; const fs = __webpack_require__(57147); exports.FILE_SYSTEM_ADAPTER = { lstat: fs.lstat, stat: fs.stat, lstatSync: fs.lstatSync, statSync: fs.statSync, readdir: fs.readdir, readdirSync: fs.readdirSync }; function createFileSystemAdapter(fsMethods) { if (fsMethods === undefined) { return exports.FILE_SYSTEM_ADAPTER; } return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); } exports.createFileSystemAdapter = createFileSystemAdapter; /***/ }), /***/ 91107: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0; const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.'); if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) { throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`); } const MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10); const MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10); const SUPPORTED_MAJOR_VERSION = 10; const SUPPORTED_MINOR_VERSION = 10; const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION; const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION; /** * IS `true` for Node.js 10.10 and greater. */ exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR; /***/ }), /***/ 55923: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Settings = exports.scandirSync = exports.scandir = void 0; const async = __webpack_require__(31411); const sync = __webpack_require__(63953); const settings_1 = __webpack_require__(36913); exports.Settings = settings_1.default; function scandir(path, optionsOrSettingsOrCallback, callback) { if (typeof optionsOrSettingsOrCallback === 'function') { async.read(path, getSettings(), optionsOrSettingsOrCallback); return; } async.read(path, getSettings(optionsOrSettingsOrCallback), callback); } exports.scandir = scandir; function scandirSync(path, optionsOrSettings) { const settings = getSettings(optionsOrSettings); return sync.read(path, settings); } exports.scandirSync = scandirSync; function getSettings(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1.default) { return settingsOrOptions; } return new settings_1.default(settingsOrOptions); } /***/ }), /***/ 31411: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readdir = exports.readdirWithFileTypes = exports.read = void 0; const fsStat = __webpack_require__(66203); const rpl = __webpack_require__(54595); const constants_1 = __webpack_require__(91107); const utils = __webpack_require__(66582); const common = __webpack_require__(34587); function read(directory, settings, callback) { if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { readdirWithFileTypes(directory, settings, callback); return; } readdir(directory, settings, callback); } exports.read = read; function readdirWithFileTypes(directory, settings, callback) { settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => { if (readdirError !== null) { callFailureCallback(callback, readdirError); return; } const entries = dirents.map((dirent) => ({ dirent, name: dirent.name, path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) })); if (!settings.followSymbolicLinks) { callSuccessCallback(callback, entries); return; } const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings)); rpl(tasks, (rplError, rplEntries) => { if (rplError !== null) { callFailureCallback(callback, rplError); return; } callSuccessCallback(callback, rplEntries); }); }); } exports.readdirWithFileTypes = readdirWithFileTypes; function makeRplTaskEntry(entry, settings) { return (done) => { if (!entry.dirent.isSymbolicLink()) { done(null, entry); return; } settings.fs.stat(entry.path, (statError, stats) => { if (statError !== null) { if (settings.throwErrorOnBrokenSymbolicLink) { done(statError); return; } done(null, entry); return; } entry.dirent = utils.fs.createDirentFromStats(entry.name, stats); done(null, entry); }); }; } function readdir(directory, settings, callback) { settings.fs.readdir(directory, (readdirError, names) => { if (readdirError !== null) { callFailureCallback(callback, readdirError); return; } const tasks = names.map((name) => { const path = common.joinPathSegments(directory, name, settings.pathSegmentSeparator); return (done) => { fsStat.stat(path, settings.fsStatSettings, (error, stats) => { if (error !== null) { done(error); return; } const entry = { name, path, dirent: utils.fs.createDirentFromStats(name, stats) }; if (settings.stats) { entry.stats = stats; } done(null, entry); }); }; }); rpl(tasks, (rplError, entries) => { if (rplError !== null) { callFailureCallback(callback, rplError); return; } callSuccessCallback(callback, entries); }); }); } exports.readdir = readdir; function callFailureCallback(callback, error) { callback(error); } function callSuccessCallback(callback, result) { callback(null, result); } /***/ }), /***/ 34587: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.joinPathSegments = void 0; function joinPathSegments(a, b, separator) { /** * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). */ if (a.endsWith(separator)) { return a + b; } return a + separator + b; } exports.joinPathSegments = joinPathSegments; /***/ }), /***/ 63953: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readdir = exports.readdirWithFileTypes = exports.read = void 0; const fsStat = __webpack_require__(66203); const constants_1 = __webpack_require__(91107); const utils = __webpack_require__(66582); const common = __webpack_require__(34587); function read(directory, settings) { if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { return readdirWithFileTypes(directory, settings); } return readdir(directory, settings); } exports.read = read; function readdirWithFileTypes(directory, settings) { const dirents = settings.fs.readdirSync(directory, { withFileTypes: true }); return dirents.map((dirent) => { const entry = { dirent, name: dirent.name, path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) }; if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) { try { const stats = settings.fs.statSync(entry.path); entry.dirent = utils.fs.createDirentFromStats(entry.name, stats); } catch (error) { if (settings.throwErrorOnBrokenSymbolicLink) { throw error; } } } return entry; }); } exports.readdirWithFileTypes = readdirWithFileTypes; function readdir(directory, settings) { const names = settings.fs.readdirSync(directory); return names.map((name) => { const entryPath = common.joinPathSegments(directory, name, settings.pathSegmentSeparator); const stats = fsStat.statSync(entryPath, settings.fsStatSettings); const entry = { name, path: entryPath, dirent: utils.fs.createDirentFromStats(name, stats) }; if (settings.stats) { entry.stats = stats; } return entry; }); } exports.readdir = readdir; /***/ }), /***/ 36913: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const path = __webpack_require__(71017); const fsStat = __webpack_require__(66203); const fs = __webpack_require__(18185); class Settings { constructor(_options = {}) { this._options = _options; this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false); this.fs = fs.createFileSystemAdapter(this._options.fs); this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path.sep); this.stats = this._getValue(this._options.stats, false); this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); this.fsStatSettings = new fsStat.Settings({ followSymbolicLink: this.followSymbolicLinks, fs: this.fs, throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink }); } _getValue(option, value) { return option !== null && option !== void 0 ? option : value; } } exports["default"] = Settings; /***/ }), /***/ 70322: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createDirentFromStats = void 0; class DirentFromStats { constructor(name, stats) { this.name = name; this.isBlockDevice = stats.isBlockDevice.bind(stats); this.isCharacterDevice = stats.isCharacterDevice.bind(stats); this.isDirectory = stats.isDirectory.bind(stats); this.isFIFO = stats.isFIFO.bind(stats); this.isFile = stats.isFile.bind(stats); this.isSocket = stats.isSocket.bind(stats); this.isSymbolicLink = stats.isSymbolicLink.bind(stats); } } function createDirentFromStats(name, stats) { return new DirentFromStats(name, stats); } exports.createDirentFromStats = createDirentFromStats; /***/ }), /***/ 66582: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fs = void 0; const fs = __webpack_require__(70322); exports.fs = fs; /***/ }), /***/ 98980: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; const fs = __webpack_require__(57147); exports.FILE_SYSTEM_ADAPTER = { lstat: fs.lstat, stat: fs.stat, lstatSync: fs.lstatSync, statSync: fs.statSync }; function createFileSystemAdapter(fsMethods) { if (fsMethods === undefined) { return exports.FILE_SYSTEM_ADAPTER; } return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); } exports.createFileSystemAdapter = createFileSystemAdapter; /***/ }), /***/ 66203: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.statSync = exports.stat = exports.Settings = void 0; const async = __webpack_require__(2654); const sync = __webpack_require__(88946); const settings_1 = __webpack_require__(18328); exports.Settings = settings_1.default; function stat(path, optionsOrSettingsOrCallback, callback) { if (typeof optionsOrSettingsOrCallback === 'function') { async.read(path, getSettings(), optionsOrSettingsOrCallback); return; } async.read(path, getSettings(optionsOrSettingsOrCallback), callback); } exports.stat = stat; function statSync(path, optionsOrSettings) { const settings = getSettings(optionsOrSettings); return sync.read(path, settings); } exports.statSync = statSync; function getSettings(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1.default) { return settingsOrOptions; } return new settings_1.default(settingsOrOptions); } /***/ }), /***/ 2654: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.read = void 0; function read(path, settings, callback) { settings.fs.lstat(path, (lstatError, lstat) => { if (lstatError !== null) { callFailureCallback(callback, lstatError); return; } if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { callSuccessCallback(callback, lstat); return; } settings.fs.stat(path, (statError, stat) => { if (statError !== null) { if (settings.throwErrorOnBrokenSymbolicLink) { callFailureCallback(callback, statError); return; } callSuccessCallback(callback, lstat); return; } if (settings.markSymbolicLink) { stat.isSymbolicLink = () => true; } callSuccessCallback(callback, stat); }); }); } exports.read = read; function callFailureCallback(callback, error) { callback(error); } function callSuccessCallback(callback, result) { callback(null, result); } /***/ }), /***/ 88946: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.read = void 0; function read(path, settings) { const lstat = settings.fs.lstatSync(path); if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { return lstat; } try { const stat = settings.fs.statSync(path); if (settings.markSymbolicLink) { stat.isSymbolicLink = () => true; } return stat; } catch (error) { if (!settings.throwErrorOnBrokenSymbolicLink) { return lstat; } throw error; } } exports.read = read; /***/ }), /***/ 18328: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const fs = __webpack_require__(98980); class Settings { constructor(_options = {}) { this._options = _options; this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true); this.fs = fs.createFileSystemAdapter(this._options.fs); this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false); this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); } _getValue(option, value) { return option !== null && option !== void 0 ? option : value; } } exports["default"] = Settings; /***/ }), /***/ 45439: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Settings = exports.walkStream = exports.walkSync = exports.walk = void 0; const async_1 = __webpack_require__(9346); const stream_1 = __webpack_require__(40215); const sync_1 = __webpack_require__(64078); const settings_1 = __webpack_require__(48690); exports.Settings = settings_1.default; function walk(directory, optionsOrSettingsOrCallback, callback) { if (typeof optionsOrSettingsOrCallback === 'function') { new async_1.default(directory, getSettings()).read(optionsOrSettingsOrCallback); return; } new async_1.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback); } exports.walk = walk; function walkSync(directory, optionsOrSettings) { const settings = getSettings(optionsOrSettings); const provider = new sync_1.default(directory, settings); return provider.read(); } exports.walkSync = walkSync; function walkStream(directory, optionsOrSettings) { const settings = getSettings(optionsOrSettings); const provider = new stream_1.default(directory, settings); return provider.read(); } exports.walkStream = walkStream; function getSettings(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1.default) { return settingsOrOptions; } return new settings_1.default(settingsOrOptions); } /***/ }), /***/ 9346: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const async_1 = __webpack_require__(34714); class AsyncProvider { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._reader = new async_1.default(this._root, this._settings); this._storage = []; } read(callback) { this._reader.onError((error) => { callFailureCallback(callback, error); }); this._reader.onEntry((entry) => { this._storage.push(entry); }); this._reader.onEnd(() => { callSuccessCallback(callback, this._storage); }); this._reader.read(); } } exports["default"] = AsyncProvider; function callFailureCallback(callback, error) { callback(error); } function callSuccessCallback(callback, entries) { callback(null, entries); } /***/ }), /***/ 40215: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const stream_1 = __webpack_require__(12781); const async_1 = __webpack_require__(34714); class StreamProvider { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._reader = new async_1.default(this._root, this._settings); this._stream = new stream_1.Readable({ objectMode: true, read: () => { }, destroy: () => { if (!this._reader.isDestroyed) { this._reader.destroy(); } } }); } read() { this._reader.onError((error) => { this._stream.emit('error', error); }); this._reader.onEntry((entry) => { this._stream.push(entry); }); this._reader.onEnd(() => { this._stream.push(null); }); this._reader.read(); return this._stream; } } exports["default"] = StreamProvider; /***/ }), /***/ 64078: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const sync_1 = __webpack_require__(79555); class SyncProvider { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._reader = new sync_1.default(this._root, this._settings); } read() { return this._reader.read(); } } exports["default"] = SyncProvider; /***/ }), /***/ 34714: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const events_1 = __webpack_require__(82361); const fsScandir = __webpack_require__(55923); const fastq = __webpack_require__(10373); const common = __webpack_require__(26865); const reader_1 = __webpack_require__(85274); class AsyncReader extends reader_1.default { constructor(_root, _settings) { super(_root, _settings); this._settings = _settings; this._scandir = fsScandir.scandir; this._emitter = new events_1.EventEmitter(); this._queue = fastq(this._worker.bind(this), this._settings.concurrency); this._isFatalError = false; this._isDestroyed = false; this._queue.drain = () => { if (!this._isFatalError) { this._emitter.emit('end'); } }; } read() { this._isFatalError = false; this._isDestroyed = false; setImmediate(() => { this._pushToQueue(this._root, this._settings.basePath); }); return this._emitter; } get isDestroyed() { return this._isDestroyed; } destroy() { if (this._isDestroyed) { throw new Error('The reader is already destroyed'); } this._isDestroyed = true; this._queue.killAndDrain(); } onEntry(callback) { this._emitter.on('entry', callback); } onError(callback) { this._emitter.once('error', callback); } onEnd(callback) { this._emitter.once('end', callback); } _pushToQueue(directory, base) { const queueItem = { directory, base }; this._queue.push(queueItem, (error) => { if (error !== null) { this._handleError(error); } }); } _worker(item, done) { this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => { if (error !== null) { done(error, undefined); return; } for (const entry of entries) { this._handleEntry(entry, item.base); } done(null, undefined); }); } _handleError(error) { if (this._isDestroyed || !common.isFatalError(this._settings, error)) { return; } this._isFatalError = true; this._isDestroyed = true; this._emitter.emit('error', error); } _handleEntry(entry, base) { if (this._isDestroyed || this._isFatalError) { return; } const fullpath = entry.path; if (base !== undefined) { entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); } if (common.isAppliedFilter(this._settings.entryFilter, entry)) { this._emitEntry(entry); } if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); } } _emitEntry(entry) { this._emitter.emit('entry', entry); } } exports["default"] = AsyncReader; /***/ }), /***/ 26865: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.joinPathSegments = exports.replacePathSegmentSeparator = exports.isAppliedFilter = exports.isFatalError = void 0; function isFatalError(settings, error) { if (settings.errorFilter === null) { return true; } return !settings.errorFilter(error); } exports.isFatalError = isFatalError; function isAppliedFilter(filter, value) { return filter === null || filter(value); } exports.isAppliedFilter = isAppliedFilter; function replacePathSegmentSeparator(filepath, separator) { return filepath.split(/[/\\]/).join(separator); } exports.replacePathSegmentSeparator = replacePathSegmentSeparator; function joinPathSegments(a, b, separator) { if (a === '') { return b; } /** * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). */ if (a.endsWith(separator)) { return a + b; } return a + separator + b; } exports.joinPathSegments = joinPathSegments; /***/ }), /***/ 85274: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const common = __webpack_require__(26865); class Reader { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._root = common.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator); } } exports["default"] = Reader; /***/ }), /***/ 79555: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const fsScandir = __webpack_require__(55923); const common = __webpack_require__(26865); const reader_1 = __webpack_require__(85274); class SyncReader extends reader_1.default { constructor() { super(...arguments); this._scandir = fsScandir.scandirSync; this._storage = []; this._queue = new Set(); } read() { this._pushToQueue(this._root, this._settings.basePath); this._handleQueue(); return this._storage; } _pushToQueue(directory, base) { this._queue.add({ directory, base }); } _handleQueue() { for (const item of this._queue.values()) { this._handleDirectory(item.directory, item.base); } } _handleDirectory(directory, base) { try { const entries = this._scandir(directory, this._settings.fsScandirSettings); for (const entry of entries) { this._handleEntry(entry, base); } } catch (error) { this._handleError(error); } } _handleError(error) { if (!common.isFatalError(this._settings, error)) { return; } throw error; } _handleEntry(entry, base) { const fullpath = entry.path; if (base !== undefined) { entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); } if (common.isAppliedFilter(this._settings.entryFilter, entry)) { this._pushToStorage(entry); } if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); } } _pushToStorage(entry) { this._storage.push(entry); } } exports["default"] = SyncReader; /***/ }), /***/ 48690: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const path = __webpack_require__(71017); const fsScandir = __webpack_require__(55923); class Settings { constructor(_options = {}) { this._options = _options; this.basePath = this._getValue(this._options.basePath, undefined); this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY); this.deepFilter = this._getValue(this._options.deepFilter, null); this.entryFilter = this._getValue(this._options.entryFilter, null); this.errorFilter = this._getValue(this._options.errorFilter, null); this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path.sep); this.fsScandirSettings = new fsScandir.Settings({ followSymbolicLinks: this._options.followSymbolicLinks, fs: this._options.fs, pathSegmentSeparator: this._options.pathSegmentSeparator, stats: this._options.stats, throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink }); } _getValue(option, value) { return option !== null && option !== void 0 ? option : value; } } exports["default"] = Settings; /***/ }), /***/ 60350: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const {isString, getType, isPlainObject, isArrayOf, map} = __webpack_require__(74094) const isArray = Array.isArray const filter = name => !(/.+(Sync|Stream|Promise)$/.test(name)) /** * Promisify Node.js callback-style function * * @param {function} target – a callback-style function * @param {any} [ctx = null] * * @return {function} - promised function * * @example * * import fs from "fs" * * const readFile = promisify(fs.readFile) * * const onFulfilled = content => console.log(String(content)) * * const onRejected = err => console.error(err) * * readFile(__filename).then(onFulfilled, onRejected) */ function promisify(target, ctx = null) { if (typeof target !== "function") { throw TypeError( `Expected target function. Received ${getType(target)}` ) } return function(...args) { ctx || (ctx = this) return new Promise((resolve, reject) => { const fulfill = (err, res) => err ? reject(err) : resolve(res) target.call(ctx, ...args, fulfill) }) } } /** * Promisify all given methods * * @param {object} targets - object with the pairs of name => target * @param {any} [ctx = null] * * @return {object} */ function all(targets, ctx) { if (!isPlainObject(targets)) { throw new TypeError( `Expected a plain object as targets. Received ${getType(targets)}` ) } return map(targets, (fn, name) => filter(name) ? promisify(fn, ctx) : fn) } /** * @param {object} targets * @param {string[]} list * @param {any} [ctx = null] * * @return {object} */ function some(targets, list, ctx) { if (!isPlainObject(targets)) { throw new TypeError( `Expected a plain object as targets. Received ${getType(targets)}` ) } if (!isArray(list)) { throw new TypeError(`Expected list as an array. Received ${getType(list)}`) } if (!isArrayOf(list, isString)) { throw new TypeError("Each element in the list should be a string.") } return map( targets, (fn, name) => ( filter(name) && list.includes(name) ? promisify(fn, ctx) : fn ) ) } /** * @param {object} targets * @param {string[]} list * @param {any} [ctx = null] * * @return {object} */ function except(targets, list, ctx) { if (!isPlainObject(targets)) { throw new TypeError( `Expected a plain object as targets. Received ${getType(targets)}` ) } if (!isArray(list)) { throw new TypeError(`Expected list as an array. Received ${getType(list)}`) } if (!isArrayOf(list, isString)) { throw new TypeError("Each element in the list should be a string.") } return map( targets, (fn, name) => ( filter(name) && !(list.includes(name)) ? promisify(fn, ctx) : fn ) ) } module.exports = promisify module.exports["default"] = promisify module.exports.all = all module.exports.some = some module.exports.except = except /***/ }), /***/ 74094: /***/ ((module) => { const keys = Object.keys const toString = val => Object.prototype.toString.call(val) const getType = val => toString(val).slice(8, -1).toLowerCase() const isString = val => typeof val === "string" || getType(val) === "string" // Based ob lodash/isPlainObject function isPlainObject(val) { if (getType(val) !== "object") { return false } const pp = Object.getPrototypeOf(val) if (pp === null || pp === void 0) { return true } const Ctor = pp.constructor && pp.constructor.toString() return Ctor === Object.toString() } function isArrayOf(arr, predicate, ctx = null) { for (const [key, val] of arr.entries()) { if (predicate.call(ctx, val, key, arr) === false) { return false } } return true } function map(obj, fn) { const res = {} for (const key of keys(obj)) { const val = obj[key] res[key] = fn(val, key, obj) } return res } module.exports = {isArrayOf, getType, isString, isPlainObject, map} /***/ }), /***/ 91332: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createBase32HashFromFile = exports.createBase32Hash = void 0; const crypto_1 = __importDefault(__webpack_require__(6113)); const fs_1 = __importDefault(__webpack_require__(57147)); const rfc4648_1 = __webpack_require__(55352); function createBase32Hash(str) { return rfc4648_1.base32.stringify(crypto_1.default.createHash('md5').update(str).digest()).replace(/(=+)$/, '').toLowerCase(); } exports.createBase32Hash = createBase32Hash; async function createBase32HashFromFile(file) { const content = await fs_1.default.promises.readFile(file, 'utf8'); return createBase32Hash(content.split('\r\n').join('\n')); } exports.createBase32HashFromFile = createBase32HashFromFile; //# sourceMappingURL=index.js.map /***/ }), /***/ 80657: /***/ ((module, exports) => { "use strict"; /// /// /// Object.defineProperty(exports, "__esModule", ({ value: true })); const typedArrayTypeNames = [ 'Int8Array', 'Uint8Array', 'Uint8ClampedArray', 'Int16Array', 'Uint16Array', 'Int32Array', 'Uint32Array', 'Float32Array', 'Float64Array', 'BigInt64Array', 'BigUint64Array' ]; function isTypedArrayName(name) { return typedArrayTypeNames.includes(name); } const objectTypeNames = [ 'Function', 'Generator', 'AsyncGenerator', 'GeneratorFunction', 'AsyncGeneratorFunction', 'AsyncFunction', 'Observable', 'Array', 'Buffer', 'Object', 'RegExp', 'Date', 'Error', 'Map', 'Set', 'WeakMap', 'WeakSet', 'ArrayBuffer', 'SharedArrayBuffer', 'DataView', 'Promise', 'URL', 'HTMLElement', ...typedArrayTypeNames ]; function isObjectTypeName(name) { return objectTypeNames.includes(name); } const primitiveTypeNames = [ 'null', 'undefined', 'string', 'number', 'bigint', 'boolean', 'symbol' ]; function isPrimitiveTypeName(name) { return primitiveTypeNames.includes(name); } // eslint-disable-next-line @typescript-eslint/ban-types function isOfType(type) { return (value) => typeof value === type; } const { toString } = Object.prototype; const getObjectType = (value) => { const objectTypeName = toString.call(value).slice(8, -1); if (/HTML\w+Element/.test(objectTypeName) && is.domElement(value)) { return 'HTMLElement'; } if (isObjectTypeName(objectTypeName)) { return objectTypeName; } return undefined; }; const isObjectOfType = (type) => (value) => getObjectType(value) === type; function is(value) { if (value === null) { return 'null'; } switch (typeof value) { case 'undefined': return 'undefined'; case 'string': return 'string'; case 'number': return 'number'; case 'boolean': return 'boolean'; case 'function': return 'Function'; case 'bigint': return 'bigint'; case 'symbol': return 'symbol'; default: } if (is.observable(value)) { return 'Observable'; } if (is.array(value)) { return 'Array'; } if (is.buffer(value)) { return 'Buffer'; } const tagType = getObjectType(value); if (tagType) { return tagType; } if (value instanceof String || value instanceof Boolean || value instanceof Number) { throw new TypeError('Please don\'t use object wrappers for primitive types'); } return 'Object'; } is.undefined = isOfType('undefined'); is.string = isOfType('string'); const isNumberType = isOfType('number'); is.number = (value) => isNumberType(value) && !is.nan(value); is.bigint = isOfType('bigint'); // eslint-disable-next-line @typescript-eslint/ban-types is.function_ = isOfType('function'); is.null_ = (value) => value === null; is.class_ = (value) => is.function_(value) && value.toString().startsWith('class '); is.boolean = (value) => value === true || value === false; is.symbol = isOfType('symbol'); is.numericString = (value) => is.string(value) && !is.emptyStringOrWhitespace(value) && !Number.isNaN(Number(value)); is.array = (value, assertion) => { if (!Array.isArray(value)) { return false; } if (!is.function_(assertion)) { return true; } return value.every(assertion); }; is.buffer = (value) => { var _a, _b, _c, _d; return (_d = (_c = (_b = (_a = value) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.isBuffer) === null || _c === void 0 ? void 0 : _c.call(_b, value)) !== null && _d !== void 0 ? _d : false; }; is.nullOrUndefined = (value) => is.null_(value) || is.undefined(value); is.object = (value) => !is.null_(value) && (typeof value === 'object' || is.function_(value)); is.iterable = (value) => { var _a; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a[Symbol.iterator]); }; is.asyncIterable = (value) => { var _a; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a[Symbol.asyncIterator]); }; is.generator = (value) => is.iterable(value) && is.function_(value.next) && is.function_(value.throw); is.asyncGenerator = (value) => is.asyncIterable(value) && is.function_(value.next) && is.function_(value.throw); is.nativePromise = (value) => isObjectOfType('Promise')(value); const hasPromiseAPI = (value) => { var _a, _b; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a.then) && is.function_((_b = value) === null || _b === void 0 ? void 0 : _b.catch); }; is.promise = (value) => is.nativePromise(value) || hasPromiseAPI(value); is.generatorFunction = isObjectOfType('GeneratorFunction'); is.asyncGeneratorFunction = (value) => getObjectType(value) === 'AsyncGeneratorFunction'; is.asyncFunction = (value) => getObjectType(value) === 'AsyncFunction'; // eslint-disable-next-line no-prototype-builtins, @typescript-eslint/ban-types is.boundFunction = (value) => is.function_(value) && !value.hasOwnProperty('prototype'); is.regExp = isObjectOfType('RegExp'); is.date = isObjectOfType('Date'); is.error = isObjectOfType('Error'); is.map = (value) => isObjectOfType('Map')(value); is.set = (value) => isObjectOfType('Set')(value); is.weakMap = (value) => isObjectOfType('WeakMap')(value); is.weakSet = (value) => isObjectOfType('WeakSet')(value); is.int8Array = isObjectOfType('Int8Array'); is.uint8Array = isObjectOfType('Uint8Array'); is.uint8ClampedArray = isObjectOfType('Uint8ClampedArray'); is.int16Array = isObjectOfType('Int16Array'); is.uint16Array = isObjectOfType('Uint16Array'); is.int32Array = isObjectOfType('Int32Array'); is.uint32Array = isObjectOfType('Uint32Array'); is.float32Array = isObjectOfType('Float32Array'); is.float64Array = isObjectOfType('Float64Array'); is.bigInt64Array = isObjectOfType('BigInt64Array'); is.bigUint64Array = isObjectOfType('BigUint64Array'); is.arrayBuffer = isObjectOfType('ArrayBuffer'); is.sharedArrayBuffer = isObjectOfType('SharedArrayBuffer'); is.dataView = isObjectOfType('DataView'); is.directInstanceOf = (instance, class_) => Object.getPrototypeOf(instance) === class_.prototype; is.urlInstance = (value) => isObjectOfType('URL')(value); is.urlString = (value) => { if (!is.string(value)) { return false; } try { new URL(value); // eslint-disable-line no-new return true; } catch (_a) { return false; } }; // TODO: Use the `not` operator with a type guard here when it's available. // Example: `is.truthy = (value: unknown): value is (not false | not 0 | not '' | not undefined | not null) => Boolean(value);` is.truthy = (value) => Boolean(value); // Example: `is.falsy = (value: unknown): value is (not true | 0 | '' | undefined | null) => Boolean(value);` is.falsy = (value) => !value; is.nan = (value) => Number.isNaN(value); is.primitive = (value) => is.null_(value) || isPrimitiveTypeName(typeof value); is.integer = (value) => Number.isInteger(value); is.safeInteger = (value) => Number.isSafeInteger(value); is.plainObject = (value) => { // From: https://github.com/sindresorhus/is-plain-obj/blob/main/index.js if (toString.call(value) !== '[object Object]') { return false; } const prototype = Object.getPrototypeOf(value); return prototype === null || prototype === Object.getPrototypeOf({}); }; is.typedArray = (value) => isTypedArrayName(getObjectType(value)); const isValidLength = (value) => is.safeInteger(value) && value >= 0; is.arrayLike = (value) => !is.nullOrUndefined(value) && !is.function_(value) && isValidLength(value.length); is.inRange = (value, range) => { if (is.number(range)) { return value >= Math.min(0, range) && value <= Math.max(range, 0); } if (is.array(range) && range.length === 2) { return value >= Math.min(...range) && value <= Math.max(...range); } throw new TypeError(`Invalid range: ${JSON.stringify(range)}`); }; const NODE_TYPE_ELEMENT = 1; const DOM_PROPERTIES_TO_CHECK = [ 'innerHTML', 'ownerDocument', 'style', 'attributes', 'nodeValue' ]; is.domElement = (value) => { return is.object(value) && value.nodeType === NODE_TYPE_ELEMENT && is.string(value.nodeName) && !is.plainObject(value) && DOM_PROPERTIES_TO_CHECK.every(property => property in value); }; is.observable = (value) => { var _a, _b, _c, _d; if (!value) { return false; } // eslint-disable-next-line no-use-extend-native/no-use-extend-native if (value === ((_b = (_a = value)[Symbol.observable]) === null || _b === void 0 ? void 0 : _b.call(_a))) { return true; } if (value === ((_d = (_c = value)['@@observable']) === null || _d === void 0 ? void 0 : _d.call(_c))) { return true; } return false; }; is.nodeStream = (value) => is.object(value) && is.function_(value.pipe) && !is.observable(value); is.infinite = (value) => value === Infinity || value === -Infinity; const isAbsoluteMod2 = (remainder) => (value) => is.integer(value) && Math.abs(value % 2) === remainder; is.evenInteger = isAbsoluteMod2(0); is.oddInteger = isAbsoluteMod2(1); is.emptyArray = (value) => is.array(value) && value.length === 0; is.nonEmptyArray = (value) => is.array(value) && value.length > 0; is.emptyString = (value) => is.string(value) && value.length === 0; // TODO: Use `not ''` when the `not` operator is available. is.nonEmptyString = (value) => is.string(value) && value.length > 0; const isWhiteSpaceString = (value) => is.string(value) && !/\S/.test(value); is.emptyStringOrWhitespace = (value) => is.emptyString(value) || isWhiteSpaceString(value); is.emptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length === 0; // TODO: Use `not` operator here to remove `Map` and `Set` from type guard: // - https://github.com/Microsoft/TypeScript/pull/29317 is.nonEmptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length > 0; is.emptySet = (value) => is.set(value) && value.size === 0; is.nonEmptySet = (value) => is.set(value) && value.size > 0; is.emptyMap = (value) => is.map(value) && value.size === 0; is.nonEmptyMap = (value) => is.map(value) && value.size > 0; const predicateOnArray = (method, predicate, values) => { if (!is.function_(predicate)) { throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`); } if (values.length === 0) { throw new TypeError('Invalid number of values'); } return method.call(values, predicate); }; is.any = (predicate, ...values) => { const predicates = is.array(predicate) ? predicate : [predicate]; return predicates.some(singlePredicate => predicateOnArray(Array.prototype.some, singlePredicate, values)); }; is.all = (predicate, ...values) => predicateOnArray(Array.prototype.every, predicate, values); const assertType = (condition, description, value, options = {}) => { if (!condition) { const { multipleValues } = options; const valuesMessage = multipleValues ? `received values of types ${[ ...new Set(value.map(singleValue => `\`${is(singleValue)}\``)) ].join(', ')}` : `received value of type \`${is(value)}\``; throw new TypeError(`Expected value which is \`${description}\`, ${valuesMessage}.`); } }; exports.assert = { // Unknowns. undefined: (value) => assertType(is.undefined(value), 'undefined', value), string: (value) => assertType(is.string(value), 'string', value), number: (value) => assertType(is.number(value), 'number', value), bigint: (value) => assertType(is.bigint(value), 'bigint', value), // eslint-disable-next-line @typescript-eslint/ban-types function_: (value) => assertType(is.function_(value), 'Function', value), null_: (value) => assertType(is.null_(value), 'null', value), class_: (value) => assertType(is.class_(value), "Class" /* class_ */, value), boolean: (value) => assertType(is.boolean(value), 'boolean', value), symbol: (value) => assertType(is.symbol(value), 'symbol', value), numericString: (value) => assertType(is.numericString(value), "string with a number" /* numericString */, value), array: (value, assertion) => { const assert = assertType; assert(is.array(value), 'Array', value); if (assertion) { value.forEach(assertion); } }, buffer: (value) => assertType(is.buffer(value), 'Buffer', value), nullOrUndefined: (value) => assertType(is.nullOrUndefined(value), "null or undefined" /* nullOrUndefined */, value), object: (value) => assertType(is.object(value), 'Object', value), iterable: (value) => assertType(is.iterable(value), "Iterable" /* iterable */, value), asyncIterable: (value) => assertType(is.asyncIterable(value), "AsyncIterable" /* asyncIterable */, value), generator: (value) => assertType(is.generator(value), 'Generator', value), asyncGenerator: (value) => assertType(is.asyncGenerator(value), 'AsyncGenerator', value), nativePromise: (value) => assertType(is.nativePromise(value), "native Promise" /* nativePromise */, value), promise: (value) => assertType(is.promise(value), 'Promise', value), generatorFunction: (value) => assertType(is.generatorFunction(value), 'GeneratorFunction', value), asyncGeneratorFunction: (value) => assertType(is.asyncGeneratorFunction(value), 'AsyncGeneratorFunction', value), // eslint-disable-next-line @typescript-eslint/ban-types asyncFunction: (value) => assertType(is.asyncFunction(value), 'AsyncFunction', value), // eslint-disable-next-line @typescript-eslint/ban-types boundFunction: (value) => assertType(is.boundFunction(value), 'Function', value), regExp: (value) => assertType(is.regExp(value), 'RegExp', value), date: (value) => assertType(is.date(value), 'Date', value), error: (value) => assertType(is.error(value), 'Error', value), map: (value) => assertType(is.map(value), 'Map', value), set: (value) => assertType(is.set(value), 'Set', value), weakMap: (value) => assertType(is.weakMap(value), 'WeakMap', value), weakSet: (value) => assertType(is.weakSet(value), 'WeakSet', value), int8Array: (value) => assertType(is.int8Array(value), 'Int8Array', value), uint8Array: (value) => assertType(is.uint8Array(value), 'Uint8Array', value), uint8ClampedArray: (value) => assertType(is.uint8ClampedArray(value), 'Uint8ClampedArray', value), int16Array: (value) => assertType(is.int16Array(value), 'Int16Array', value), uint16Array: (value) => assertType(is.uint16Array(value), 'Uint16Array', value), int32Array: (value) => assertType(is.int32Array(value), 'Int32Array', value), uint32Array: (value) => assertType(is.uint32Array(value), 'Uint32Array', value), float32Array: (value) => assertType(is.float32Array(value), 'Float32Array', value), float64Array: (value) => assertType(is.float64Array(value), 'Float64Array', value), bigInt64Array: (value) => assertType(is.bigInt64Array(value), 'BigInt64Array', value), bigUint64Array: (value) => assertType(is.bigUint64Array(value), 'BigUint64Array', value), arrayBuffer: (value) => assertType(is.arrayBuffer(value), 'ArrayBuffer', value), sharedArrayBuffer: (value) => assertType(is.sharedArrayBuffer(value), 'SharedArrayBuffer', value), dataView: (value) => assertType(is.dataView(value), 'DataView', value), urlInstance: (value) => assertType(is.urlInstance(value), 'URL', value), urlString: (value) => assertType(is.urlString(value), "string with a URL" /* urlString */, value), truthy: (value) => assertType(is.truthy(value), "truthy" /* truthy */, value), falsy: (value) => assertType(is.falsy(value), "falsy" /* falsy */, value), nan: (value) => assertType(is.nan(value), "NaN" /* nan */, value), primitive: (value) => assertType(is.primitive(value), "primitive" /* primitive */, value), integer: (value) => assertType(is.integer(value), "integer" /* integer */, value), safeInteger: (value) => assertType(is.safeInteger(value), "integer" /* safeInteger */, value), plainObject: (value) => assertType(is.plainObject(value), "plain object" /* plainObject */, value), typedArray: (value) => assertType(is.typedArray(value), "TypedArray" /* typedArray */, value), arrayLike: (value) => assertType(is.arrayLike(value), "array-like" /* arrayLike */, value), domElement: (value) => assertType(is.domElement(value), "HTMLElement" /* domElement */, value), observable: (value) => assertType(is.observable(value), 'Observable', value), nodeStream: (value) => assertType(is.nodeStream(value), "Node.js Stream" /* nodeStream */, value), infinite: (value) => assertType(is.infinite(value), "infinite number" /* infinite */, value), emptyArray: (value) => assertType(is.emptyArray(value), "empty array" /* emptyArray */, value), nonEmptyArray: (value) => assertType(is.nonEmptyArray(value), "non-empty array" /* nonEmptyArray */, value), emptyString: (value) => assertType(is.emptyString(value), "empty string" /* emptyString */, value), nonEmptyString: (value) => assertType(is.nonEmptyString(value), "non-empty string" /* nonEmptyString */, value), emptyStringOrWhitespace: (value) => assertType(is.emptyStringOrWhitespace(value), "empty string or whitespace" /* emptyStringOrWhitespace */, value), emptyObject: (value) => assertType(is.emptyObject(value), "empty object" /* emptyObject */, value), nonEmptyObject: (value) => assertType(is.nonEmptyObject(value), "non-empty object" /* nonEmptyObject */, value), emptySet: (value) => assertType(is.emptySet(value), "empty set" /* emptySet */, value), nonEmptySet: (value) => assertType(is.nonEmptySet(value), "non-empty set" /* nonEmptySet */, value), emptyMap: (value) => assertType(is.emptyMap(value), "empty map" /* emptyMap */, value), nonEmptyMap: (value) => assertType(is.nonEmptyMap(value), "non-empty map" /* nonEmptyMap */, value), // Numbers. evenInteger: (value) => assertType(is.evenInteger(value), "even integer" /* evenInteger */, value), oddInteger: (value) => assertType(is.oddInteger(value), "odd integer" /* oddInteger */, value), // Two arguments. directInstanceOf: (instance, class_) => assertType(is.directInstanceOf(instance, class_), "T" /* directInstanceOf */, instance), inRange: (value, range) => assertType(is.inRange(value, range), "in range" /* inRange */, value), // Variadic functions. any: (predicate, ...values) => { return assertType(is.any(predicate, ...values), "predicate returns truthy for any value" /* any */, values, { multipleValues: true }); }, all: (predicate, ...values) => assertType(is.all(predicate, ...values), "predicate returns truthy for all values" /* all */, values, { multipleValues: true }) }; // Some few keywords are reserved, but we'll populate them for Node.js users // See https://github.com/Microsoft/TypeScript/issues/2536 Object.defineProperties(is, { class: { value: is.class_ }, function: { value: is.function_ }, null: { value: is.null_ } }); Object.defineProperties(exports.assert, { class: { value: exports.assert.class_ }, function: { value: exports.assert.function_ }, null: { value: exports.assert.null_ } }); exports["default"] = is; // For CommonJS default export support module.exports = is; module.exports["default"] = is; module.exports.assert = exports.assert; /***/ }), /***/ 65266: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.legacyCommon = exports.legacyMonitor = exports.legacyPlugin = void 0; const legacy_1 = __webpack_require__(83888); Object.defineProperty(exports, "legacyPlugin", ({ enumerable: true, get: function () { return legacy_1.plugin; } })); Object.defineProperty(exports, "legacyMonitor", ({ enumerable: true, get: function () { return legacy_1.monitor; } })); Object.defineProperty(exports, "legacyCommon", ({ enumerable: true, get: function () { return legacy_1.common; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 78752: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); //# sourceMappingURL=common.js.map /***/ }), /***/ 83888: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.common = exports.monitor = exports.plugin = void 0; const plugin = __webpack_require__(88904); exports.plugin = plugin; const monitor = __webpack_require__(65861); exports.monitor = monitor; const common = __webpack_require__(78752); exports.common = common; //# sourceMappingURL=index.js.map /***/ }), /***/ 65861: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); //# sourceMappingURL=monitor.js.map /***/ }), /***/ 88904: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isMultiResult = exports.isMultiSubProject = exports.adaptSingleProjectPlugin = void 0; function adaptSingleProjectPlugin(plugin) { return { inspect: (root, targetFile, options) => { if (options && isMultiSubProject(options)) { const name = plugin.pluginName ? plugin.pluginName() : '[unknown]'; throw new Error(`Plugin ${name} does not support scanning multiple sub-projects`); } else { return plugin.inspect(root, targetFile, options); } } }; } exports.adaptSingleProjectPlugin = adaptSingleProjectPlugin; function isMultiSubProject(options) { return options.allSubProjects; } exports.isMultiSubProject = isMultiSubProject; function isMultiResult(res) { return !!res.scannedProjects; } exports.isMultiResult = isMultiResult; //# sourceMappingURL=plugin.js.map /***/ }), /***/ 84537: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const lockfile_parser_1 = __webpack_require__(7023); exports.LockfileParser = lockfile_parser_1.default; //# sourceMappingURL=index.js.map /***/ }), /***/ 7023: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const fs = __webpack_require__(57147); const path = __webpack_require__(71017); const yaml = __webpack_require__(93320); const dep_graph_1 = __webpack_require__(14010); const utils_1 = __webpack_require__(43033); class LockfileParser { constructor(hash, rootPkgInfo) { this.rootPkgInfo = undefined; this.rootPkgInfo = rootPkgInfo; this.internalData = hash; } static async readFile(lockfilePath) { const rootName = path.basename(path.dirname(path.resolve(lockfilePath))); return new Promise((resolve, reject) => { fs.readFile(lockfilePath, { encoding: 'utf8' }, (err, fileContents) => { if (err) { reject(err); } try { const parser = this.readContents(fileContents, { name: rootName, version: '0.0.0', }); resolve(parser); } catch (err) { reject(err); } }); }); } static readFileSync(lockfilePath) { const fileContents = fs.readFileSync(lockfilePath, 'utf8'); const rootName = path.basename(path.dirname(path.resolve(lockfilePath))); return this.readContents(fileContents, { name: rootName, version: '0.0.0', }); } static readContents(contents, rootPkgInfo) { return new LockfileParser(yaml.safeLoad(contents), rootPkgInfo); } toDepGraph() { const builder = new dep_graph_1.DepGraphBuilder(this.pkgManager, this.rootPkgInfo); const allDeps = {}; // Add all package nodes first, but collect dependencies this.internalData.PODS.forEach((elem) => { let pkgInfo; let pkgDeps; if (typeof elem === 'string') { // When there are NO dependencies. This equals in yaml e.g. // - Expecta (1.0.5) pkgInfo = utils_1.pkgInfoFromSpecificationString(elem); pkgDeps = []; } else { // When there are dependencies. This equals in yaml e.g. // - React/Core (0.59.2): // - yoga (= 0.59.2.React) const objKey = Object.keys(elem)[0]; pkgInfo = utils_1.pkgInfoFromSpecificationString(objKey); pkgDeps = elem[objKey].map(utils_1.pkgInfoFromDependencyString); } const nodeId = this.nodeIdForPkgInfo(pkgInfo); builder.addPkgNode(pkgInfo, nodeId, { labels: this.nodeInfoLabelsForPod(pkgInfo.name), }); allDeps[nodeId] = pkgDeps; }); // Connect explicitly in the manifest (`Podfile`) // declared dependencies to the root node. this.internalData.DEPENDENCIES.map(utils_1.pkgInfoFromDependencyString).forEach((pkgInfo) => { builder.connectDep(builder.rootNodeId, this.nodeIdForPkgInfo(pkgInfo)); }); // Now we can start to connect dependencies Object.entries(allDeps).forEach(([nodeId, pkgDeps]) => pkgDeps.forEach((pkgInfo) => { const depNodeId = this.nodeIdForPkgInfo(pkgInfo); if (!allDeps[depNodeId]) { // The pod is not a direct dependency of any targets of the integration, // which can happen for platform-specific transitives, when their platform // is not used in any target. (e.g. PromiseKit/UIKit is iOS-specific and is // a transitive of PromiseKit, but won't be included for a macOS project.) return; } builder.connectDep(nodeId, depNodeId); })); return builder.build(); } /// CocoaPods guarantees that every pod is only present in one version, /// so we can use just the pod name as node ID. nodeIdForPkgInfo(pkgInfo) { return pkgInfo.name; } /// Gathers relevant info from the lockfile and transform /// them into the expected labels data structure. nodeInfoLabelsForPod(podName) { let nodeInfoLabels = { checksum: this.checksumForPod(podName), }; const repository = this.repositoryForPod(podName); if (repository) { nodeInfoLabels = Object.assign(Object.assign({}, nodeInfoLabels), { repository }); } const externalSourceInfo = this.externalSourceInfoForPod(podName); if (externalSourceInfo) { nodeInfoLabels = Object.assign(Object.assign({}, nodeInfoLabels), { externalSourcePodspec: externalSourceInfo[':podspec'], externalSourcePath: externalSourceInfo[':path'], externalSourceGit: externalSourceInfo[':git'], externalSourceTag: externalSourceInfo[':tag'], externalSourceCommit: externalSourceInfo[':commit'], externalSourceBranch: externalSourceInfo[':branch'] }); } const checkoutOptions = this.checkoutOptionsForPod(podName); if (checkoutOptions) { nodeInfoLabels = Object.assign(Object.assign({}, nodeInfoLabels), { checkoutOptionsPodspec: checkoutOptions[':podspec'], checkoutOptionsPath: checkoutOptions[':path'], checkoutOptionsGit: checkoutOptions[':git'], checkoutOptionsTag: checkoutOptions[':tag'], checkoutOptionsCommit: checkoutOptions[':commit'], checkoutOptionsBranch: checkoutOptions[':branch'] }); } // Sanitize labels by removing null fields // (as they don't survive a serialization/parse cycle and break tests) Object.entries(nodeInfoLabels).forEach(([key, value]) => { if (value === null || value === undefined) { delete nodeInfoLabels[key]; } }); return nodeInfoLabels; } /// The checksum of the pod. checksumForPod(podName) { const rootName = utils_1.rootSpecName(podName); return this.internalData['SPEC CHECKSUMS'][rootName]; } /// This can be either an URL or the local repository name. repositoryForPod(podName) { // Older Podfile.lock might not have this section yet. const specRepos = this.internalData['SPEC REPOS']; if (!specRepos) { return undefined; } const rootName = utils_1.rootSpecName(podName); const specRepoEntry = Object.entries(specRepos).find(([, deps]) => deps.includes(rootName)); if (specRepoEntry) { return specRepoEntry[0]; } return undefined; } /// Extracts the external source info for a given pod, if there is any. externalSourceInfoForPod(podName) { // Older Podfile.lock might not have this section yet. const externalSources = this.internalData['EXTERNAL SOURCES']; if (!externalSources) { return undefined; } const externalSourceEntry = externalSources[utils_1.rootSpecName(podName)]; if (externalSourceEntry) { return externalSourceEntry; } return undefined; } /// Extracts the checkout options for a given pod, if there is any. checkoutOptionsForPod(podName) { // Older Podfile.lock might not have this section yet. const checkoutOptions = this.internalData['CHECKOUT OPTIONS']; if (!checkoutOptions) { return undefined; } const checkoutOptionsEntry = checkoutOptions[utils_1.rootSpecName(podName)]; if (checkoutOptionsEntry) { return checkoutOptionsEntry; } return undefined; } get repositories() { // Older Podfile.lock might not have this section yet. const specRepos = this.internalData['SPEC REPOS']; if (!specRepos) { return []; } return Object.keys(specRepos).map((nameOrUrl) => { return { alias: nameOrUrl }; }); } get pkgManager() { return { name: 'cocoapods', version: this.cocoapodsVersion, repositories: this.repositories, }; } /// The CocoaPods version encoded in the lockfile which was used to /// create this resolution. get cocoapodsVersion() { return this.internalData.COCOAPODS || 'unknown'; } /// The checksum of the Podfile, which was used when resolving this integration. /// - Note: this was not tracked by earlier versions of CocoaPods. get podfileChecksum() { return this.internalData['PODFILE CHECKSUM']; } } exports["default"] = LockfileParser; //# sourceMappingURL=lockfile-parser.js.map /***/ }), /***/ 43033: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /// e.g. Adjust (4.17.1) /// Adjust/Core (4.17.1) function pkgInfoFromSpecificationString(stringRepresentation) { const match = stringRepresentation.match(/^((?:\s?[^\s(])+)(?: \((.+)\))?$/); if (!match) { throw new Error('Invalid string representation for a ' + `specification: \`${stringRepresentation}\`. ` + 'The string representation should include the name and ' + 'optionally the version of the Pod.'); } return { name: match[1], version: match[2] }; } exports.pkgInfoFromSpecificationString = pkgInfoFromSpecificationString; /// e.g. Expecta /// ReactiveObjC (~> 2.0) /// Pulley (from `https://github.com/l2succes/Pulley.git`, branch `master`) function pkgInfoFromDependencyString(stringRepresentation) { const match = stringRepresentation.match(/^((?:\s?[^\s(])+)(?: \((.+)\))?$/); if (!match) { throw new Error('Invalid string representation for a ' + `dependency: \`${stringRepresentation}\`. ` + 'The string representation should include the name and ' + 'a requirement of which version of the Pod should be used.'); } if (!match[2] || match[2].match(/from `(.*)(`|')/)) { return { name: match[1] }; } return { name: match[1], version: match[2] }; } exports.pkgInfoFromDependencyString = pkgInfoFromDependencyString; /// Returns the root spec name, if the given specification name /// is a subspec or just the same name. function rootSpecName(specName) { return specName.split('/')[0]; } exports.rootSpecName = rootSpecName; //# sourceMappingURL=utils.js.map /***/ }), /***/ 27877: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DepGraphBuilder = void 0; const graphlib = __webpack_require__(89536); const dep_graph_1 = __webpack_require__(92695); class DepGraphBuilder { constructor(pkgManager, rootPkg) { this._pkgs = {}; this._pkgNodes = {}; const graph = new graphlib.Graph({ directed: true, multigraph: false, compound: false, }); if (!rootPkg) { rootPkg = { name: '_root', version: '0.0.0', }; } this._rootNodeId = 'root-node'; this._rootPkgId = DepGraphBuilder._getPkgId(rootPkg); this._pkgs[this._rootPkgId] = rootPkg; graph.setNode(this._rootNodeId, { pkgId: this._rootPkgId }); this._pkgNodes[this._rootPkgId] = new Set([this._rootNodeId]); this._graph = graph; this._pkgManager = pkgManager; } get rootNodeId() { return this._rootNodeId; } static _getPkgId(pkg) { return `${pkg.name}@${pkg.version || ''}`; } getPkgs() { return Object.values(this._pkgs); } // TODO: this can create disconnected nodes addPkgNode(pkgInfo, nodeId, nodeInfo) { if (nodeId === this._rootNodeId) { throw new Error('DepGraphBuilder.addPkgNode() cant override root node'); } const pkgId = DepGraphBuilder._getPkgId(pkgInfo); this._pkgs[pkgId] = pkgInfo; this._pkgNodes[pkgId] = this._pkgNodes[pkgId] || new Set(); this._pkgNodes[pkgId].add(nodeId); this._graph.setNode(nodeId, { pkgId, info: nodeInfo }); return this; } // TODO: this can create cycles connectDep(parentNodeId, depNodeId) { if (!this._graph.hasNode(parentNodeId)) { throw new Error('parentNodeId does not exist'); } if (!this._graph.hasNode(depNodeId)) { throw new Error('depNodeId does not exist'); } this._graph.setEdge(parentNodeId, depNodeId); return this; } build() { return new dep_graph_1.DepGraphImpl(this._graph, this._rootNodeId, this._pkgs, this._pkgNodes, this._pkgManager); } } exports.DepGraphBuilder = DepGraphBuilder; //# sourceMappingURL=builder.js.map /***/ }), /***/ 24955: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createFromJSON = exports.SUPPORTED_SCHEMA_RANGE = void 0; const semver = __webpack_require__(5739); const graphlib = __webpack_require__(89536); const errors_1 = __webpack_require__(93815); const validate_graph_1 = __webpack_require__(47980); const dep_graph_1 = __webpack_require__(92695); exports.SUPPORTED_SCHEMA_RANGE = '^1.0.0'; /** * Create a DepGraph instance from a JSON representation of a dep graph. This * is typically used after passing the graph over the wire as `DepGraphData`. */ function createFromJSON(depGraphData) { validateDepGraphData(depGraphData); const graph = new graphlib.Graph({ directed: true, multigraph: false, compound: false, }); const pkgs = {}; const pkgNodes = {}; for (const { id, info } of depGraphData.pkgs) { pkgs[id] = info.version ? info : Object.assign(Object.assign({}, info), { version: undefined }); } for (const node of depGraphData.graph.nodes) { const pkgId = node.pkgId; if (!pkgNodes[pkgId]) { pkgNodes[pkgId] = new Set(); } pkgNodes[pkgId].add(node.nodeId); graph.setNode(node.nodeId, { pkgId, info: node.info }); } for (const node of depGraphData.graph.nodes) { for (const depNodeId of node.deps) { graph.setEdge(node.nodeId, depNodeId.nodeId); } } validate_graph_1.validateGraph(graph, depGraphData.graph.rootNodeId, pkgs, pkgNodes); return new dep_graph_1.DepGraphImpl(graph, depGraphData.graph.rootNodeId, pkgs, pkgNodes, depGraphData.pkgManager); } exports.createFromJSON = createFromJSON; function assert(condition, msg) { if (!condition) { throw new errors_1.ValidationError(msg); } } function validateDepGraphData(depGraphData) { assert(!!semver.valid(depGraphData.schemaVersion) && semver.satisfies(depGraphData.schemaVersion, exports.SUPPORTED_SCHEMA_RANGE), `dep-graph schemaVersion not in "${exports.SUPPORTED_SCHEMA_RANGE}"`); assert(depGraphData.pkgManager && !!depGraphData.pkgManager.name, '.pkgManager.name is missing'); const pkgsMap = depGraphData.pkgs.reduce((acc, cur) => { assert(!(cur.id in acc), 'more than one pkg with same id'); assert(!!cur.info, '.pkgs item missing .info'); acc[cur.id] = cur.info; return acc; }, {}); const nodesMap = depGraphData.graph.nodes.reduce((acc, cur) => { assert(!(cur.nodeId in acc), 'more than on node with same id'); acc[cur.nodeId] = cur; return acc; }, {}); const rootNodeId = depGraphData.graph.rootNodeId; const rootNode = nodesMap[rootNodeId]; assert(rootNodeId in nodesMap, `.${rootNodeId} root graph node is missing`); const rootPkgId = rootNode.pkgId; assert(rootPkgId in pkgsMap, `.${rootPkgId} root pkg missing`); assert(nodesMap[rootNodeId].pkgId === rootPkgId, `the root node .pkgId should be "${rootPkgId}"`); const pkgIds = Object.keys(pkgsMap); // NOTE: this name@version check is very strict, // we can relax it later, it just makes things easier now assert(pkgIds.filter((pkgId) => pkgId !== dep_graph_1.DepGraphImpl.getPkgId(pkgsMap[pkgId])) .length === 0, 'pkgs ids should be name@version'); assert(Object.values(nodesMap).filter((node) => !(node.pkgId in pkgsMap)) .length === 0, 'some instance nodes belong to non-existing pkgIds'); assert(Object.values(pkgsMap).filter((pkg) => !pkg.name) .length === 0, 'some .pkgs elements have no .name field'); } //# sourceMappingURL=create-from-json.js.map /***/ }), /***/ 92695: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DepGraphImpl = void 0; const _isEqual = __webpack_require__(72307); const graphlib = __webpack_require__(89536); const create_from_json_1 = __webpack_require__(24955); class DepGraphImpl { constructor(_graph, _rootNodeId, _pkgs, _pkgNodes, _pkgManager) { this._graph = _graph; this._rootNodeId = _rootNodeId; this._pkgs = _pkgs; this._pkgNodes = _pkgNodes; this._pkgManager = _pkgManager; this._countNodePathsToRootCache = new Map(); this._rootPkgId = _graph.node(_rootNodeId).pkgId; this._pkgList = Object.values(_pkgs); this._depPkgsList = this._pkgList.filter((pkg) => pkg !== this.rootPkg); } static getPkgId(pkg) { return `${pkg.name}@${pkg.version || ''}`; } get pkgManager() { return this._pkgManager; } get rootPkg() { return this._pkgs[this._rootPkgId]; } get rootNodeId() { return this._rootNodeId; } /** * Get all unique packages in the graph (including the root package) */ getPkgs() { return this._pkgList; } /** * Get all unique packages in the graph (excluding the root package) */ getDepPkgs() { return this._depPkgsList; } getPkgNodes(pkg) { const pkgId = DepGraphImpl.getPkgId(pkg); const nodes = []; for (const nodeId of Array.from(this._pkgNodes[pkgId])) { const graphNode = this.getGraphNode(nodeId); nodes.push({ info: graphNode.info || {}, }); } return nodes; } getNode(nodeId) { return this.getGraphNode(nodeId).info || {}; } getNodePkg(nodeId) { return this._pkgs[this.getGraphNode(nodeId).pkgId]; } getPkgNodeIds(pkg) { const pkgId = DepGraphImpl.getPkgId(pkg); if (!this._pkgs[pkgId]) { throw new Error(`no such pkg: ${pkgId}`); } return Array.from(this._pkgNodes[pkgId]); } getNodeDepsNodeIds(nodeId) { const deps = this._graph.successors(nodeId); if (!deps) { throw new Error(`no such node: ${nodeId}`); } return deps; } getNodeParentsNodeIds(nodeId) { const parents = this._graph.predecessors(nodeId); if (!parents) { throw new Error(`no such node: ${nodeId}`); } return parents; } hasCycles() { // `isAcyclic` is expensive, so memoize if (this._hasCycles === undefined) { this._hasCycles = !graphlib.alg.isAcyclic(this._graph); } return this._hasCycles; } pkgPathsToRoot(pkg, opts) { const pathsToRoot = []; const limit = opts === null || opts === void 0 ? void 0 : opts.limit; for (const nodeId of this.getPkgNodeIds(pkg)) { const pathsFromNodeToRoot = this.pathsFromNodeToRoot(nodeId, [], { limit, }); for (const path of pathsFromNodeToRoot) { pathsToRoot.push(path); } if (limit && pathsToRoot.length >= limit) { break; } } // note: sorting to get shorter paths first - // it's nicer - and better resembles older behaviour return pathsToRoot.sort((a, b) => a.length - b.length); } countPathsToRoot(pkg) { let count = 0; for (const nodeId of this.getPkgNodeIds(pkg)) { count += this.countNodePathsToRoot(nodeId); } return count; } equals(other, { compareRoot = true } = {}) { let otherDepGraph; if (other instanceof DepGraphImpl) { otherDepGraph = other; } else { // At runtime theoretically we can have multiple versions of // @snyk/dep-graph. If "other" is not an instance of the same class it is // safer to rebuild it from JSON. otherDepGraph = create_from_json_1.createFromJSON(other.toJSON()); } // In theory, for the graphs created by standard means, `_.isEquals(this._data, otherDepGraph._data)` // should suffice, since node IDs will be generated in a predictable way. // However, there might be different versions of graph and inconsistencies // in the ordering of the arrays, so we perform a deep comparison. return this.nodeEquals(this, this.rootNodeId, otherDepGraph, otherDepGraph.rootNodeId, compareRoot); } directDepsLeadingTo(pkg) { const pkgNodes = this.getPkgNodeIds(pkg); const directDeps = this.getNodeDepsNodeIds(this.rootNodeId); const nodes = directDeps.filter((directDep) => { const reachableNodes = graphlib.alg.postorder(this._graph, [directDep]); return reachableNodes.filter((node) => pkgNodes.includes(node)).length; }); return nodes.map((node) => this.getNodePkg(node)); } /** * Create a JSON representation of a dep graph. This is typically used to * send the dep graph over the wire */ toJSON() { const nodeIds = this._graph.nodes(); const nodes = nodeIds.reduce((acc, nodeId) => { const deps = (this._graph.successors(nodeId) || []).map((depNodeId) => ({ nodeId: depNodeId, })); const node = this._graph.node(nodeId); const elem = { nodeId, pkgId: node.pkgId, deps, }; if (node.info && Object.keys(node.info).length > 0) { elem.info = node.info; } acc.push(elem); return acc; }, []); const pkgs = Object.keys(this._pkgs).map((pkgId) => ({ id: pkgId, info: this._pkgs[pkgId], })); return { schemaVersion: DepGraphImpl.SCHEMA_VERSION, pkgManager: this._pkgManager, pkgs, graph: { rootNodeId: this._rootNodeId, nodes, }, }; } nodeEquals(graphA, nodeIdA, graphB, nodeIdB, compareRoot, traversedPairs = new Set()) { // Skip root nodes comparision if needed. if (compareRoot || (nodeIdA !== graphA.rootNodeId && nodeIdB !== graphB.rootNodeId)) { const pkgA = graphA.getNodePkg(nodeIdA); const pkgB = graphB.getNodePkg(nodeIdB); // Compare PkgInfo (name and version). if (!_isEqual(pkgA, pkgB)) { return false; } const infoA = graphA.getNode(nodeIdA); const infoB = graphB.getNode(nodeIdB); // Compare NodeInfo (VersionProvenance and labels). if (!_isEqual(infoA, infoB)) { return false; } } let depsA = graphA.getNodeDepsNodeIds(nodeIdA); let depsB = graphB.getNodeDepsNodeIds(nodeIdB); // Number of dependencies should be the same. if (depsA.length !== depsB.length) { return false; } // Sort dependencies by name@version string. const sortFn = (graph) => (idA, idB) => { const pkgA = graph.getNodePkg(idA); const pkgB = graph.getNodePkg(idB); return DepGraphImpl.getPkgId(pkgA).localeCompare(DepGraphImpl.getPkgId(pkgB)); }; depsA = depsA.sort(sortFn(graphA)); depsB = depsB.sort(sortFn(graphB)); // Compare Each dependency recursively. for (let i = 0; i < depsA.length; i++) { const pairKey = `${depsA[i]}_${depsB[i]}`; // Prevent cycles. if (traversedPairs.has(pairKey)) { continue; } traversedPairs.add(pairKey); if (!this.nodeEquals(graphA, depsA[i], graphB, depsB[i], compareRoot, traversedPairs)) { return false; } } return true; } getGraphNode(nodeId) { const node = this._graph.node(nodeId); if (!node) { throw new Error(`no such node: ${nodeId}`); } return node; } pathsFromNodeToRoot(nodeId, ancestors = [], opts) { const parentNodesIds = this.getNodeParentsNodeIds(nodeId); const pkgInfo = this.getNodePkg(nodeId); if (parentNodesIds.length === 0) { return [[pkgInfo]]; } const allPaths = []; ancestors = ancestors.concat(nodeId); const limit = opts.limit; for (const id of parentNodesIds) { if (ancestors.includes(id)) continue; const pathsFromNodeToRoot = this.pathsFromNodeToRoot(id, ancestors, opts); pathsFromNodeToRoot.forEach((path) => allPaths.push([pkgInfo].concat(path))); if (limit && allPaths.length >= limit) { break; } } return allPaths; } countNodePathsToRoot(nodeId, ancestors = []) { if (ancestors.includes(nodeId)) { return 0; } if (this._countNodePathsToRootCache.has(nodeId)) { return this._countNodePathsToRootCache.get(nodeId) || 0; } const parentNodesIds = this.getNodeParentsNodeIds(nodeId); if (parentNodesIds.length === 0) { this._countNodePathsToRootCache.set(nodeId, 1); return 1; } ancestors = ancestors.concat(nodeId); const count = parentNodesIds.reduce((acc, parentNodeId) => { return acc + this.countNodePathsToRoot(parentNodeId, ancestors); }, 0); this._countNodePathsToRootCache.set(nodeId, count); return count; } } exports.DepGraphImpl = DepGraphImpl; DepGraphImpl.SCHEMA_VERSION = '1.2.0'; //# sourceMappingURL=dep-graph.js.map /***/ }), /***/ 61188: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CustomError = void 0; class CustomError extends Error { constructor(message) { super(message); Object.setPrototypeOf(this, CustomError.prototype); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; } } exports.CustomError = CustomError; //# sourceMappingURL=custom-error.js.map /***/ }), /***/ 93815: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ValidationError = void 0; const validation_error_1 = __webpack_require__(2596); Object.defineProperty(exports, "ValidationError", ({ enumerable: true, get: function () { return validation_error_1.ValidationError; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 2596: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ValidationError = void 0; const custom_error_1 = __webpack_require__(61188); class ValidationError extends custom_error_1.CustomError { constructor(message) { super(message); Object.setPrototypeOf(this, ValidationError.prototype); } } exports.ValidationError = ValidationError; //# sourceMappingURL=validation-error.js.map /***/ }), /***/ 47980: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.validateGraph = void 0; const graphlib = __webpack_require__(89536); const errors_1 = __webpack_require__(93815); function assert(condition, msg) { if (!condition) { throw new errors_1.ValidationError(msg); } } function validateGraph(graph, rootNodeId, pkgs, pkgNodes) { assert((graph.predecessors(rootNodeId) || []).length === 0, `"${rootNodeId}" is not really the root`); const reachableFromRoot = graphlib.alg.postorder(graph, [rootNodeId]); const nodeIds = graph.nodes(); assert(JSON.stringify(nodeIds.sort()) === JSON.stringify(reachableFromRoot.sort()), 'not all graph nodes are reachable from root'); const pkgIds = Object.keys(pkgs); const pkgsWithoutInstances = pkgIds.filter((pkgId) => !pkgNodes[pkgId] || pkgNodes[pkgId].size === 0); assert(pkgsWithoutInstances.length === 0, 'not all pkgs have instance nodes'); } exports.validateGraph = validateGraph; //# sourceMappingURL=validate-graph.js.map /***/ }), /***/ 95946: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.dfs = void 0; const each = __webpack_require__(43590); /* * A helper that preforms a pre- or post-order traversal on the input graph * and returns the nodes in the order they were visited. If the graph is * undirected then this algorithm will navigate using neighbors. If the graph * is directed then this algorithm will navigate using successors. * * Order must be one of "pre" or "post". */ function dfs(g, vs, order) { if (!Array.isArray(vs)) { vs = [vs]; } const navigation = (g.isDirected() ? g.successors : g.neighbors).bind(g); const acc = []; const visited = {}; each(vs, (v) => { if (!g.hasNode(v)) { throw new Error('Graph does not have node: ' + v); } doDfs(g, v, order === 'post', visited, navigation, acc); }); return acc; } exports.dfs = dfs; function doDfs(g, v, postorder, visited, navigation, acc) { if (!(v in visited)) { visited[v] = true; if (!postorder) { acc.push(v); } each(navigation(v), function (w) { doDfs(g, w, postorder, visited, navigation, acc); }); if (postorder) { acc.push(v); } } } //# sourceMappingURL=dfs.js.map /***/ }), /***/ 24374: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isAcyclic = void 0; const topsort_1 = __webpack_require__(34026); function isAcyclic(g) { try { topsort_1.topsort(g); } catch (e) { if (e instanceof topsort_1.CycleException) { return false; } throw e; } return true; } exports.isAcyclic = isAcyclic; //# sourceMappingURL=is-acyclic.js.map /***/ }), /***/ 68958: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.postorder = void 0; const dfs_1 = __webpack_require__(95946); function postorder(g, vs) { return dfs_1.dfs(g, vs, 'post'); } exports.postorder = postorder; //# sourceMappingURL=postorder.js.map /***/ }), /***/ 34026: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CycleException = exports.topsort = void 0; const each = __webpack_require__(43590); const size = __webpack_require__(27946); function topsort(g) { const visited = {}; const stack = {}; const results = []; function visit(node) { if (node in stack) { throw new CycleException(); } if (!(node in visited)) { stack[node] = true; visited[node] = true; each(g.predecessors(node), visit); delete stack[node]; results.push(node); } } each(g.sinks(), visit); if (size(visited) !== g.nodeCount()) { throw new CycleException(); } return results; } exports.topsort = topsort; class CycleException extends Error { } exports.CycleException = CycleException; //# sourceMappingURL=topsort.js.map /***/ }), /***/ 89781: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Graph = void 0; /* eslint-disable prefer-rest-params */ /* eslint-disable @typescript-eslint/no-this-alias */ const constant = __webpack_require__(4254); const each = __webpack_require__(43590); const _filter = __webpack_require__(43590); const isEmpty = __webpack_require__(99245); const isFunction = __webpack_require__(98423); const isUndefined = __webpack_require__(28801); const keys = __webpack_require__(44799); const reduce = __webpack_require__(34766); const union = __webpack_require__(96744); const values = __webpack_require__(17720); const DEFAULT_EDGE_NAME = '\x00'; const GRAPH_NODE = '\x00'; const EDGE_KEY_DELIM = '\x01'; // Implementation notes: // // * Node id query functions should return string ids for the nodes // * Edge id query functions should return an "edgeObj", edge object, that is // composed of enough information to uniquely identify an edge: {v, w, name}. // * Internally we use an "edgeId", a stringified form of the edgeObj, to // reference edges. This is because we need a performant way to look these // edges up and, object properties, which have string keys, are the closest // we're going to get to a performant hashtable in JavaScript. class Graph { constructor(opts) { var _a, _b, _c; /* Number of nodes in the graph. Should only be changed by the implementation. */ this._nodeCount = 0; /* Number of edges in the graph. Should only be changed by the implementation. */ this._edgeCount = 0; this._isDirected = (_a = opts === null || opts === void 0 ? void 0 : opts.directed) !== null && _a !== void 0 ? _a : true; this._isMultigraph = (_b = opts === null || opts === void 0 ? void 0 : opts.multigraph) !== null && _b !== void 0 ? _b : false; this._isCompound = (_c = opts === null || opts === void 0 ? void 0 : opts.compound) !== null && _c !== void 0 ? _c : false; // Label for the graph itself this._label = undefined; // Defaults to be set when creating a new node this._defaultNodeLabelFn = constant(undefined); // Defaults to be set when creating a new edge this._defaultEdgeLabelFn = constant(undefined); // v -> label this._nodes = {}; if (this._isCompound) { // v -> parent this._parent = {}; // v -> children this._children = {}; this._children[GRAPH_NODE] = {}; } // v -> edgeObj this._in = {}; // u -> v -> Number this._preds = {}; // v -> edgeObj this._out = {}; // v -> w -> Number this._sucs = {}; // e -> edgeObj this._edgeObjs = {}; // e -> label this._edgeLabels = {}; } /* === Graph functions ========= */ isDirected() { return this._isDirected; } isMultigraph() { return this._isMultigraph; } isCompound() { return this._isCompound; } setGraph(label) { this._label = label; return this; } graph() { return this._label; } /* === Node functions ========== */ setDefaultNodeLabel(newDefault) { if (!isFunction(newDefault)) { newDefault = constant(newDefault); } this._defaultNodeLabelFn = newDefault; return this; } nodeCount() { return this._nodeCount; } nodes() { return keys(this._nodes); } sources() { const self = this; return _filter(this.nodes(), function (v) { return isEmpty(self._in[v]); }); } sinks() { const self = this; return _filter(this.nodes(), function (v) { return isEmpty(self._out[v]); }); } setNodes(vs, value) { const args = arguments; const self = this; each(vs, function (v) { if (args.length > 1) { self.setNode(v, value); } else { self.setNode(v); } }); return this; } setNode(v, value) { if (v in this._nodes) { if (arguments.length > 1) { this._nodes[v] = value; } return this; } this._nodes[v] = arguments.length > 1 ? value : this._defaultNodeLabelFn(v); if (this._isCompound) { this._parent[v] = GRAPH_NODE; this._children[v] = {}; this._children[GRAPH_NODE][v] = true; } this._in[v] = {}; this._preds[v] = {}; this._out[v] = {}; this._sucs[v] = {}; ++this._nodeCount; return this; } node(v) { return this._nodes[v]; } hasNode(v) { return v in this._nodes; } removeNode(v) { const self = this; if (v in this._nodes) { const removeEdge = function (e) { self.removeEdge(self._edgeObjs[e]); }; delete this._nodes[v]; if (this._isCompound) { this._removeFromParentsChildList(v); delete this._parent[v]; each(this.children(v), function (child) { self.setParent(child); }); delete this._children[v]; } each(keys(this._in[v]), removeEdge); delete this._in[v]; delete this._preds[v]; each(keys(this._out[v]), removeEdge); delete this._out[v]; delete this._sucs[v]; --this._nodeCount; } return this; } setParent(v, parent) { if (!this._isCompound) { throw new Error('Cannot set parent in a non-compound graph'); } if (isUndefined(parent)) { parent = GRAPH_NODE; } else { // Coerce parent to string parent += ''; for (let ancestor = parent; !isUndefined(ancestor); ancestor = this.parent(ancestor)) { if (ancestor === v) { throw new Error('Setting ' + parent + ' as parent of ' + v + ' would create a cycle'); } } this.setNode(parent); } this.setNode(v); this._removeFromParentsChildList(v); this._parent[v] = parent; this._children[parent][v] = true; return this; } _removeFromParentsChildList(v) { delete this._children[this._parent[v]][v]; } parent(v) { if (this._isCompound) { const parent = this._parent[v]; if (parent !== GRAPH_NODE) { return parent; } } } children(v) { if (isUndefined(v)) { v = GRAPH_NODE; } if (this._isCompound) { const children = this._children[v]; if (children) { return keys(children); } } else if (v === GRAPH_NODE) { return this.nodes(); } else if (this.hasNode(v)) { return []; } } predecessors(v) { const predsV = this._preds[v]; if (predsV) { return keys(predsV); } } successors(v) { const sucsV = this._sucs[v]; if (sucsV) { return keys(sucsV); } } neighbors(v) { const preds = this.predecessors(v); if (preds) { return union(preds, this.successors(v)); } } isLeaf(v) { let neighbors; if (this.isDirected()) { neighbors = this.successors(v); } else { neighbors = this.neighbors(v); } return neighbors.length === 0; } filterNodes(filter) { const copy = new Graph({ directed: this._isDirected, multigraph: this._isMultigraph, compound: this._isCompound, }); copy.setGraph(this.graph()); const self = this; each(this._nodes, function (value, v) { if (filter(v)) { copy.setNode(v, value); } }); each(this._edgeObjs, function (e) { if (copy.hasNode(e.v) && copy.hasNode(e.w)) { copy.setEdge(e, self.edge(e)); } }); const parents = {}; function findParent(v) { const parent = self.parent(v); if (parent === undefined || copy.hasNode(parent)) { parents[v] = parent; return parent; } else if (parent in parents) { return parents[parent]; } else { return findParent(parent); } } if (this._isCompound) { each(copy.nodes(), function (v) { copy.setParent(v, findParent(v)); }); } return copy; } /* === Edge functions ========== */ setDefaultEdgeLabel(newDefault) { if (!isFunction(newDefault)) { newDefault = constant(newDefault); } this._defaultEdgeLabelFn = newDefault; return this; } edgeCount() { return this._edgeCount; } edges() { return values(this._edgeObjs); } setPath(vs, value) { const self = this; const args = arguments; reduce(vs, function (v, w) { if (args.length > 1) { self.setEdge(v, w, value); } else { self.setEdge(v, w); } return w; }); return this; } // eslint-disable-next-line @typescript-eslint/no-unused-vars setEdge(...args) { let v, w, name, value; let valueSpecified = false; const arg0 = arguments[0]; if (typeof arg0 === 'object' && arg0 !== null && 'v' in arg0) { v = arg0.v; w = arg0.w; name = arg0.name; if (arguments.length === 2) { value = arguments[1]; valueSpecified = true; } } else { v = arg0; w = arguments[1]; name = arguments[3]; if (arguments.length > 2) { value = arguments[2]; valueSpecified = true; } } v = '' + v; w = '' + w; if (!isUndefined(name)) { name = '' + name; } const e = edgeArgsToId(this._isDirected, v, w, name); if (e in this._edgeLabels) { if (valueSpecified) { this._edgeLabels[e] = value; } return this; } if (!isUndefined(name) && !this._isMultigraph) { throw new Error('Cannot set a named edge when isMultigraph = false'); } // It didn't exist, so we need to create it. // First ensure the nodes exist. this.setNode(v); this.setNode(w); this._edgeLabels[e] = valueSpecified ? value : this._defaultEdgeLabelFn(v, w, name); const edgeObj = edgeArgsToObj(this._isDirected, v, w, name); // Ensure we add undirected edges in a consistent way. v = edgeObj.v; w = edgeObj.w; Object.freeze(edgeObj); this._edgeObjs[e] = edgeObj; incrementOrInitEntry(this._preds[w], v); incrementOrInitEntry(this._sucs[v], w); this._in[w][e] = edgeObj; this._out[v][e] = edgeObj; this._edgeCount++; return this; } edge(v, w, name) { const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); return this._edgeLabels[e]; } hasEdge(v, w, name) { const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); return e in this._edgeLabels; } removeEdge(v, w, name) { const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); const edge = this._edgeObjs[e]; if (edge) { v = edge.v; w = edge.w; delete this._edgeLabels[e]; delete this._edgeObjs[e]; decrementOrRemoveEntry(this._preds[w], v); decrementOrRemoveEntry(this._sucs[v], w); delete this._in[w][e]; delete this._out[v][e]; this._edgeCount--; } return this; } inEdges(v, u) { const inV = this._in[v]; if (inV) { const edges = values(inV); if (!u) { return edges; } return _filter(edges, function (edge) { return edge.v === u; }); } } outEdges(v, w) { const outV = this._out[v]; if (outV) { const edges = values(outV); if (!w) { return edges; } return _filter(edges, function (edge) { return edge.w === w; }); } } nodeEdges(v, w) { const inEdges = this.inEdges(v, w); if (inEdges) { return inEdges.concat(this.outEdges(v, w)); } } } exports.Graph = Graph; function incrementOrInitEntry(map, k) { if (map[k]) { map[k]++; } else { map[k] = 1; } } function decrementOrRemoveEntry(map, k) { if (!--map[k]) { delete map[k]; } } function edgeArgsToId(isDirected, v_, w_, name) { let v = '' + v_; let w = '' + w_; if (!isDirected && v > w) { const tmp = v; v = w; w = tmp; } return (v + EDGE_KEY_DELIM + w + EDGE_KEY_DELIM + (isUndefined(name) ? DEFAULT_EDGE_NAME : name)); } function edgeArgsToObj(isDirected, v_, w_, name) { let v = '' + v_; let w = '' + w_; if (!isDirected && v > w) { const tmp = v; v = w; w = tmp; } const edgeObj = { v: v, w: w }; if (name) { edgeObj.name = name; } return edgeObj; } function edgeObjToId(isDirected, edgeObj) { return edgeArgsToId(isDirected, edgeObj.v, edgeObj.w, edgeObj.name); } //# sourceMappingURL=graph.js.map /***/ }), /***/ 89536: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.alg = exports.Graph = void 0; var graph_1 = __webpack_require__(89781); Object.defineProperty(exports, "Graph", ({ enumerable: true, get: function () { return graph_1.Graph; } })); const is_acyclic_1 = __webpack_require__(24374); const postorder_1 = __webpack_require__(68958); exports.alg = { isAcyclic: is_acyclic_1.isAcyclic, postorder: postorder_1.postorder, }; //# sourceMappingURL=index.js.map /***/ }), /***/ 14010: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.legacy = exports.Errors = exports.DepGraphBuilder = exports.createFromJSON = void 0; var create_from_json_1 = __webpack_require__(24955); Object.defineProperty(exports, "createFromJSON", ({ enumerable: true, get: function () { return create_from_json_1.createFromJSON; } })); var builder_1 = __webpack_require__(27877); Object.defineProperty(exports, "DepGraphBuilder", ({ enumerable: true, get: function () { return builder_1.DepGraphBuilder; } })); const Errors = __webpack_require__(93815); exports.Errors = Errors; const legacy = __webpack_require__(74767); exports.legacy = legacy; //# sourceMappingURL=index.js.map /***/ }), /***/ 91678: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.partitionCycles = exports.getCycle = void 0; function getCycle(ancestors, nodeId) { if (!ancestors.includes(nodeId)) { return null; } // first item is where the cycle starts and ends. return ancestors.slice(ancestors.indexOf(nodeId)); } exports.getCycle = getCycle; function partitionCycles(nodeId, allCyclesTheNodeIsPartOf) { const cyclesStartWithThisNode = []; const cyclesWithThisNode = []; for (const cycle of allCyclesTheNodeIsPartOf) { const nodeStartsCycle = cycle[0] === nodeId; if (nodeStartsCycle) { cyclesStartWithThisNode.push(cycle); } else { cyclesWithThisNode.push(cycle); } } return { cyclesStartWithThisNode, cyclesWithThisNode }; } exports.partitionCycles = partitionCycles; //# sourceMappingURL=cycles.js.map /***/ }), /***/ 74767: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.graphToDepTree = exports.depTreeToGraph = void 0; const crypto = __webpack_require__(6113); const event_loop_spinner_1 = __webpack_require__(77158); const builder_1 = __webpack_require__(27877); const objectHash = __webpack_require__(66353); const cycles_1 = __webpack_require__(91678); const memiozation_1 = __webpack_require__(38590); function addLabel(dep, key, value) { if (!dep.labels) { dep.labels = {}; } dep.labels[key] = value; } /** * @deprecated Don't use dep trees as an intermediate step, because they are * large structures, resulting in high memory usage and high CPU costs from * serializing / deserializing. Instead, create a graph directly with * {@link DepGraphBuilder} */ async function depTreeToGraph(depTree, pkgManagerName) { const rootPkg = { name: depTree.name, version: depTree.version || undefined, }; const pkgManagerInfo = { name: pkgManagerName, }; const targetOS = depTree.targetOS; if (targetOS) { pkgManagerInfo.repositories = [ { alias: `${targetOS.name}:${targetOS.version}`, }, ]; } const builder = new builder_1.DepGraphBuilder(pkgManagerInfo, rootPkg); await buildGraph(builder, depTree, depTree.name, true); const depGraph = await builder.build(); return shortenNodeIds(depGraph); } exports.depTreeToGraph = depTreeToGraph; async function buildGraph(builder, depTree, pkgName, isRoot = false, memoizationMap = new Map()) { if (memoizationMap.has(depTree)) { return memoizationMap.get(depTree); } const getNodeId = (name, version, hashId) => `${name}@${version || ''}|${hashId}`; const depNodesIds = []; const hash = crypto.createHash('sha1'); if (depTree.versionProvenance) { hash.update(objectHash(depTree.versionProvenance)); } if (depTree.labels) { hash.update(objectHash(depTree.labels)); } const deps = depTree.dependencies || {}; // filter-out invalid null deps (shouldn't happen - but did...) const depNames = Object.keys(deps).filter((d) => !!deps[d]); for (const depName of depNames.sort()) { const dep = deps[depName]; const subtreeHash = await buildGraph(builder, dep, depName, false, memoizationMap); const depPkg = { name: depName, version: dep.version, }; const depNodeId = getNodeId(depPkg.name, depPkg.version, subtreeHash); depNodesIds.push(depNodeId); const nodeInfo = {}; if (dep.versionProvenance) { nodeInfo.versionProvenance = dep.versionProvenance; } if (dep.labels) { nodeInfo.labels = dep.labels; } builder.addPkgNode(depPkg, depNodeId, nodeInfo); hash.update(depNodeId); } const treeHash = hash.digest('hex'); let pkgNodeId; if (isRoot) { pkgNodeId = builder.rootNodeId; } else { // we don't assume depTree has a .name to support output of `npm list --json` const pkg = { name: pkgName, version: depTree.version, }; pkgNodeId = getNodeId(pkg.name, pkg.version, treeHash); const nodeInfo = {}; if (depTree.versionProvenance) { nodeInfo.versionProvenance = depTree.versionProvenance; } if (depTree.labels) { nodeInfo.labels = depTree.labels; } builder.addPkgNode(pkg, pkgNodeId, nodeInfo); } for (const depNodeId of depNodesIds) { builder.connectDep(pkgNodeId, depNodeId); } if (depNodesIds.length > 0 && event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } memoizationMap.set(depTree, treeHash); return treeHash; } async function shortenNodeIds(depGraph) { const builder = new builder_1.DepGraphBuilder(depGraph.pkgManager, depGraph.rootPkg); const nodesMap = {}; // create nodes with shorter ids for (const pkg of depGraph.getPkgs()) { const nodeIds = depGraph.getPkgNodeIds(pkg); for (let i = 0; i < nodeIds.length; i++) { const nodeId = nodeIds[i]; if (nodeId === depGraph.rootNodeId) { continue; } const nodeInfo = depGraph.getNode(nodeId); let newNodeId; if (nodeIds.length === 1) { newNodeId = `${trimAfterLastSep(nodeId, '|')}`; } else { newNodeId = `${trimAfterLastSep(nodeId, '|')}|${i + 1}`; } nodesMap[nodeId] = newNodeId; builder.addPkgNode(pkg, newNodeId, nodeInfo); } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } // connect nodes for (const pkg of depGraph.getPkgs()) { for (const nodeId of depGraph.getPkgNodeIds(pkg)) { for (const depNodeId of depGraph.getNodeDepsNodeIds(nodeId)) { const parentNode = nodesMap[nodeId] || nodeId; const childNode = nodesMap[depNodeId] || depNodeId; builder.connectDep(parentNode, childNode); } } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } return builder.build(); } /** * @deprecated Don't use dep trees. You should adapt your code to use graphs, * and enhance the dep-graph library if there is missing functionality from * the graph structure */ async function graphToDepTree(depGraphInterface, pkgType, opts = { deduplicateWithinTopLevelDeps: false }) { const depGraph = depGraphInterface; const [depTree] = await buildSubtree(depGraph, depGraph.rootNodeId, opts.deduplicateWithinTopLevelDeps ? null : false); depTree.type = depGraph.pkgManager.name; depTree.packageFormatVersion = constructPackageFormatVersion(pkgType); const targetOS = constructTargetOS(depGraph); if (targetOS) { depTree.targetOS = targetOS; } return depTree; } exports.graphToDepTree = graphToDepTree; function constructPackageFormatVersion(pkgType) { if (pkgType === 'maven') { pkgType = 'mvn'; } return `${pkgType}:0.0.1`; } function constructTargetOS(depGraph) { if (['apk', 'apt', 'deb', 'rpm', 'linux'].indexOf(depGraph.pkgManager.name) === -1) { // .targetOS is undefined unless its a linux pkgManager return; } if (!depGraph.pkgManager.repositories || !depGraph.pkgManager.repositories.length || !depGraph.pkgManager.repositories[0].alias) { throw new Error('Incomplete .pkgManager, could not create .targetOS'); } const [name, version] = depGraph.pkgManager.repositories[0].alias.split(':'); return { name, version }; } async function buildSubtree(depGraph, nodeId, maybeDeduplicationSet = false, // false = disabled; null = not in deduplication scope yet ancestors = [], memoizationMap = new Map()) { if (!maybeDeduplicationSet) { const memoizedDepTree = memiozation_1.getMemoizedDepTree(nodeId, ancestors, memoizationMap); if (memoizedDepTree) { return [memoizedDepTree, undefined]; } } const isRoot = nodeId === depGraph.rootNodeId; const nodePkg = depGraph.getNodePkg(nodeId); const nodeInfo = depGraph.getNode(nodeId); const depTree = {}; depTree.name = nodePkg.name; depTree.version = nodePkg.version; if (nodeInfo.versionProvenance) { depTree.versionProvenance = nodeInfo.versionProvenance; } if (nodeInfo.labels) { depTree.labels = Object.assign({}, nodeInfo.labels); } const depInstanceIds = depGraph.getNodeDepsNodeIds(nodeId); if (!depInstanceIds || depInstanceIds.length === 0) { memoizationMap.set(nodeId, { depTree }); return [depTree, undefined]; } const cycle = cycles_1.getCycle(ancestors, nodeId); if (cycle) { // This node starts a cycle and now it's the second visit. addLabel(depTree, 'pruned', 'cyclic'); return [depTree, [cycle]]; } if (maybeDeduplicationSet) { if (maybeDeduplicationSet.has(nodeId)) { if (depInstanceIds.length > 0) { addLabel(depTree, 'pruned', 'true'); } return [depTree, undefined]; } maybeDeduplicationSet.add(nodeId); } const cycles = []; for (const depInstId of depInstanceIds) { // Deduplication of nodes occurs only within a scope of a top-level dependency. // Therefore, every top-level dep gets an independent set to track duplicates. if (isRoot && maybeDeduplicationSet !== false) { maybeDeduplicationSet = new Set(); } const [subtree, subtreeCycles] = await buildSubtree(depGraph, depInstId, maybeDeduplicationSet, ancestors.concat(nodeId), memoizationMap); if (subtreeCycles) { for (const cycle of subtreeCycles) { cycles.push(cycle); } } if (!subtree) { continue; } if (!depTree.dependencies) { depTree.dependencies = {}; } depTree.dependencies[subtree.name] = subtree; } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } const partitionedCycles = cycles_1.partitionCycles(nodeId, cycles); memiozation_1.memoize(nodeId, memoizationMap, depTree, partitionedCycles); return [depTree, partitionedCycles.cyclesWithThisNode]; } function trimAfterLastSep(str, sep) { return str.slice(0, str.lastIndexOf(sep)); } //# sourceMappingURL=index.js.map /***/ }), /***/ 38590: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getMemoizedDepTree = exports.memoize = void 0; function memoize(nodeId, memoizationMap, depTree, partitionedCycles) { const { cyclesStartWithThisNode, cyclesWithThisNode } = partitionedCycles; if (cyclesStartWithThisNode.length > 0) { const cycleNodeIds = new Set(...cyclesStartWithThisNode); memoizationMap.set(nodeId, { depTree, cycleNodeIds }); } else if (cyclesWithThisNode.length === 0) { memoizationMap.set(nodeId, { depTree }); } // Don't memoize nodes in cycles (cyclesWithThisNode.length > 0) } exports.memoize = memoize; function getMemoizedDepTree(nodeId, ancestors, memoizationMap) { if (!memoizationMap.has(nodeId)) return null; const { depTree, cycleNodeIds } = memoizationMap.get(nodeId); if (!cycleNodeIds) return depTree; const ancestorsArePartOfTheCycle = ancestors.some((nodeId) => cycleNodeIds.has(nodeId)); return ancestorsArePartOfTheCycle ? null : depTree; } exports.getMemoizedDepTree = getMemoizedDepTree; //# sourceMappingURL=memiozation.js.map /***/ }), /***/ 42114: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // A linked list to keep track of recently-used-ness const Yallist = __webpack_require__(351) const MAX = Symbol('max') const LENGTH = Symbol('length') const LENGTH_CALCULATOR = Symbol('lengthCalculator') const ALLOW_STALE = Symbol('allowStale') const MAX_AGE = Symbol('maxAge') const DISPOSE = Symbol('dispose') const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') const LRU_LIST = Symbol('lruList') const CACHE = Symbol('cache') const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') const naiveLength = () => 1 // lruList is a yallist where the head is the youngest // item, and the tail is the oldest. the list contains the Hit // objects as the entries. // Each Hit object has a reference to its Yallist.Node. This // never changes. // // cache is a Map (or PseudoMap) that matches the keys to // the Yallist.Node object. class LRUCache { constructor (options) { if (typeof options === 'number') options = { max: options } if (!options) options = {} if (options.max && (typeof options.max !== 'number' || options.max < 0)) throw new TypeError('max must be a non-negative number') // Kind of weird to have a default max of Infinity, but oh well. const max = this[MAX] = options.max || Infinity const lc = options.length || naiveLength this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc this[ALLOW_STALE] = options.stale || false if (options.maxAge && typeof options.maxAge !== 'number') throw new TypeError('maxAge must be a number') this[MAX_AGE] = options.maxAge || 0 this[DISPOSE] = options.dispose this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false this.reset() } // resize the cache when the max changes. set max (mL) { if (typeof mL !== 'number' || mL < 0) throw new TypeError('max must be a non-negative number') this[MAX] = mL || Infinity trim(this) } get max () { return this[MAX] } set allowStale (allowStale) { this[ALLOW_STALE] = !!allowStale } get allowStale () { return this[ALLOW_STALE] } set maxAge (mA) { if (typeof mA !== 'number') throw new TypeError('maxAge must be a non-negative number') this[MAX_AGE] = mA trim(this) } get maxAge () { return this[MAX_AGE] } // resize the cache when the lengthCalculator changes. set lengthCalculator (lC) { if (typeof lC !== 'function') lC = naiveLength if (lC !== this[LENGTH_CALCULATOR]) { this[LENGTH_CALCULATOR] = lC this[LENGTH] = 0 this[LRU_LIST].forEach(hit => { hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) this[LENGTH] += hit.length }) } trim(this) } get lengthCalculator () { return this[LENGTH_CALCULATOR] } get length () { return this[LENGTH] } get itemCount () { return this[LRU_LIST].length } rforEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].tail; walker !== null;) { const prev = walker.prev forEachStep(this, fn, walker, thisp) walker = prev } } forEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].head; walker !== null;) { const next = walker.next forEachStep(this, fn, walker, thisp) walker = next } } keys () { return this[LRU_LIST].toArray().map(k => k.key) } values () { return this[LRU_LIST].toArray().map(k => k.value) } reset () { if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) { this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) } this[CACHE] = new Map() // hash of items by key this[LRU_LIST] = new Yallist() // list of items in order of use recency this[LENGTH] = 0 // length of items in the list } dump () { return this[LRU_LIST].map(hit => isStale(this, hit) ? false : { k: hit.key, v: hit.value, e: hit.now + (hit.maxAge || 0) }).toArray().filter(h => h) } dumpLru () { return this[LRU_LIST] } set (key, value, maxAge) { maxAge = maxAge || this[MAX_AGE] if (maxAge && typeof maxAge !== 'number') throw new TypeError('maxAge must be a number') const now = maxAge ? Date.now() : 0 const len = this[LENGTH_CALCULATOR](value, key) if (this[CACHE].has(key)) { if (len > this[MAX]) { del(this, this[CACHE].get(key)) return false } const node = this[CACHE].get(key) const item = node.value // dispose of the old one before overwriting // split out into 2 ifs for better coverage tracking if (this[DISPOSE]) { if (!this[NO_DISPOSE_ON_SET]) this[DISPOSE](key, item.value) } item.now = now item.maxAge = maxAge item.value = value this[LENGTH] += len - item.length item.length = len this.get(key) trim(this) return true } const hit = new Entry(key, value, len, now, maxAge) // oversized objects fall out of cache automatically. if (hit.length > this[MAX]) { if (this[DISPOSE]) this[DISPOSE](key, value) return false } this[LENGTH] += hit.length this[LRU_LIST].unshift(hit) this[CACHE].set(key, this[LRU_LIST].head) trim(this) return true } has (key) { if (!this[CACHE].has(key)) return false const hit = this[CACHE].get(key).value return !isStale(this, hit) } get (key) { return get(this, key, true) } peek (key) { return get(this, key, false) } pop () { const node = this[LRU_LIST].tail if (!node) return null del(this, node) return node.value } del (key) { del(this, this[CACHE].get(key)) } load (arr) { // reset the cache this.reset() const now = Date.now() // A previous serialized cache has the most recent items first for (let l = arr.length - 1; l >= 0; l--) { const hit = arr[l] const expiresAt = hit.e || 0 if (expiresAt === 0) // the item was created without expiration in a non aged cache this.set(hit.k, hit.v) else { const maxAge = expiresAt - now // dont add already expired items if (maxAge > 0) { this.set(hit.k, hit.v, maxAge) } } } } prune () { this[CACHE].forEach((value, key) => get(this, key, false)) } } const get = (self, key, doUse) => { const node = self[CACHE].get(key) if (node) { const hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) return undefined } else { if (doUse) { if (self[UPDATE_AGE_ON_GET]) node.value.now = Date.now() self[LRU_LIST].unshiftNode(node) } } return hit.value } } const isStale = (self, hit) => { if (!hit || (!hit.maxAge && !self[MAX_AGE])) return false const diff = Date.now() - hit.now return hit.maxAge ? diff > hit.maxAge : self[MAX_AGE] && (diff > self[MAX_AGE]) } const trim = self => { if (self[LENGTH] > self[MAX]) { for (let walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) { // We know that we're about to delete this one, and also // what the next least recently used key will be, so just // go ahead and set it now. const prev = walker.prev del(self, walker) walker = prev } } } const del = (self, node) => { if (node) { const hit = node.value if (self[DISPOSE]) self[DISPOSE](hit.key, hit.value) self[LENGTH] -= hit.length self[CACHE].delete(hit.key) self[LRU_LIST].removeNode(node) } } class Entry { constructor (key, value, length, now, maxAge) { this.key = key this.value = value this.length = length this.now = now this.maxAge = maxAge || 0 } } const forEachStep = (self, fn, node, thisp) => { let hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) hit = undefined } if (hit) fn.call(thisp, hit.value, hit.key, self) } module.exports = LRUCache /***/ }), /***/ 66353: /***/ ((module, exports, __webpack_require__) => { "use strict"; var crypto = __webpack_require__(6113); /** * Exported function * * Options: * * - `algorithm` hash algo to be used by this instance: *'sha1', 'md5' * - `excludeValues` {true|*false} hash object keys, values ignored * - `encoding` hash encoding, supports 'buffer', '*hex', 'binary', 'base64' * - `ignoreUnknown` {true|*false} ignore unknown object types * - `replacer` optional function that replaces values before hashing * - `respectFunctionProperties` {*true|false} consider function properties when hashing * - `respectFunctionNames` {*true|false} consider 'name' property of functions for hashing * - `respectType` {*true|false} Respect special properties (prototype, constructor) * when hashing to distinguish between types * - `unorderedArrays` {true|*false} Sort all arrays before hashing * - `unorderedSets` {*true|false} Sort `Set` and `Map` instances before hashing * * = default * * @param {object} object value to hash * @param {object} options hashing options * @return {string} hash value * @api public */ exports = module.exports = objectHash; function objectHash(object, options){ options = applyDefaults(object, options); return hash(object, options); } /** * Exported sugar methods * * @param {object} object value to hash * @return {string} hash value * @api public */ exports.sha1 = function(object){ return objectHash(object); }; exports.keys = function(object){ return objectHash(object, {excludeValues: true, algorithm: 'sha1', encoding: 'hex'}); }; exports.MD5 = function(object){ return objectHash(object, {algorithm: 'md5', encoding: 'hex'}); }; exports.keysMD5 = function(object){ return objectHash(object, {algorithm: 'md5', encoding: 'hex', excludeValues: true}); }; // Internals var hashes = crypto.getHashes ? crypto.getHashes().slice() : ['sha1', 'md5']; hashes.push('passthrough'); var encodings = ['buffer', 'hex', 'binary', 'base64']; function applyDefaults(object, sourceOptions){ sourceOptions = sourceOptions || {}; // create a copy rather than mutating var options = {}; options.algorithm = sourceOptions.algorithm || 'sha1'; options.encoding = sourceOptions.encoding || 'hex'; options.excludeValues = sourceOptions.excludeValues ? true : false; options.algorithm = options.algorithm.toLowerCase(); options.encoding = options.encoding.toLowerCase(); options.ignoreUnknown = sourceOptions.ignoreUnknown !== true ? false : true; // default to false options.respectType = sourceOptions.respectType === false ? false : true; // default to true options.respectFunctionNames = sourceOptions.respectFunctionNames === false ? false : true; options.respectFunctionProperties = sourceOptions.respectFunctionProperties === false ? false : true; options.unorderedArrays = sourceOptions.unorderedArrays !== true ? false : true; // default to false options.unorderedSets = sourceOptions.unorderedSets === false ? false : true; // default to false options.unorderedObjects = sourceOptions.unorderedObjects === false ? false : true; // default to true options.replacer = sourceOptions.replacer || undefined; options.excludeKeys = sourceOptions.excludeKeys || undefined; if(typeof object === 'undefined') { throw new Error('Object argument required.'); } // if there is a case-insensitive match in the hashes list, accept it // (i.e. SHA256 for sha256) for (var i = 0; i < hashes.length; ++i) { if (hashes[i].toLowerCase() === options.algorithm.toLowerCase()) { options.algorithm = hashes[i]; } } if(hashes.indexOf(options.algorithm) === -1){ throw new Error('Algorithm "' + options.algorithm + '" not supported. ' + 'supported values: ' + hashes.join(', ')); } if(encodings.indexOf(options.encoding) === -1 && options.algorithm !== 'passthrough'){ throw new Error('Encoding "' + options.encoding + '" not supported. ' + 'supported values: ' + encodings.join(', ')); } return options; } /** Check if the given function is a native function */ function isNativeFunction(f) { if ((typeof f) !== 'function') { return false; } var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i; return exp.exec(Function.prototype.toString.call(f)) != null; } function hash(object, options) { var hashingStream; if (options.algorithm !== 'passthrough') { hashingStream = crypto.createHash(options.algorithm); } else { hashingStream = new PassThrough(); } if (typeof hashingStream.write === 'undefined') { hashingStream.write = hashingStream.update; hashingStream.end = hashingStream.update; } var hasher = typeHasher(options, hashingStream); hasher.dispatch(object); if (!hashingStream.update) { hashingStream.end(''); } if (hashingStream.digest) { return hashingStream.digest(options.encoding === 'buffer' ? undefined : options.encoding); } var buf = hashingStream.read(); if (options.encoding === 'buffer') { return buf; } return buf.toString(options.encoding); } /** * Expose streaming API * * @param {object} object Value to serialize * @param {object} options Options, as for hash() * @param {object} stream A stream to write the serializiation to * @api public */ exports.writeToStream = function(object, options, stream) { if (typeof stream === 'undefined') { stream = options; options = {}; } options = applyDefaults(object, options); return typeHasher(options, stream).dispatch(object); }; function typeHasher(options, writeTo, context){ context = context || []; var write = function(str) { if (writeTo.update) { return writeTo.update(str, 'utf8'); } else { return writeTo.write(str, 'utf8'); } }; return { dispatch: function(value){ if (options.replacer) { value = options.replacer(value); } var type = typeof value; if (value === null) { type = 'null'; } //console.log("[DEBUG] Dispatch: ", value, "->", type, " -> ", "_" + type); return this['_' + type](value); }, _object: function(object) { var pattern = (/\[object (.*)\]/i); var objString = Object.prototype.toString.call(object); var objType = pattern.exec(objString); if (!objType) { // object type did not match [object ...] objType = 'unknown:[' + objString + ']'; } else { objType = objType[1]; // take only the class name } objType = objType.toLowerCase(); var objectNumber = null; if ((objectNumber = context.indexOf(object)) >= 0) { return this.dispatch('[CIRCULAR:' + objectNumber + ']'); } else { context.push(object); } if (typeof Buffer !== 'undefined' && Buffer.isBuffer && Buffer.isBuffer(object)) { write('buffer:'); return write(object); } if(objType !== 'object' && objType !== 'function' && objType !== 'asyncfunction') { if(this['_' + objType]) { this['_' + objType](object); } else if (options.ignoreUnknown) { return write('[' + objType + ']'); } else { throw new Error('Unknown object type "' + objType + '"'); } }else{ var keys = Object.keys(object); if (options.unorderedObjects) { keys = keys.sort(); } // Make sure to incorporate special properties, so // Types with different prototypes will produce // a different hash and objects derived from // different functions (`new Foo`, `new Bar`) will // produce different hashes. // We never do this for native functions since some // seem to break because of that. if (options.respectType !== false && !isNativeFunction(object)) { keys.splice(0, 0, 'prototype', '__proto__', 'constructor'); } if (options.excludeKeys) { keys = keys.filter(function(key) { return !options.excludeKeys(key); }); } write('object:' + keys.length + ':'); var self = this; return keys.forEach(function(key){ self.dispatch(key); write(':'); if(!options.excludeValues) { self.dispatch(object[key]); } write(','); }); } }, _array: function(arr, unordered){ unordered = typeof unordered !== 'undefined' ? unordered : options.unorderedArrays !== false; // default to options.unorderedArrays var self = this; write('array:' + arr.length + ':'); if (!unordered || arr.length <= 1) { return arr.forEach(function(entry) { return self.dispatch(entry); }); } // the unordered case is a little more complicated: // since there is no canonical ordering on objects, // i.e. {a:1} < {a:2} and {a:1} > {a:2} are both false, // we first serialize each entry using a PassThrough stream // before sorting. // also: we can’t use the same context array for all entries // since the order of hashing should *not* matter. instead, // we keep track of the additions to a copy of the context array // and add all of them to the global context array when we’re done var contextAdditions = []; var entries = arr.map(function(entry) { var strm = new PassThrough(); var localContext = context.slice(); // make copy var hasher = typeHasher(options, strm, localContext); hasher.dispatch(entry); // take only what was added to localContext and append it to contextAdditions contextAdditions = contextAdditions.concat(localContext.slice(context.length)); return strm.read().toString(); }); context = context.concat(contextAdditions); entries.sort(); return this._array(entries, false); }, _date: function(date){ return write('date:' + date.toJSON()); }, _symbol: function(sym){ return write('symbol:' + sym.toString()); }, _error: function(err){ return write('error:' + err.toString()); }, _boolean: function(bool){ return write('bool:' + bool.toString()); }, _string: function(string){ write('string:' + string.length + ':'); write(string.toString()); }, _function: function(fn){ write('fn:'); if (isNativeFunction(fn)) { this.dispatch('[native]'); } else { this.dispatch(fn.toString()); } if (options.respectFunctionNames !== false) { // Make sure we can still distinguish native functions // by their name, otherwise String and Function will // have the same hash this.dispatch("function-name:" + String(fn.name)); } if (options.respectFunctionProperties) { this._object(fn); } }, _number: function(number){ return write('number:' + number.toString()); }, _xml: function(xml){ return write('xml:' + xml.toString()); }, _null: function() { return write('Null'); }, _undefined: function() { return write('Undefined'); }, _regexp: function(regex){ return write('regex:' + regex.toString()); }, _uint8array: function(arr){ write('uint8array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _uint8clampedarray: function(arr){ write('uint8clampedarray:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _int8array: function(arr){ write('uint8array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _uint16array: function(arr){ write('uint16array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _int16array: function(arr){ write('uint16array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _uint32array: function(arr){ write('uint32array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _int32array: function(arr){ write('uint32array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _float32array: function(arr){ write('float32array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _float64array: function(arr){ write('float64array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _arraybuffer: function(arr){ write('arraybuffer:'); return this.dispatch(new Uint8Array(arr)); }, _url: function(url) { return write('url:' + url.toString(), 'utf8'); }, _map: function(map) { write('map:'); var arr = Array.from(map); return this._array(arr, options.unorderedSets !== false); }, _set: function(set) { write('set:'); var arr = Array.from(set); return this._array(arr, options.unorderedSets !== false); }, _file: function(file) { write('file:'); return this.dispatch([file.name, file.size, file.type, file.lastModfied]); }, _blob: function() { if (options.ignoreUnknown) { return write('[blob]'); } throw Error('Hashing Blob objects is currently not supported\n' + '(see https://github.com/puleos/object-hash/issues/26)\n' + 'Use "options.replacer" or "options.ignoreUnknown"\n'); }, _domwindow: function() { return write('domwindow'); }, _bigint: function(number){ return write('bigint:' + number.toString()); }, /* Node.js standard native objects */ _process: function() { return write('process'); }, _timer: function() { return write('timer'); }, _pipe: function() { return write('pipe'); }, _tcp: function() { return write('tcp'); }, _udp: function() { return write('udp'); }, _tty: function() { return write('tty'); }, _statwatcher: function() { return write('statwatcher'); }, _securecontext: function() { return write('securecontext'); }, _connection: function() { return write('connection'); }, _zlib: function() { return write('zlib'); }, _context: function() { return write('context'); }, _nodescript: function() { return write('nodescript'); }, _httpparser: function() { return write('httpparser'); }, _dataview: function() { return write('dataview'); }, _signal: function() { return write('signal'); }, _fsevent: function() { return write('fsevent'); }, _tlswrap: function() { return write('tlswrap'); }, }; } // Mini-implementation of stream.PassThrough // We are far from having need for the full implementation, and we can // make assumptions like "many writes, then only one final read" // and we can ignore encoding specifics function PassThrough() { return { buf: '', write: function(b) { this.buf += b; }, end: function(b) { this.buf += b; }, read: function() { return this.buf; } }; } /***/ }), /***/ 57015: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const ANY = Symbol('SemVer ANY') // hoisted class for cyclic dependency class Comparator { static get ANY () { return ANY } constructor (comp, options) { options = parseOptions(options) if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } comp = comp.trim().split(/\s+/).join(' ') debug('comparator', comp, options) this.options = options this.loose = !!options.loose this.parse(comp) if (this.semver === ANY) { this.value = '' } else { this.value = this.operator + this.semver.version } debug('comp', this) } parse (comp) { const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] const m = comp.match(r) if (!m) { throw new TypeError(`Invalid comparator: ${comp}`) } this.operator = m[1] !== undefined ? m[1] : '' if (this.operator === '=') { this.operator = '' } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY } else { this.semver = new SemVer(m[2], this.options.loose) } } toString () { return this.value } test (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY || version === ANY) { return true } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } return cmp(version, this.operator, this.semver, this.options) } intersects (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (this.operator === '') { if (this.value === '') { return true } return new Range(comp.value, options).test(this.value) } else if (comp.operator === '') { if (comp.value === '') { return true } return new Range(this.value, options).test(comp.semver) } options = parseOptions(options) // Special cases where nothing can possibly be lower if (options.includePrerelease && (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { return false } if (!options.includePrerelease && (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { return false } // Same direction increasing (> or >=) if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { return true } // Same direction decreasing (< or <=) if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { return true } // same SemVer and both sides are inclusive (<= or >=) if ( (this.semver.version === comp.semver.version) && this.operator.includes('=') && comp.operator.includes('=')) { return true } // opposite directions less than if (cmp(this.semver, '<', comp.semver, options) && this.operator.startsWith('>') && comp.operator.startsWith('<')) { return true } // opposite directions greater than if (cmp(this.semver, '>', comp.semver, options) && this.operator.startsWith('<') && comp.operator.startsWith('>')) { return true } return false } } module.exports = Comparator const parseOptions = __webpack_require__(49149) const { safeRe: re, t } = __webpack_require__(3339) const cmp = __webpack_require__(47102) const debug = __webpack_require__(46586) const SemVer = __webpack_require__(82555) const Range = __webpack_require__(9461) /***/ }), /***/ 9461: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // hoisted class for cyclic dependency class Range { constructor (range, options) { options = parseOptions(options) if (range instanceof Range) { if ( range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease ) { return range } else { return new Range(range.raw, options) } } if (range instanceof Comparator) { // just put it in the set and return this.raw = range.value this.set = [[range]] this.format() return this } this.options = options this.loose = !!options.loose this.includePrerelease = !!options.includePrerelease // First reduce all whitespace as much as possible so we do not have to rely // on potentially slow regexes like \s*. This is then stored and used for // future error messages as well. this.raw = range .trim() .split(/\s+/) .join(' ') // First, split on || this.set = this.raw .split('||') // map the range to a 2d array of comparators .map(r => this.parseRange(r.trim())) // throw out any comparator lists that are empty // this generally means that it was not a valid range, which is allowed // in loose mode, but will still throw if the WHOLE range is invalid. .filter(c => c.length) if (!this.set.length) { throw new TypeError(`Invalid SemVer Range: ${this.raw}`) } // if we have any that are not the null set, throw out null sets. if (this.set.length > 1) { // keep the first one, in case they're all null sets const first = this.set[0] this.set = this.set.filter(c => !isNullSet(c[0])) if (this.set.length === 0) { this.set = [first] } else if (this.set.length > 1) { // if we have any that are *, then the range is just * for (const c of this.set) { if (c.length === 1 && isAny(c[0])) { this.set = [c] break } } } } this.format() } format () { this.range = this.set .map((comps) => comps.join(' ').trim()) .join('||') .trim() return this.range } toString () { return this.range } parseRange (range) { // memoize range parsing for performance. // this is a very hot path, and fully deterministic. const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE) const memoKey = memoOpts + ':' + range const cached = cache.get(memoKey) if (cached) { return cached } const loose = this.options.loose // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range) // `~ 1.2.3` => `~1.2.3` range = range.replace(re[t.TILDETRIM], tildeTrimReplace) debug('tilde trim', range) // `^ 1.2.3` => `^1.2.3` range = range.replace(re[t.CARETTRIM], caretTrimReplace) debug('caret trim', range) // At this point, the range is completely trimmed and // ready to be split into comparators. let rangeList = range .split(' ') .map(comp => parseComparator(comp, this.options)) .join(' ') .split(/\s+/) // >=0.0.0 is equivalent to * .map(comp => replaceGTE0(comp, this.options)) if (loose) { // in loose mode, throw out any that are not valid comparators rangeList = rangeList.filter(comp => { debug('loose invalid filter', comp, this.options) return !!comp.match(re[t.COMPARATORLOOSE]) }) } debug('range list', rangeList) // if any comparators are the null set, then replace with JUST null set // if more than one comparator, remove any * comparators // also, don't include the same comparator more than once const rangeMap = new Map() const comparators = rangeList.map(comp => new Comparator(comp, this.options)) for (const comp of comparators) { if (isNullSet(comp)) { return [comp] } rangeMap.set(comp.value, comp) } if (rangeMap.size > 1 && rangeMap.has('')) { rangeMap.delete('') } const result = [...rangeMap.values()] cache.set(memoKey, result) return result } intersects (range, options) { if (!(range instanceof Range)) { throw new TypeError('a Range is required') } return this.set.some((thisComparators) => { return ( isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => { return ( isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { return rangeComparators.every((rangeComparator) => { return thisComparator.intersects(rangeComparator, options) }) }) ) }) ) }) } // if ANY of the sets match ALL of its comparators, then pass test (version) { if (!version) { return false } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } for (let i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true } } return false } } module.exports = Range const LRU = __webpack_require__(42114) const cache = new LRU({ max: 1000 }) const parseOptions = __webpack_require__(49149) const Comparator = __webpack_require__(57015) const debug = __webpack_require__(46586) const SemVer = __webpack_require__(82555) const { safeRe: re, t, comparatorTrimReplace, tildeTrimReplace, caretTrimReplace, } = __webpack_require__(3339) const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __webpack_require__(23489) const isNullSet = c => c.value === '<0.0.0-0' const isAny = c => c.value === '' // take a set of comparators and determine whether there // exists a version which can satisfy it const isSatisfiable = (comparators, options) => { let result = true const remainingComparators = comparators.slice() let testComparator = remainingComparators.pop() while (result && remainingComparators.length) { result = remainingComparators.every((otherComparator) => { return testComparator.intersects(otherComparator, options) }) testComparator = remainingComparators.pop() } return result } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. const parseComparator = (comp, options) => { debug('comp', comp, options) comp = replaceCarets(comp, options) debug('caret', comp) comp = replaceTildes(comp, options) debug('tildes', comp) comp = replaceXRanges(comp, options) debug('xrange', comp) comp = replaceStars(comp, options) debug('stars', comp) return comp } const isX = id => !id || id.toLowerCase() === 'x' || id === '*' // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 // ~0.0.1 --> >=0.0.1 <0.1.0-0 const replaceTildes = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceTilde(c, options)) .join(' ') } const replaceTilde = (comp, options) => { const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] return comp.replace(r, (_, M, m, p, pr) => { debug('tilde', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0 <${+M + 1}.0.0-0` } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0-0 ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` } else if (pr) { debug('replaceTilde pr', pr) ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } else { // ~1.2.3 == >=1.2.3 <1.3.0-0 ret = `>=${M}.${m}.${p } <${M}.${+m + 1}.0-0` } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 // ^1.2.3 --> >=1.2.3 <2.0.0-0 // ^1.2.0 --> >=1.2.0 <2.0.0-0 // ^0.0.1 --> >=0.0.1 <0.0.2-0 // ^0.1.0 --> >=0.1.0 <0.2.0-0 const replaceCarets = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceCaret(c, options)) .join(' ') } const replaceCaret = (comp, options) => { debug('caret', comp, options) const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] const z = options.includePrerelease ? '-0' : '' return comp.replace(r, (_, M, m, p, pr) => { debug('caret', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` } else if (isX(p)) { if (M === '0') { ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` } else { ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p}-${pr } <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p}-${pr } <${+M + 1}.0.0-0` } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p }${z} <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p }${z} <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p } <${+M + 1}.0.0-0` } } debug('caret return', ret) return ret }) } const replaceXRanges = (comp, options) => { debug('replaceXRanges', comp, options) return comp .split(/\s+/) .map((c) => replaceXRange(c, options)) .join(' ') } const replaceXRange = (comp, options) => { comp = comp.trim() const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] return comp.replace(r, (ret, gtlt, M, m, p, pr) => { debug('xRange', comp, ret, gtlt, M, m, p, pr) const xM = isX(M) const xm = xM || isX(m) const xp = xm || isX(p) const anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } // if we're including prereleases in the match, then we need // to fix this to -0, the lowest possible prerelease value pr = options.includePrerelease ? '-0' : '' if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0-0' } else { // nothing is forbidden ret = '*' } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0 } p = 0 if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 gtlt = '>=' if (xm) { M = +M + 1 m = 0 p = 0 } else { m = +m + 1 p = 0 } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<' if (xm) { M = +M + 1 } else { m = +m + 1 } } if (gtlt === '<') { pr = '-0' } ret = `${gtlt + M}.${m}.${p}${pr}` } else if (xm) { ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` } else if (xp) { ret = `>=${M}.${m}.0${pr } <${M}.${+m + 1}.0-0` } debug('xRange return', ret) return ret }) } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. const replaceStars = (comp, options) => { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp .trim() .replace(re[t.STAR], '') } const replaceGTE0 = (comp, options) => { debug('replaceGTE0', comp, options) return comp .trim() .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') } // This function is passed to string.replace(re[t.HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 const hyphenReplace = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) => { if (isX(fM)) { from = '' } else if (isX(fm)) { from = `>=${fM}.0.0${incPr ? '-0' : ''}` } else if (isX(fp)) { from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` } else if (fpr) { from = `>=${from}` } else { from = `>=${from}${incPr ? '-0' : ''}` } if (isX(tM)) { to = '' } else if (isX(tm)) { to = `<${+tM + 1}.0.0-0` } else if (isX(tp)) { to = `<${tM}.${+tm + 1}.0-0` } else if (tpr) { to = `<=${tM}.${tm}.${tp}-${tpr}` } else if (incPr) { to = `<${tM}.${tm}.${+tp + 1}-0` } else { to = `<=${to}` } return `${from} ${to}`.trim() } const testSet = (set, version, options) => { for (let i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (let i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === Comparator.ANY) { continue } if (set[i].semver.prerelease.length > 0) { const allowed = set[i].semver if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } /***/ }), /***/ 82555: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const debug = __webpack_require__(46586) const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(23489) const { safeRe: re, t } = __webpack_require__(3339) const parseOptions = __webpack_require__(49149) const { compareIdentifiers } = __webpack_require__(98726) class SemVer { constructor (version, options) { options = parseOptions(options) if (version instanceof SemVer) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) } if (version.length > MAX_LENGTH) { throw new TypeError( `version is longer than ${MAX_LENGTH} characters` ) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose // this isn't actually relevant for versions, but keep it so that we // don't run into trouble passing this.options around. this.includePrerelease = !!options.includePrerelease const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) if (!m) { throw new TypeError(`Invalid Version: ${version}`) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map((id) => { if (/^[0-9]+$/.test(id)) { const num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } format () { this.version = `${this.major}.${this.minor}.${this.patch}` if (this.prerelease.length) { this.version += `-${this.prerelease.join('.')}` } return this.version } toString () { return this.version } compare (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { if (typeof other === 'string' && other === this.version) { return 0 } other = new SemVer(other, this.options) } if (other.version === this.version) { return 0 } return this.compareMain(other) || this.comparePre(other) } compareMain (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return ( compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) ) } comparePre (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } let i = 0 do { const a = this.prerelease[i] const b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } compareBuild (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } let i = 0 do { const a = this.build[i] const b = other.build[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc (release, identifier, identifierBase) { switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier, identifierBase) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier, identifierBase) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier, identifierBase) this.inc('pre', identifier, identifierBase) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier, identifierBase) } this.inc('pre', identifier, identifierBase) break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if ( this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0 ) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. case 'pre': { const base = Number(identifierBase) ? 1 : 0 if (!identifier && identifierBase === false) { throw new Error('invalid increment argument: identifier is empty') } if (this.prerelease.length === 0) { this.prerelease = [base] } else { let i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything if (identifier === this.prerelease.join('.') && identifierBase === false) { throw new Error('invalid increment argument: identifier already exists') } this.prerelease.push(base) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 let prerelease = [identifier, base] if (identifierBase === false) { prerelease = [identifier] } if (compareIdentifiers(this.prerelease[0], identifier) === 0) { if (isNaN(this.prerelease[1])) { this.prerelease = prerelease } } else { this.prerelease = prerelease } } break } default: throw new Error(`invalid increment argument: ${release}`) } this.raw = this.format() if (this.build.length) { this.raw += `+${this.build.join('.')}` } return this } } module.exports = SemVer /***/ }), /***/ 44740: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(79155) const clean = (version, options) => { const s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } module.exports = clean /***/ }), /***/ 47102: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const eq = __webpack_require__(68236) const neq = __webpack_require__(92115) const gt = __webpack_require__(19316) const gte = __webpack_require__(50249) const lt = __webpack_require__(8834) const lte = __webpack_require__(45962) const cmp = (a, op, b, loose) => { switch (op) { case '===': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a === b case '!==': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError(`Invalid operator: ${op}`) } } module.exports = cmp /***/ }), /***/ 12294: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(82555) const parse = __webpack_require__(79155) const { safeRe: re, t } = __webpack_require__(3339) const coerce = (version, options) => { if (version instanceof SemVer) { return version } if (typeof version === 'number') { version = String(version) } if (typeof version !== 'string') { return null } options = options || {} let match = null if (!options.rtl) { match = version.match(re[t.COERCE]) } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' // // Walk through the string checking with a /g regexp // Manually set the index so as to pick up overlapping matches. // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. let next while ((next = re[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next } re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length } // leave it in a clean state re[t.COERCERTL].lastIndex = -1 } if (match === null) { return null } return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) } module.exports = coerce /***/ }), /***/ 32335: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(82555) const compareBuild = (a, b, loose) => { const versionA = new SemVer(a, loose) const versionB = new SemVer(b, loose) return versionA.compare(versionB) || versionA.compareBuild(versionB) } module.exports = compareBuild /***/ }), /***/ 49639: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(56198) const compareLoose = (a, b) => compare(a, b, true) module.exports = compareLoose /***/ }), /***/ 56198: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(82555) const compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)) module.exports = compare /***/ }), /***/ 24720: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(79155) const diff = (version1, version2) => { const v1 = parse(version1, null, true) const v2 = parse(version2, null, true) const comparison = v1.compare(v2) if (comparison === 0) { return null } const v1Higher = comparison > 0 const highVersion = v1Higher ? v1 : v2 const lowVersion = v1Higher ? v2 : v1 const highHasPre = !!highVersion.prerelease.length const lowHasPre = !!lowVersion.prerelease.length if (lowHasPre && !highHasPre) { // Going from prerelease -> no prerelease requires some special casing // If the low version has only a major, then it will always be a major // Some examples: // 1.0.0-1 -> 1.0.0 // 1.0.0-1 -> 1.1.1 // 1.0.0-1 -> 2.0.0 if (!lowVersion.patch && !lowVersion.minor) { return 'major' } // Otherwise it can be determined by checking the high version if (highVersion.patch) { // anything higher than a patch bump would result in the wrong version return 'patch' } if (highVersion.minor) { // anything higher than a minor bump would result in the wrong version return 'minor' } // bumping major/minor/patch all have same result return 'major' } // add the `pre` prefix if we are going to a prerelease version const prefix = highHasPre ? 'pre' : '' if (v1.major !== v2.major) { return prefix + 'major' } if (v1.minor !== v2.minor) { return prefix + 'minor' } if (v1.patch !== v2.patch) { return prefix + 'patch' } // high and low are preleases return 'prerelease' } module.exports = diff /***/ }), /***/ 68236: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(56198) const eq = (a, b, loose) => compare(a, b, loose) === 0 module.exports = eq /***/ }), /***/ 19316: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(56198) const gt = (a, b, loose) => compare(a, b, loose) > 0 module.exports = gt /***/ }), /***/ 50249: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(56198) const gte = (a, b, loose) => compare(a, b, loose) >= 0 module.exports = gte /***/ }), /***/ 42876: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(82555) const inc = (version, release, options, identifier, identifierBase) => { if (typeof (options) === 'string') { identifierBase = identifier identifier = options options = undefined } try { return new SemVer( version instanceof SemVer ? version.version : version, options ).inc(release, identifier, identifierBase).version } catch (er) { return null } } module.exports = inc /***/ }), /***/ 8834: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(56198) const lt = (a, b, loose) => compare(a, b, loose) < 0 module.exports = lt /***/ }), /***/ 45962: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(56198) const lte = (a, b, loose) => compare(a, b, loose) <= 0 module.exports = lte /***/ }), /***/ 22755: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(82555) const major = (a, loose) => new SemVer(a, loose).major module.exports = major /***/ }), /***/ 5683: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(82555) const minor = (a, loose) => new SemVer(a, loose).minor module.exports = minor /***/ }), /***/ 92115: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(56198) const neq = (a, b, loose) => compare(a, b, loose) !== 0 module.exports = neq /***/ }), /***/ 79155: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(82555) const parse = (version, options, throwErrors = false) => { if (version instanceof SemVer) { return version } try { return new SemVer(version, options) } catch (er) { if (!throwErrors) { return null } throw er } } module.exports = parse /***/ }), /***/ 30162: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(82555) const patch = (a, loose) => new SemVer(a, loose).patch module.exports = patch /***/ }), /***/ 25127: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(79155) const prerelease = (version, options) => { const parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } module.exports = prerelease /***/ }), /***/ 17886: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(56198) const rcompare = (a, b, loose) => compare(b, a, loose) module.exports = rcompare /***/ }), /***/ 3565: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(32335) const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) module.exports = rsort /***/ }), /***/ 65345: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(9461) const satisfies = (version, range, options) => { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } module.exports = satisfies /***/ }), /***/ 91421: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(32335) const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) module.exports = sort /***/ }), /***/ 98828: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(79155) const valid = (version, options) => { const v = parse(version, options) return v ? v.version : null } module.exports = valid /***/ }), /***/ 5739: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // just pre-load all the stuff that index.js lazily exports const internalRe = __webpack_require__(3339) const constants = __webpack_require__(23489) const SemVer = __webpack_require__(82555) const identifiers = __webpack_require__(98726) const parse = __webpack_require__(79155) const valid = __webpack_require__(98828) const clean = __webpack_require__(44740) const inc = __webpack_require__(42876) const diff = __webpack_require__(24720) const major = __webpack_require__(22755) const minor = __webpack_require__(5683) const patch = __webpack_require__(30162) const prerelease = __webpack_require__(25127) const compare = __webpack_require__(56198) const rcompare = __webpack_require__(17886) const compareLoose = __webpack_require__(49639) const compareBuild = __webpack_require__(32335) const sort = __webpack_require__(91421) const rsort = __webpack_require__(3565) const gt = __webpack_require__(19316) const lt = __webpack_require__(8834) const eq = __webpack_require__(68236) const neq = __webpack_require__(92115) const gte = __webpack_require__(50249) const lte = __webpack_require__(45962) const cmp = __webpack_require__(47102) const coerce = __webpack_require__(12294) const Comparator = __webpack_require__(57015) const Range = __webpack_require__(9461) const satisfies = __webpack_require__(65345) const toComparators = __webpack_require__(96962) const maxSatisfying = __webpack_require__(85275) const minSatisfying = __webpack_require__(21344) const minVersion = __webpack_require__(52768) const validRange = __webpack_require__(259) const outside = __webpack_require__(28123) const gtr = __webpack_require__(11748) const ltr = __webpack_require__(5596) const intersects = __webpack_require__(7627) const simplifyRange = __webpack_require__(27672) const subset = __webpack_require__(60961) module.exports = { parse, valid, clean, inc, diff, major, minor, patch, prerelease, compare, rcompare, compareLoose, compareBuild, sort, rsort, gt, lt, eq, neq, gte, lte, cmp, coerce, Comparator, Range, satisfies, toComparators, maxSatisfying, minSatisfying, minVersion, validRange, outside, gtr, ltr, intersects, simplifyRange, subset, SemVer, re: internalRe.re, src: internalRe.src, tokens: internalRe.t, SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, RELEASE_TYPES: constants.RELEASE_TYPES, compareIdentifiers: identifiers.compareIdentifiers, rcompareIdentifiers: identifiers.rcompareIdentifiers, } /***/ }), /***/ 23489: /***/ ((module) => { // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. const SEMVER_SPEC_VERSION = '2.0.0' const MAX_LENGTH = 256 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. const MAX_SAFE_COMPONENT_LENGTH = 16 // Max safe length for a build identifier. The max length minus 6 characters for // the shortest version with a build 0.0.0+BUILD. const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 const RELEASE_TYPES = [ 'major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease', ] module.exports = { MAX_LENGTH, MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_SAFE_INTEGER, RELEASE_TYPES, SEMVER_SPEC_VERSION, FLAG_INCLUDE_PRERELEASE: 0b001, FLAG_LOOSE: 0b010, } /***/ }), /***/ 46586: /***/ ((module) => { const debug = ( typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ) ? (...args) => console.error('SEMVER', ...args) : () => {} module.exports = debug /***/ }), /***/ 98726: /***/ ((module) => { const numeric = /^[0-9]+$/ const compareIdentifiers = (a, b) => { const anum = numeric.test(a) const bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) module.exports = { compareIdentifiers, rcompareIdentifiers, } /***/ }), /***/ 49149: /***/ ((module) => { // parse out just the options we care about const looseOption = Object.freeze({ loose: true }) const emptyOpts = Object.freeze({ }) const parseOptions = options => { if (!options) { return emptyOpts } if (typeof options !== 'object') { return looseOption } return options } module.exports = parseOptions /***/ }), /***/ 3339: /***/ ((module, exports, __webpack_require__) => { const { MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_LENGTH, } = __webpack_require__(23489) const debug = __webpack_require__(46586) exports = module.exports = {} // The actual regexps go on exports.re const re = exports.re = [] const safeRe = exports.safeRe = [] const src = exports.src = [] const t = exports.t = {} let R = 0 const LETTERDASHNUMBER = '[a-zA-Z0-9-]' // Replace some greedy regex tokens to prevent regex dos issues. These regex are // used internally via the safeRe object since all inputs in this library get // normalized first to trim and collapse all extra whitespace. The original // regexes are exported for userland consumption and lower level usage. A // future breaking change could export the safer regex only with a note that // all input should have extra whitespace removed. const safeRegexReplacements = [ ['\\s', 1], ['\\d', MAX_LENGTH], [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], ] const makeSafeRegex = (value) => { for (const [token, max] of safeRegexReplacements) { value = value .split(`${token}*`).join(`${token}{0,${max}}`) .split(`${token}+`).join(`${token}{1,${max}}`) } return value } const createToken = (name, value, isGlobal) => { const safe = makeSafeRegex(value) const index = R++ debug(name, index, value) t[name] = index src[index] = value re[index] = new RegExp(value, isGlobal ? 'g' : undefined) safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) } // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') createToken('NUMERICIDENTIFIERLOOSE', '\\d+') // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) // ## Main Version // Three dot-separated numeric identifiers. createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`) createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] }|${src[t.NONNUMERICIDENTIFIER]})`) createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] }|${src[t.NONNUMERICIDENTIFIER]})`) // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] }(?:\\.${src[t.BUILDIDENTIFIER]})*))`) // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. createToken('FULLPLAIN', `v?${src[t.MAINVERSION] }${src[t.PRERELEASE]}?${ src[t.BUILD]}?`) createToken('FULL', `^${src[t.FULLPLAIN]}$`) // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] }${src[t.PRERELEASELOOSE]}?${ src[t.BUILD]}?`) createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) createToken('GTLT', '((?:<|>)?=?)') // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) // Coercion. // Extract anything that could conceivably be a part of a valid semver createToken('COERCE', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:$|[^\\d])`) createToken('COERCERTL', src[t.COERCE], true) // Tilde ranges. // Meaning is "reasonably at or greater than" createToken('LONETILDE', '(?:~>?)') createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) exports.tildeTrimReplace = '$1~' createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) // Caret ranges. // Meaning is "at least and backwards compatible with" createToken('LONECARET', '(?:\\^)') createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) exports.caretTrimReplace = '$1^' createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) // A simple gt/lt/eq thing, or just "" to indicate "any version" createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) exports.comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`) createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`) // Star ranges basically just allow anything at all. createToken('STAR', '(<|>)?=?\\s*\\*') // >=0.0.0 is like a star createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') /***/ }), /***/ 11748: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Determine if version is greater than all the versions possible in the range. const outside = __webpack_require__(28123) const gtr = (version, range, options) => outside(version, range, '>', options) module.exports = gtr /***/ }), /***/ 7627: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(9461) const intersects = (r1, r2, options) => { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2, options) } module.exports = intersects /***/ }), /***/ 5596: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const outside = __webpack_require__(28123) // Determine if version is less than all the versions possible in the range const ltr = (version, range, options) => outside(version, range, '<', options) module.exports = ltr /***/ }), /***/ 85275: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(82555) const Range = __webpack_require__(9461) const maxSatisfying = (versions, range, options) => { let max = null let maxSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } module.exports = maxSatisfying /***/ }), /***/ 21344: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(82555) const Range = __webpack_require__(9461) const minSatisfying = (versions, range, options) => { let min = null let minSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } module.exports = minSatisfying /***/ }), /***/ 52768: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(82555) const Range = __webpack_require__(9461) const gt = __webpack_require__(19316) const minVersion = (range, loose) => { range = new Range(range, loose) let minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let setMin = null comparators.forEach((comparator) => { // Clone to avoid manipulating the comparator's semver object. const compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!setMin || gt(compver, setMin)) { setMin = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error(`Unexpected operation: ${comparator.operator}`) } }) if (setMin && (!minver || gt(minver, setMin))) { minver = setMin } } if (minver && range.test(minver)) { return minver } return null } module.exports = minVersion /***/ }), /***/ 28123: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(82555) const Comparator = __webpack_require__(57015) const { ANY } = Comparator const Range = __webpack_require__(9461) const satisfies = __webpack_require__(65345) const gt = __webpack_require__(19316) const lt = __webpack_require__(8834) const lte = __webpack_require__(45962) const gte = __webpack_require__(50249) const outside = (version, range, hilo, options) => { version = new SemVer(version, options) range = new Range(range, options) let gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisfies the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let high = null let low = null comparators.forEach((comparator) => { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } module.exports = outside /***/ }), /***/ 27672: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // given a set of versions and a range, create a "simplified" range // that includes the same versions that the original range does // If the original range is shorter than the simplified one, return that. const satisfies = __webpack_require__(65345) const compare = __webpack_require__(56198) module.exports = (versions, range, options) => { const set = [] let first = null let prev = null const v = versions.sort((a, b) => compare(a, b, options)) for (const version of v) { const included = satisfies(version, range, options) if (included) { prev = version if (!first) { first = version } } else { if (prev) { set.push([first, prev]) } prev = null first = null } } if (first) { set.push([first, null]) } const ranges = [] for (const [min, max] of set) { if (min === max) { ranges.push(min) } else if (!max && min === v[0]) { ranges.push('*') } else if (!max) { ranges.push(`>=${min}`) } else if (min === v[0]) { ranges.push(`<=${max}`) } else { ranges.push(`${min} - ${max}`) } } const simplified = ranges.join(' || ') const original = typeof range.raw === 'string' ? range.raw : String(range) return simplified.length < original.length ? simplified : range } /***/ }), /***/ 60961: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(9461) const Comparator = __webpack_require__(57015) const { ANY } = Comparator const satisfies = __webpack_require__(65345) const compare = __webpack_require__(56198) // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: // - Every simple range `r1, r2, ...` is a null set, OR // - Every simple range `r1, r2, ...` which is not a null set is a subset of // some `R1, R2, ...` // // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: // - If c is only the ANY comparator // - If C is only the ANY comparator, return true // - Else if in prerelease mode, return false // - else replace c with `[>=0.0.0]` // - If C is only the ANY comparator // - if in prerelease mode, return true // - else replace C with `[>=0.0.0]` // - Let EQ be the set of = comparators in c // - If EQ is more than one, return true (null set) // - Let GT be the highest > or >= comparator in c // - Let LT be the lowest < or <= comparator in c // - If GT and LT, and GT.semver > LT.semver, return true (null set) // - If any C is a = range, and GT or LT are set, return false // - If EQ // - If GT, and EQ does not satisfy GT, return true (null set) // - If LT, and EQ does not satisfy LT, return true (null set) // - If EQ satisfies every C, return true // - Else return false // - If GT // - If GT.semver is lower than any > or >= comp in C, return false // - If GT is >=, and GT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the GT.semver tuple, return false // - If LT // - If LT.semver is greater than any < or <= comp in C, return false // - If LT is <=, and LT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the LT.semver tuple, return false // - Else return true const subset = (sub, dom, options = {}) => { if (sub === dom) { return true } sub = new Range(sub, options) dom = new Range(dom, options) let sawNonNull = false OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { const isSub = simpleSubset(simpleSub, simpleDom, options) sawNonNull = sawNonNull || isSub !== null if (isSub) { continue OUTER } } // the null set is a subset of everything, but null simple ranges in // a complex range should be ignored. so if we saw a non-null range, // then we know this isn't a subset, but if EVERY simple range was null, // then it is a subset. if (sawNonNull) { return false } } return true } const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] const minimumVersion = [new Comparator('>=0.0.0')] const simpleSubset = (sub, dom, options) => { if (sub === dom) { return true } if (sub.length === 1 && sub[0].semver === ANY) { if (dom.length === 1 && dom[0].semver === ANY) { return true } else if (options.includePrerelease) { sub = minimumVersionWithPreRelease } else { sub = minimumVersion } } if (dom.length === 1 && dom[0].semver === ANY) { if (options.includePrerelease) { return true } else { dom = minimumVersion } } const eqSet = new Set() let gt, lt for (const c of sub) { if (c.operator === '>' || c.operator === '>=') { gt = higherGT(gt, c, options) } else if (c.operator === '<' || c.operator === '<=') { lt = lowerLT(lt, c, options) } else { eqSet.add(c.semver) } } if (eqSet.size > 1) { return null } let gtltComp if (gt && lt) { gtltComp = compare(gt.semver, lt.semver, options) if (gtltComp > 0) { return null } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { return null } } // will iterate one or zero times for (const eq of eqSet) { if (gt && !satisfies(eq, String(gt), options)) { return null } if (lt && !satisfies(eq, String(lt), options)) { return null } for (const c of dom) { if (!satisfies(eq, String(c), options)) { return false } } return true } let higher, lower let hasDomLT, hasDomGT // if the subset has a prerelease, we need a comparator in the superset // with the same tuple and a prerelease, or it's not a subset let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false // exception: <1.2.3-0 is the same as <1.2.3 if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { needDomLTPre = false } for (const c of dom) { hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' if (gt) { if (needDomGTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { needDomGTPre = false } } if (c.operator === '>' || c.operator === '>=') { higher = higherGT(gt, c, options) if (higher === c && higher !== gt) { return false } } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { return false } } if (lt) { if (needDomLTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { needDomLTPre = false } } if (c.operator === '<' || c.operator === '<=') { lower = lowerLT(lt, c, options) if (lower === c && lower !== lt) { return false } } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { return false } } if (!c.operator && (lt || gt) && gtltComp !== 0) { return false } } // if there was a < or >, and nothing in the dom, then must be false // UNLESS it was limited by another range in the other direction. // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 if (gt && hasDomLT && !lt && gtltComp !== 0) { return false } if (lt && hasDomGT && !gt && gtltComp !== 0) { return false } // we needed a prerelease range in a specific tuple, but didn't get one // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, // because it includes prereleases in the 1.2.3 tuple if (needDomGTPre || needDomLTPre) { return false } return true } // >=1.2.3 is lower than >1.2.3 const higherGT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp > 0 ? a : comp < 0 ? b : b.operator === '>' && a.operator === '>=' ? b : a } // <=1.2.3 is higher than <1.2.3 const lowerLT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp < 0 ? a : comp > 0 ? b : b.operator === '<' && a.operator === '<=' ? b : a } module.exports = subset /***/ }), /***/ 96962: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(9461) // Mostly just for testing and legacy API reasons const toComparators = (range, options) => new Range(range, options).set .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) module.exports = toComparators /***/ }), /***/ 259: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(9461) const validRange = (range, options) => { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } module.exports = validRange /***/ }), /***/ 67765: /***/ ((module) => { "use strict"; module.exports = function (Yallist) { Yallist.prototype[Symbol.iterator] = function* () { for (let walker = this.head; walker; walker = walker.next) { yield walker.value } } } /***/ }), /***/ 351: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = Yallist Yallist.Node = Node Yallist.create = Yallist function Yallist (list) { var self = this if (!(self instanceof Yallist)) { self = new Yallist() } self.tail = null self.head = null self.length = 0 if (list && typeof list.forEach === 'function') { list.forEach(function (item) { self.push(item) }) } else if (arguments.length > 0) { for (var i = 0, l = arguments.length; i < l; i++) { self.push(arguments[i]) } } return self } Yallist.prototype.removeNode = function (node) { if (node.list !== this) { throw new Error('removing node which does not belong to this list') } var next = node.next var prev = node.prev if (next) { next.prev = prev } if (prev) { prev.next = next } if (node === this.head) { this.head = next } if (node === this.tail) { this.tail = prev } node.list.length-- node.next = null node.prev = null node.list = null return next } Yallist.prototype.unshiftNode = function (node) { if (node === this.head) { return } if (node.list) { node.list.removeNode(node) } var head = this.head node.list = this node.next = head if (head) { head.prev = node } this.head = node if (!this.tail) { this.tail = node } this.length++ } Yallist.prototype.pushNode = function (node) { if (node === this.tail) { return } if (node.list) { node.list.removeNode(node) } var tail = this.tail node.list = this node.prev = tail if (tail) { tail.next = node } this.tail = node if (!this.head) { this.head = node } this.length++ } Yallist.prototype.push = function () { for (var i = 0, l = arguments.length; i < l; i++) { push(this, arguments[i]) } return this.length } Yallist.prototype.unshift = function () { for (var i = 0, l = arguments.length; i < l; i++) { unshift(this, arguments[i]) } return this.length } Yallist.prototype.pop = function () { if (!this.tail) { return undefined } var res = this.tail.value this.tail = this.tail.prev if (this.tail) { this.tail.next = null } else { this.head = null } this.length-- return res } Yallist.prototype.shift = function () { if (!this.head) { return undefined } var res = this.head.value this.head = this.head.next if (this.head) { this.head.prev = null } else { this.tail = null } this.length-- return res } Yallist.prototype.forEach = function (fn, thisp) { thisp = thisp || this for (var walker = this.head, i = 0; walker !== null; i++) { fn.call(thisp, walker.value, i, this) walker = walker.next } } Yallist.prototype.forEachReverse = function (fn, thisp) { thisp = thisp || this for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { fn.call(thisp, walker.value, i, this) walker = walker.prev } } Yallist.prototype.get = function (n) { for (var i = 0, walker = this.head; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.next } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.getReverse = function (n) { for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.prev } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.map = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.head; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.next } return res } Yallist.prototype.mapReverse = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.tail; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.prev } return res } Yallist.prototype.reduce = function (fn, initial) { var acc var walker = this.head if (arguments.length > 1) { acc = initial } else if (this.head) { walker = this.head.next acc = this.head.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = 0; walker !== null; i++) { acc = fn(acc, walker.value, i) walker = walker.next } return acc } Yallist.prototype.reduceReverse = function (fn, initial) { var acc var walker = this.tail if (arguments.length > 1) { acc = initial } else if (this.tail) { walker = this.tail.prev acc = this.tail.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = this.length - 1; walker !== null; i--) { acc = fn(acc, walker.value, i) walker = walker.prev } return acc } Yallist.prototype.toArray = function () { var arr = new Array(this.length) for (var i = 0, walker = this.head; walker !== null; i++) { arr[i] = walker.value walker = walker.next } return arr } Yallist.prototype.toArrayReverse = function () { var arr = new Array(this.length) for (var i = 0, walker = this.tail; walker !== null; i++) { arr[i] = walker.value walker = walker.prev } return arr } Yallist.prototype.slice = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = 0, walker = this.head; walker !== null && i < from; i++) { walker = walker.next } for (; walker !== null && i < to; i++, walker = walker.next) { ret.push(walker.value) } return ret } Yallist.prototype.sliceReverse = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { walker = walker.prev } for (; walker !== null && i > from; i--, walker = walker.prev) { ret.push(walker.value) } return ret } Yallist.prototype.splice = function (start, deleteCount, ...nodes) { if (start > this.length) { start = this.length - 1 } if (start < 0) { start = this.length + start; } for (var i = 0, walker = this.head; walker !== null && i < start; i++) { walker = walker.next } var ret = [] for (var i = 0; walker && i < deleteCount; i++) { ret.push(walker.value) walker = this.removeNode(walker) } if (walker === null) { walker = this.tail } if (walker !== this.head && walker !== this.tail) { walker = walker.prev } for (var i = 0; i < nodes.length; i++) { walker = insert(this, walker, nodes[i]) } return ret; } Yallist.prototype.reverse = function () { var head = this.head var tail = this.tail for (var walker = head; walker !== null; walker = walker.prev) { var p = walker.prev walker.prev = walker.next walker.next = p } this.head = tail this.tail = head return this } function insert (self, node, value) { var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self) if (inserted.next === null) { self.tail = inserted } if (inserted.prev === null) { self.head = inserted } self.length++ return inserted } function push (self, item) { self.tail = new Node(item, self.tail, null, self) if (!self.head) { self.head = self.tail } self.length++ } function unshift (self, item) { self.head = new Node(item, null, self.head, self) if (!self.tail) { self.tail = self.head } self.length++ } function Node (value, prev, next, list) { if (!(this instanceof Node)) { return new Node(value, prev, next, list) } this.list = list this.value = value if (prev) { prev.next = this this.prev = prev } else { this.prev = null } if (next) { next.prev = this this.next = next } else { this.next = null } } try { // add if support for Symbol.iterator is present __webpack_require__(67765)(Yallist) } catch (er) {} /***/ }), /***/ 54151: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.analyzeScmProject = exports.extendAnalysis = exports.analyzeFolders = exports.analyzeBundle = void 0; /* eslint-disable no-await-in-loop */ const lodash_omit_1 = __importDefault(__webpack_require__(76427)); const uuid_1 = __webpack_require__(96771); const files_1 = __webpack_require__(32083); const constants_1 = __webpack_require__(65765); const http_1 = __webpack_require__(60776); const bundles_1 = __webpack_require__(86639); const report_1 = __webpack_require__(17608); const emitter_1 = __webpack_require__(37544); const sleep = (duration) => new Promise(resolve => setTimeout(resolve, duration)); function getConnectionOptions(connectionOptions) { var _a; return { ...connectionOptions, // Ensure requestId is set. requestId: (_a = connectionOptions.requestId) !== null && _a !== void 0 ? _a : uuid_1.v4(), }; } function getAnalysisContext(analysisContext) { return analysisContext ? { analysisContext } : {}; } async function pollAnalysis(options) { let analysisResponse; let analysisData; emitter_1.emitter.analyseProgress({ status: http_1.AnalysisStatus.waiting, progress: 0, }); // eslint-disable-next-line no-constant-condition while (true) { analysisResponse = await http_1.getAnalysis(options); if (analysisResponse.type === 'error') { return analysisResponse; } analysisData = analysisResponse.value; if (analysisData.status === http_1.AnalysisStatus.waiting || analysisData.status === http_1.AnalysisStatus.fetching || analysisData.status === http_1.AnalysisStatus.analyzing || analysisData.status === http_1.AnalysisStatus.done) { // Report progress of fetching emitter_1.emitter.analyseProgress(analysisData); } else if (analysisData.status === http_1.AnalysisStatus.complete) { // Return data of analysis return analysisResponse; // deepcode ignore DuplicateIfBody: false positive it seems that interface is not taken into account } else if (analysisData.status === http_1.AnalysisStatus.failed) { // Report failure of analysing return analysisResponse; } await sleep(constants_1.POLLING_INTERVAL); } } async function analyzeBundle(options) { // Call remote bundle for analysis results and emit intermediate progress const analysisData = await pollAnalysis(options); if (analysisData.type === 'error') { throw analysisData.error; } else if (analysisData.value.status === http_1.AnalysisStatus.failed) { throw new Error('Analysis has failed'); } return analysisData.value; } exports.analyzeBundle = analyzeBundle; function normalizeResultFiles(files, baseDir) { return Object.entries(files).reduce((obj, [path, positions]) => { const filePath = files_1.resolveBundleFilePath(baseDir, path); obj[filePath] = positions; return obj; }, {}); } /** * Perform a file-based analysis. * Optionally with reporting of results to the platform. */ async function analyzeFolders(options) { var _a, _b; const connectionOptions = getConnectionOptions(options.connection); const analysisContext = getAnalysisContext(options.analysisContext); const fileBundle = await bundles_1.createBundleFromFolders({ ...connectionOptions, ...options.fileOptions, languages: options.languages, }); if (fileBundle === null) return null; const config = { bundleHash: fileBundle.bundleHash, ...connectionOptions, ...options.analysisOptions, shard: files_1.calcHash(fileBundle.baseDir), ...analysisContext, }; let analysisResults; // Whether this is a report/result upload operation. const isReport = (_b = (_a = options.reportOptions) === null || _a === void 0 ? void 0 : _a.enabled) !== null && _b !== void 0 ? _b : false; let reportResults; if (isReport && options.reportOptions) { // Analyze and upload bundle results. const reportRes = await report_1.reportBundle({ ...config, report: options.reportOptions, }); analysisResults = reportRes.analysisResult; reportResults = reportRes.uploadResult; } else { // Analyze bundle. analysisResults = await analyzeBundle(config); } if (analysisResults.type === 'legacy') { // expand relative file names to absolute ones only for legacy results analysisResults.files = normalizeResultFiles(analysisResults.files, fileBundle.baseDir); } return { fileBundle, analysisResults, reportResults, ...options }; } exports.analyzeFolders = analyzeFolders; function mergeBundleResults(oldAnalysisResults, newAnalysisResults, limitToFiles, removedFiles = [], baseDir) { if (newAnalysisResults.type == 'sarif') { return mergeSarifResults(oldAnalysisResults, newAnalysisResults, limitToFiles, removedFiles); } return mergeLegacyResults(oldAnalysisResults, newAnalysisResults, limitToFiles, removedFiles, baseDir); } function mergeSarifResults(oldAnalysisResults, newAnalysisResults, limitToFiles, removedFiles = []) { // Start from the new analysis results // For each finding of the old analysis, // if it's location is not part of the limitToFiles or removedFiles (removedFiles should also be checked against condeFlow), // append the finding to the new analysis and check if the rule must be added as well const changedFiles = [...limitToFiles, ...removedFiles]; const sarifResults = (newAnalysisResults.sarif.runs[0].results || []).filter(res => { var _a, _b, _c; // TODO: This should not be necessary in theory but, in case of two identical files, // Bundle Server returns the finding in both files even if limitToFiles only reports one const loc = (_c = (_b = (_a = res.locations) === null || _a === void 0 ? void 0 : _a[0].physicalLocation) === null || _b === void 0 ? void 0 : _b.artifactLocation) === null || _c === void 0 ? void 0 : _c.uri; return loc && changedFiles.includes(loc); }); const sarifRules = newAnalysisResults.sarif.runs[0].tool.driver.rules || []; const oldResults = oldAnalysisResults.sarif.runs[0].results || []; for (const res of oldResults) { // NOTE: Node 10 doesn't support the more readable .flatMap, so we need to use .reduce, but the behaviour would be the following: // const locations: string[] = (res.locations || []).flatMap( // loc => !!loc.physicalLocation?.artifactLocation?.uri ? [loc.physicalLocation.artifactLocation.uri] : [] // ); // const codeFlowLocations: string[] = (res.codeFlows || []).flatMap( // cf => (cf.threadFlows || []).flatMap( // tf => (tf.locations || []).flatMap( // loc => !!loc.location?.physicalLocation?.artifactLocation?.uri ? [loc.location.physicalLocation.artifactLocation.uri] : [] // ) // ) // ); const locations = (res.locations || []).reduce((acc, loc) => { var _a, _b; if ((_b = (_a = loc.physicalLocation) === null || _a === void 0 ? void 0 : _a.artifactLocation) === null || _b === void 0 ? void 0 : _b.uri) { acc.push(loc.physicalLocation.artifactLocation.uri); } return acc; }, []); const codeFlowLocations = (res.codeFlows || []).reduce((acc1, cf) => { acc1.push(...(cf.threadFlows || []).reduce((acc2, tf) => { acc2.push(...(tf.locations || []).reduce((acc3, loc) => { var _a, _b, _c; if ((_c = (_b = (_a = loc.location) === null || _a === void 0 ? void 0 : _a.physicalLocation) === null || _b === void 0 ? void 0 : _b.artifactLocation) === null || _c === void 0 ? void 0 : _c.uri) { acc3.push(loc.location.physicalLocation.artifactLocation.uri); } return acc3; }, [])); return acc2; }, [])); return acc1; }, []); if (locations.some(loc => changedFiles.includes(loc)) || codeFlowLocations.some(loc => removedFiles.includes(loc))) continue; let ruleIndex = sarifRules.findIndex(rule => rule.id === res.ruleId); if (ruleIndex === -1 && res.ruleIndex && oldAnalysisResults.sarif.runs[0].tool.driver.rules && oldAnalysisResults.sarif.runs[0].tool.driver.rules[res.ruleIndex]) { const newLength = sarifRules.push(oldAnalysisResults.sarif.runs[0].tool.driver.rules[res.ruleIndex]); ruleIndex = newLength - 1; } res.ruleIndex = ruleIndex; sarifResults.push(res); } newAnalysisResults.sarif.runs[0].results = sarifResults; newAnalysisResults.sarif.runs[0].tool.driver.rules = sarifRules; return newAnalysisResults; } const moveSuggestionIndexes = (suggestionIndex, suggestions) => { const entries = Object.entries(suggestions); return entries.reduce((obj, [i, s]) => { obj[`${parseInt(i, 10) + suggestionIndex + 1}`] = s; return obj; }, {}); }; function mergeLegacyResults(oldAnalysisResults, newAnalysisResults, limitToFiles, removedFiles = [], baseDir) { // expand relative file names to absolute ones only for legacy results newAnalysisResults.files = normalizeResultFiles(newAnalysisResults.files, baseDir); // Determine max suggestion index in our data const suggestionIndex = Math.max(...Object.keys(oldAnalysisResults.suggestions).map(i => parseInt(i, 10))) || -1; // Addup all new suggestions' indexes const newSuggestions = moveSuggestionIndexes(suggestionIndex, newAnalysisResults.suggestions); const suggestions = { ...oldAnalysisResults.suggestions, ...newSuggestions }; const newFiles = Object.entries(newAnalysisResults.files).reduce((obj, [fn, s]) => { obj[fn] = moveSuggestionIndexes(suggestionIndex, s); return obj; }, {}); // expand relative file names to absolute ones only for legacy results const changedFiles = [...limitToFiles, ...removedFiles].map(path => files_1.resolveBundleFilePath(baseDir, path)); const files = { ...lodash_omit_1.default(oldAnalysisResults.files, changedFiles), ...newFiles, }; return { ...newAnalysisResults, files, suggestions, }; } async function extendAnalysis(options) { const { files, removedFiles } = await files_1.prepareExtendingBundle(options.fileBundle.baseDir, options.fileBundle.supportedFiles, options.fileBundle.fileIgnores, options.files, options.fileOptions.symlinksEnabled); if (!files.length && !removedFiles.length) { return null; // nothing to extend, just return null } // Extend remote bundle const remoteBundle = await bundles_1.remoteBundleFactory({ ...options.connection, bundleHash: options.fileBundle.bundleHash, baseDir: options.fileBundle.baseDir, files, removedFiles, }); if (remoteBundle === null) return null; const fileBundle = { ...options.fileBundle, ...remoteBundle, }; const limitToFiles = files.map(f => f.bundlePath); let analysisResults = await analyzeBundle({ bundleHash: remoteBundle.bundleHash, ...options.connection, ...options.analysisOptions, shard: files_1.calcHash(fileBundle.baseDir), limitToFiles, }); analysisResults = mergeBundleResults(options.analysisResults, analysisResults, limitToFiles, removedFiles, options.fileBundle.baseDir); return { ...options, fileBundle, analysisResults }; } exports.extendAnalysis = extendAnalysis; /** * Perform an SCM-based analysis for an existing project, * with reporting of results to the platform. */ async function analyzeScmProject(options) { const connectionOptions = getConnectionOptions(options.connection); const analysisContext = getAnalysisContext(options.analysisContext); const { analysisResult: analysisResults, uploadResult: reportResults } = await report_1.reportScm({ ...connectionOptions, ...options.analysisOptions, ...options.reportOptions, ...analysisContext, }); return { analysisResults, reportResults }; } exports.analyzeScmProject = analyzeScmProject; //# sourceMappingURL=analysis.js.map /***/ }), /***/ 86639: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createBundleWithCustomFiles = exports.createBundleFromFolders = exports.getSupportedFiles = exports.remoteBundleFactory = exports.uploadRemoteBundle = void 0; /* eslint-disable no-await-in-loop */ const lodash_pick_1 = __importDefault(__webpack_require__(25030)); const lodash_omit_1 = __importDefault(__webpack_require__(76427)); const p_map_1 = __importDefault(__webpack_require__(49503)); const files_1 = __webpack_require__(32083); const http_1 = __webpack_require__(60776); const constants_1 = __webpack_require__(65765); const emitter_1 = __webpack_require__(37544); async function* prepareRemoteBundle(options) { let response; let { bundleHash } = options; let cumulativeProgress = 0; emitter_1.emitter.createBundleProgress(cumulativeProgress, options.files.length); for (const chunkedFiles of files_1.composeFilePayloads(options.files)) { const apiParams = { ...lodash_pick_1.default(options, [ 'baseURL', 'sessionToken', 'source', 'extraHeaders', 'removedFiles', 'requestId', 'org', 'orgId', ]), files: chunkedFiles.reduce((d, f) => { // deepcode ignore PrototypePollution: FP this is an internal code d[f.bundlePath] = f.hash; return d; }, {}), }; if (!bundleHash) { // eslint-disable-next-line no-await-in-loop response = await http_1.createBundle(apiParams); } else { // eslint-disable-next-line no-await-in-loop response = await http_1.extendBundle({ bundleHash, ...apiParams }); } cumulativeProgress += chunkedFiles.length; emitter_1.emitter.createBundleProgress(cumulativeProgress, options.files.length); if (response.type === 'error') { // TODO: process Error yield response; break; } bundleHash = response.value.bundleHash; yield response; } } /** * Splits files in buckets and upload in parallel * @param baseURL * @param sessionToken * @param remoteBundle */ async function uploadRemoteBundle(options) { let uploadedFiles = 0; emitter_1.emitter.uploadBundleProgress(0, options.files.length); const apiParams = lodash_pick_1.default(options, [ 'baseURL', 'sessionToken', 'source', 'bundleHash', 'requestId', 'org', 'orgId', 'extraHeaders', ]); const uploadFileChunks = async (bucketFiles) => { // Note: we specifically create __new__ isolated bundles here to faster files upload const resp = await http_1.createBundle({ ...apiParams, files: bucketFiles.reduce((d, f) => { d[f.bundlePath] = lodash_pick_1.default(f, ['hash', 'content']); return d; }, {}), }); if (resp.type !== 'error') { uploadedFiles += bucketFiles.length; emitter_1.emitter.uploadBundleProgress(uploadedFiles, options.files.length); } }; const files = []; for (const bucketFiles of files_1.composeFilePayloads(options.files)) { files.push(bucketFiles); } await p_map_1.default(files, async (task) => await uploadFileChunks(task), { concurrency: constants_1.UPLOAD_CONCURRENCY, }); } exports.uploadRemoteBundle = uploadRemoteBundle; async function fullfillRemoteBundle(options) { // Fulfill remote bundle by uploading only missing files (splitted in chunks) // Check remove bundle to make sure no missing files left let attempts = 0; let { remoteBundle } = options; const connectionOptions = lodash_pick_1.default(options, [ 'baseURL', 'sessionToken', 'source', 'requestId', 'org', 'orgId', 'extraHeaders', ]); while (remoteBundle.missingFiles.length && attempts < (options.maxAttempts || constants_1.MAX_UPLOAD_ATTEMPTS)) { const missingFiles = await files_1.resolveBundleFiles(options.baseDir, remoteBundle.missingFiles); await uploadRemoteBundle({ ...connectionOptions, bundleHash: remoteBundle.bundleHash, files: missingFiles, }); const bundleResponse = await http_1.checkBundle({ ...connectionOptions, bundleHash: remoteBundle.bundleHash }); if (bundleResponse.type === 'error') { throw new Error('Failed to get remote bundle'); } // eslint-disable-next-line no-param-reassign remoteBundle = bundleResponse.value; attempts += 1; } return remoteBundle; } async function remoteBundleFactory(options) { let remoteBundle = null; const baseOptions = lodash_pick_1.default(options, [ 'baseURL', 'sessionToken', 'source', 'baseDir', 'requestId', 'org', 'orgId', 'extraHeaders', ]); const bundleFactory = prepareRemoteBundle(lodash_omit_1.default(options, ['baseDir'])); for await (const response of bundleFactory) { if (response.type === 'error') { throw response.error; } remoteBundle = await fullfillRemoteBundle({ ...baseOptions, remoteBundle: response.value }); if (remoteBundle.missingFiles.length) { throw new Error(`Failed to upload # files: ${remoteBundle.missingFiles.length}`); } } return remoteBundle; } exports.remoteBundleFactory = remoteBundleFactory; /** * Get supported filters and test baseURL for correctness and availability * * @param baseURL * @param source * @returns */ async function getSupportedFiles(baseURL, source, requestId, languages, orgId, extraHeaders) { emitter_1.emitter.supportedFilesLoaded(null); const resp = await http_1.getFilters({ baseURL, source, orgId, requestId, attempts: constants_1.MAX_RETRY_ATTEMPTS, extraHeaders: extraHeaders !== null && extraHeaders !== void 0 ? extraHeaders : {}, }); if (resp.type === 'error') { throw resp.error; } const supportedFilesFromApi = resp.value; //Given supported languages from 'registy' if (languages) { const supportedFiles = { configFiles: supportedFilesFromApi.configFiles, extensions: languages, }; //For verification only // Make sure we compare file extensions between results from `registry` and `deeproxy` without case sensitivity to avoid missing some of supported extensions. const userSupportedExtensions = supportedFilesFromApi.extensions.map(e => e.toLowerCase()); supportedFiles.extensions = supportedFiles.extensions.filter(langExtension => userSupportedExtensions.includes(langExtension.toLowerCase())); emitter_1.emitter.supportedFilesLoaded(supportedFiles); return supportedFiles; } emitter_1.emitter.supportedFilesLoaded(supportedFilesFromApi); return supportedFilesFromApi; } exports.getSupportedFiles = getSupportedFiles; /** * Creates a remote bundle and returns response from the bundle API * * @param {CreateBundleFromFoldersOptions} options * @returns {Promise} */ async function createBundleFromFolders(options) { // Fetch supported files to save network traffic const supportedFiles = await getSupportedFiles(options.baseURL, options.source, options.requestId, options.languages, options.orgId, options.extraHeaders); // Collect files and create a remote bundle return await createBundleWithCustomFiles(options, supportedFiles); } exports.createBundleFromFolders = createBundleFromFolders; /** * Creates a remote bundle and returns response from the bundle API * This function is used to create a bundle with a custom list of supported file extensions * * @param {CreateBundleFromFoldersOptions} options * @param {SupportedFiles} supportedFiles * @returns {Promise} */ async function createBundleWithCustomFiles(options, supportedFiles) { // Scan for custom ignore rules const filePolicies = await files_1.collectFilePolicies(options.paths, options.symlinksEnabled, options.defaultFileIgnores); const baseDir = files_1.determineBaseDir(options.paths); emitter_1.emitter.scanFilesProgress(0); const bundleFiles = []; const skippedOversizedFiles = []; let totalFiles = 0; const bundleFileCollector = files_1.collectBundleFiles({ ...lodash_pick_1.default(options, ['paths', 'symlinksEnabled']), baseDir, filePolicies, supportedFiles, }); for await (const f of bundleFileCollector) { typeof f == 'string' ? skippedOversizedFiles.push(f) : bundleFiles.push(f); totalFiles += 1; emitter_1.emitter.scanFilesProgress(totalFiles); } const bundleOptions = { ...lodash_pick_1.default(options, ['baseURL', 'sessionToken', 'source', 'requestId', 'org', 'orgId', 'extraHeaders']), baseDir, files: bundleFiles, }; // Create remote bundle if (!bundleFiles.length) return null; const remoteBundle = await remoteBundleFactory(bundleOptions); if (remoteBundle === null) return null; return { ...remoteBundle, baseDir, supportedFiles, fileIgnores: [...filePolicies.excludes, ...filePolicies.ignores], skippedOversizedFiles, }; } exports.createBundleWithCustomFiles = createBundleWithCustomFiles; //# sourceMappingURL=bundles.js.map /***/ }), /***/ 27234: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readJSON = exports.Cache = void 0; //This is our own implementation of flat-cache without the use of flattened as we do not need cicular JSON support //and the executable for flattened was broken const path_1 = __importDefault(__webpack_require__(71017)); const fs_1 = __importDefault(__webpack_require__(57147)); class Cache { constructor(docId, cacheDir) { this.visited = {}; this.persisted = {}; this.pathToFile = ''; this.pathToFile = cacheDir ? path_1.default.resolve(cacheDir, docId) : path_1.default.resolve(__dirname, '../.cache/', docId); if (fs_1.default.existsSync(this.pathToFile)) { this.persisted = tryParse(this.pathToFile, {}); } } save(noPrune = false) { !noPrune && this.prune(); writeJSON(this.pathToFile, this.persisted); } getKey(key) { this.visited[key] = true; return this.persisted[key]; } setKey(key, value) { this.visited[key] = true; this.persisted[key] = value; } prune() { const obj = {}; const keys = Object.keys(this.visited); // no keys visited for either get or set value if (keys.length === 0) { return; } keys.forEach(key => { obj[key] = this.persisted[key]; }); this.visited = {}; this.persisted = obj; } } exports.Cache = Cache; function writeJSON(filePath, data) { fs_1.default.mkdirSync(path_1.default.dirname(filePath), { recursive: true, }); fs_1.default.writeFileSync(filePath, JSON.stringify(data)); } function tryParse(filePath, defaultValue) { let result; try { result = readJSON(filePath); } catch (ex) { result = defaultValue; } return result; } function readJSON(filePath) { return JSON.parse(fs_1.default.readFileSync(filePath, { encoding: 'utf8', })); } exports.readJSON = readJSON; //# sourceMappingURL=cache.js.map /***/ }), /***/ 65765: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DEFAULT_ERROR_MESSAGES = exports.NETWORK_ERRORS = exports.ErrorCodes = exports.DCIGNORE_DRAFTS = exports.IGNORE_FILES_NAMES = exports.IGNORES_DEFAULT = exports.ORG_ID_REGEXP = exports.REQUEST_RETRY_DELAY = exports.MAX_RETRY_ATTEMPTS = exports.POLLING_INTERVAL = exports.UPLOAD_CONCURRENCY = exports.MAX_UPLOAD_ATTEMPTS = exports.CACHE_KEY = exports.EXCLUDED_NAMES = exports.DOTSNYK_FILENAME = exports.DCIGNORE_FILENAME = exports.GITIGNORE_FILENAME = exports.GIT_FILENAME = exports.ENCODE_TYPE = exports.HASH_ALGORITHM = exports.MAX_FILE_SIZE = exports.MAX_PAYLOAD = void 0; const dcignore_1 = __webpack_require__(55086); exports.MAX_PAYLOAD = 4 * 1024 * 1024; exports.MAX_FILE_SIZE = 1024 * 1024; exports.HASH_ALGORITHM = 'sha256'; exports.ENCODE_TYPE = 'hex'; exports.GIT_FILENAME = '.git'; exports.GITIGNORE_FILENAME = '.gitignore'; exports.DCIGNORE_FILENAME = '.dcignore'; exports.DOTSNYK_FILENAME = '.snyk'; exports.EXCLUDED_NAMES = [exports.GITIGNORE_FILENAME, exports.DCIGNORE_FILENAME]; exports.CACHE_KEY = '.dccache'; exports.MAX_UPLOAD_ATTEMPTS = 10; exports.UPLOAD_CONCURRENCY = 2; exports.POLLING_INTERVAL = 500; exports.MAX_RETRY_ATTEMPTS = 10; // Request retries on network errors exports.REQUEST_RETRY_DELAY = 5 * 1000; // delay between retries in milliseconds exports.ORG_ID_REGEXP = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; exports.IGNORES_DEFAULT = [`**/${exports.GIT_FILENAME}/**`]; exports.IGNORE_FILES_NAMES = [exports.GITIGNORE_FILENAME, exports.DCIGNORE_FILENAME, exports.DOTSNYK_FILENAME]; exports.DCIGNORE_DRAFTS = { custom: dcignore_1.CustomDCIgnore, default: dcignore_1.DefaultDCIgnore, }; // eslint-disable-next-line no-shadow var ErrorCodes; (function (ErrorCodes) { ErrorCodes[ErrorCodes["loginInProgress"] = 304] = "loginInProgress"; ErrorCodes[ErrorCodes["badRequest"] = 400] = "badRequest"; ErrorCodes[ErrorCodes["unauthorizedUser"] = 401] = "unauthorizedUser"; ErrorCodes[ErrorCodes["unauthorizedBundleAccess"] = 403] = "unauthorizedBundleAccess"; ErrorCodes[ErrorCodes["notFound"] = 404] = "notFound"; ErrorCodes[ErrorCodes["bigPayload"] = 413] = "bigPayload"; ErrorCodes[ErrorCodes["connectionRefused"] = 421] = "connectionRefused"; ErrorCodes[ErrorCodes["dnsNotFound"] = 452] = "dnsNotFound"; ErrorCodes[ErrorCodes["serverError"] = 500] = "serverError"; ErrorCodes[ErrorCodes["badGateway"] = 502] = "badGateway"; ErrorCodes[ErrorCodes["serviceUnavailable"] = 503] = "serviceUnavailable"; ErrorCodes[ErrorCodes["timeout"] = 504] = "timeout"; })(ErrorCodes = exports.ErrorCodes || (exports.ErrorCodes = {})); exports.NETWORK_ERRORS = { ETIMEDOUT: ErrorCodes.timeout, ECONNREFUSED: ErrorCodes.connectionRefused, ECONNRESET: ErrorCodes.connectionRefused, ENETUNREACH: ErrorCodes.connectionRefused, ENOTFOUND: ErrorCodes.dnsNotFound, }; exports.DEFAULT_ERROR_MESSAGES = { [ErrorCodes.serverError]: 'Unexpected server error', [ErrorCodes.badGateway]: 'Bad gateway', [ErrorCodes.serviceUnavailable]: 'Service unavailable', [ErrorCodes.timeout]: 'Timeout occured. Try again later.', [ErrorCodes.dnsNotFound]: '[Connection issue] Could not resolve domain', [ErrorCodes.connectionRefused]: '[Connection issue] Connection refused', [ErrorCodes.loginInProgress]: 'Login has not been confirmed yet', [ErrorCodes.badRequest]: 'Bad request', [ErrorCodes.unauthorizedUser]: 'Missing, revoked or inactive token', [ErrorCodes.unauthorizedBundleAccess]: 'Unauthorized access to requested bundle analysis', [ErrorCodes.notFound]: 'Not found', [ErrorCodes.bigPayload]: `Payload too large (max is ${exports.MAX_PAYLOAD}b)`, }; //# sourceMappingURL=constants.js.map /***/ }), /***/ 37544: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.emitter = exports.EmitterDC = void 0; const events_1 = __webpack_require__(82361); // eslint-disable-next-line no-shadow var CUSTOM_EVENTS; (function (CUSTOM_EVENTS) { CUSTOM_EVENTS["supportedFilesLoaded"] = "supportedFilesLoaded"; CUSTOM_EVENTS["scanFilesProgress"] = "scanFilesProgress"; CUSTOM_EVENTS["createBundleProgress"] = "createBundleProgress"; CUSTOM_EVENTS["uploadBundleProgress"] = "uploadBundleProgress"; CUSTOM_EVENTS["analyseProgress"] = "analyseProgress"; CUSTOM_EVENTS["apiRequestLog"] = "apiRequestLog"; CUSTOM_EVENTS["error"] = "error"; })(CUSTOM_EVENTS || (CUSTOM_EVENTS = {})); class EmitterDC extends events_1.EventEmitter { constructor() { super(...arguments); this.events = CUSTOM_EVENTS; } supportedFilesLoaded(data) { this.emit(CUSTOM_EVENTS.supportedFilesLoaded, data); } scanFilesProgress(processed) { this.emit(CUSTOM_EVENTS.scanFilesProgress, processed); } createBundleProgress(processed, total) { this.emit(CUSTOM_EVENTS.createBundleProgress, processed, total); } uploadBundleProgress(processed, total) { this.emit(CUSTOM_EVENTS.uploadBundleProgress, processed, total); } analyseProgress(data) { this.emit(CUSTOM_EVENTS.analyseProgress, data); } sendError(error) { this.emit(CUSTOM_EVENTS.error, error); } apiRequestLog(message) { this.emit(CUSTOM_EVENTS.apiRequestLog, message); } } exports.EmitterDC = EmitterDC; exports.emitter = new EmitterDC(); //# sourceMappingURL=emitter.js.map /***/ }), /***/ 32083: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isMatch = exports.composeFilePayloads = exports.resolveBundleFilePath = exports.resolveBundleFiles = exports.getFileInfo = exports.calcHash = exports.getBundleFilePath = exports.prepareExtendingBundle = exports.collectBundleFiles = exports.determineBaseDir = exports.collectFilePolicies = exports.getGlobPatterns = exports.parseFileIgnores = exports.notEmpty = void 0; const nodePath = __importStar(__webpack_require__(71017)); const fs = __importStar(__webpack_require__(57147)); const fast_glob_1 = __importDefault(__webpack_require__(13294)); const multimatch_1 = __importDefault(__webpack_require__(23424)); const crypto_1 = __importDefault(__webpack_require__(6113)); const yaml_1 = __webpack_require__(6792); const lodash_union_1 = __importDefault(__webpack_require__(96744)); const util_1 = __importDefault(__webpack_require__(73837)); const cache_1 = __webpack_require__(27234); const constants_1 = __webpack_require__(65765); const isWindows = nodePath.sep === '\\'; const asyncLStat = util_1.default.promisify(fs.lstat); const lStat = async (path) => { let fileStats = null; try { // eslint-disable-next-line no-await-in-loop fileStats = await asyncLStat(path); } catch (err) { // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access if (err.code === 'EACCES' || err.code === 'EPERM') { console.log(`${path} is not accessible. Please check permissions and adjust .dcignore file to not even test this file`); } // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access if (err.code === 'ENOENT') { console.log(`no such file or directory: ${path}`); } } return fileStats; }; function notEmpty(value) { return value !== null && value !== undefined; } exports.notEmpty = notEmpty; const multiMatchOptions = { matchBase: true, dot: true }; const fgOptions = { dot: true, absolute: true, baseNameMatch: true, onlyFiles: true, suppressErrors: true, }; function filterSupportedFiles(files, supportedFiles) { const patters = getGlobPatterns(supportedFiles); return multimatch_1.default(files, patters, multiMatchOptions); } function parseIgnoreRulesToGlobs(rules, baseDir) { // Mappings from .gitignore format to glob format: // `/foo/` => `/foo/**` (meaning: Ignore root (not sub) foo dir and its paths underneath.) // `/foo` => `/foo/**`, `/foo` (meaning: Ignore root (not sub) file and dir and its paths underneath.) // `foo/` => `**/foo/**` (meaning: Ignore (root/sub) foo dirs and their paths underneath.) // `foo` => `**/foo/**`, `foo` (meaning: Ignore (root/sub) foo files and dirs and their paths underneath.) return rules.reduce((results, rule) => { let prefix = ''; if (rule.startsWith('!')) { // eslint-disable-next-line no-param-reassign rule = rule.substring(1); prefix = '!'; } const startingSlash = rule.startsWith('/'); const startingGlobstar = rule.startsWith('**'); const endingSlash = rule.endsWith('/'); const endingGlobstar = rule.endsWith('**'); if (startingSlash || startingGlobstar) { // case `/foo/`, `/foo` => `{baseDir}/foo/**` // case `**/foo/`, `**/foo` => `{baseDir}/**/foo/**` if (!endingGlobstar) results.push(prefix + nodePath.posix.join(baseDir, rule, '**')); // case `/foo` => `{baseDir}/foo` // case `**/foo` => `{baseDir}/**/foo` // case `/foo/**` => `{baseDir}/foo/**` // case `**/foo/**` => `{baseDir}/**/foo/**` if (!endingSlash) results.push(prefix + nodePath.posix.join(baseDir, rule)); } else { // case `foo/`, `foo` => `{baseDir}/**/foo/**` if (!endingGlobstar) results.push(prefix + nodePath.posix.join(baseDir, '**', rule, '**')); // case `foo` => `{baseDir}/**/foo` // case `foo/**` => `{baseDir}/**/foo/**` if (!endingSlash) results.push(prefix + nodePath.posix.join(baseDir, '**', rule)); } return results; }, []); } function parseFileIgnores(path) { let rules = []; const dirname = nodePath.dirname(path); try { const f = fs.readFileSync(path, { encoding: 'utf8' }); if (path.includes(constants_1.DOTSNYK_FILENAME)) { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const parsed = yaml_1.parse(f); const codeIgnoredPaths = parsed.exclude.code || []; const globalIgnoredPaths = parsed.exclude.global || []; rules = [...codeIgnoredPaths, ...globalIgnoredPaths]; } else { rules = f .split('\n') .map(l => l.trim()) .filter(l => !!l && !l.startsWith('#')); } } catch (err) { // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access if (err.code === 'EACCES' || err.code === 'EPERM') { console.log(`${path} is not accessible. Please check permissions and adjust .dcignore file to not even test this file`); } } try { return parseIgnoreRulesToGlobs(rules, dirname); } catch (err) { console.error('Could not parse ignore rules to glob', { path }); throw new Error('Please make sure ignore file follows correct syntax'); } } exports.parseFileIgnores = parseFileIgnores; function getGlobPatterns(supportedFiles) { return [ ...supportedFiles.extensions.map(e => `${generateAllCaseGlobPattern(e)}`), ...supportedFiles.configFiles.filter(e => !constants_1.EXCLUDED_NAMES.includes(e)), ]; } exports.getGlobPatterns = getGlobPatterns; // Generates glob patterns for case-insensitive file extension matching. // E.g. *.[jJ][sS] for matching .js files without case-sensitivity. function generateAllCaseGlobPattern(fileExtension) { const chars = Array.from(fileExtension); if (!chars.length) { console.log('Invalid file extension pattern: file extension is empty.'); return ''; } if (chars[0] != '.') { console.log("Invalid file extension pattern: missing '.' in the beginning of the file extension. Some files may not be included in the analysis."); return ''; } const caseInsensitivePatterns = chars.reduce((pattern, extensionChar, i) => { if (i == 0) { // first char should always be '.', no need to generate multiple cases for file extension character return ['*.']; } if (extensionChar.toLowerCase() == extensionChar.toUpperCase()) { // Char doesn't have case variant, return as-is. return pattern.concat(extensionChar); } const globCharPattern = `[${extensionChar.toLowerCase()}${extensionChar.toUpperCase()}]`; return pattern.concat(globCharPattern); }, []); return caseInsensitivePatterns.join(''); } /** * Recursively collect all exclude and ignore rules from "dirs". * * Exclude rules from .snyk files and ignore rules from .[*]ignore files are collected separately. * Any .[*]ignore files in paths excluded by .snyk exclude rules are ignored. */ async function collectFilePolicies(dirs, symlinksEnabled = false, fileIgnores = constants_1.IGNORES_DEFAULT) { const tasks = dirs.map(async (folder) => { const fileStats = await lStat(folder); // Check if symlink and exclude if requested if (!fileStats || (fileStats.isSymbolicLink() && !symlinksEnabled) || fileStats.isFile()) { return { excludes: [], ignores: [], }; } // Find .snyk and .[*]ignore files inside this directory. const allIgnoredFiles = await fast_glob_1.default(constants_1.IGNORE_FILES_NAMES.map(i => `*${i}`), { ...fgOptions, cwd: folder, followSymbolicLinks: symlinksEnabled, }); // Parse rules from all .snyk files inside this directory. const snykFiles = allIgnoredFiles.filter(f => f.endsWith(constants_1.DOTSNYK_FILENAME)); const snykExcludeRules = lodash_union_1.default(...snykFiles.map(parseFileIgnores)); // Parse rules from relevant .[*]ignore files inside this directory. // Exclude ignore files under paths excluded by .snyk files. const ignoreFiles = allIgnoredFiles.filter(f => !f.endsWith(constants_1.DOTSNYK_FILENAME) && multimatch_1.default([nodePath.dirname(f)], snykExcludeRules).length === 0); const ignoreFileRules = lodash_union_1.default(...ignoreFiles.map(parseFileIgnores)); return { excludes: snykExcludeRules, ignores: ignoreFileRules, }; }); const collectedRules = await Promise.all(tasks); return { excludes: lodash_union_1.default(...collectedRules.map(policies => policies.excludes)), // Merge external and collected ignore rules ignores: lodash_union_1.default(fileIgnores, ...collectedRules.map(policies => policies.ignores)), }; } exports.collectFilePolicies = collectFilePolicies; function determineBaseDir(paths) { if (paths.length === 1) { const path = paths[0]; const stats = fs.lstatSync(path); if (stats.isFile()) { return nodePath.dirname(path); } return path; } return ''; } exports.determineBaseDir = determineBaseDir; async function* searchFiles(patterns, cwd, symlinksEnabled, policies) { const positiveIgnores = [...policies.excludes, ...policies.ignores.filter(rule => !rule.startsWith('!'))]; const negativeIgnores = policies.ignores.filter(rule => rule.startsWith('!')).map(rule => rule.substring(1)); // We need to use the ignore rules directly in the stream. Otherwise we would expand all the branches of the file system // that should be ignored, leading to performance issues (the parser would look stuck while analyzing each ignored file). // However, fast-glob doesn't address the negative rules in the ignore option correctly. // As a compromise between correctness and performance, we split the search in two streams, the first one using the // extension patterns as a search term and the positive ignore rules in the options, while the second that manually // expands those branches that should be excluded from the ignore rules throught the negative ignores as search term // and then matches the extensions as a second step to exclude any file that should not be analyzed. const positiveSearcher = fast_glob_1.default.stream(patterns, { ...fgOptions, cwd, followSymbolicLinks: symlinksEnabled, ignore: positiveIgnores, }); for await (const filePath of positiveSearcher) { yield filePath; } const deepPatterns = patterns.map(p => `**/${p}`); // TODO: This is incorrect because the .gitignore format allows to specify exceptions to previous rules, therefore // the separation between positive and negative ignores is incorrect in a scenario with 2+ exeptions like the one below: // `node_module/` <= ignores everything in a `node_module` folder and it's relative subfolders // `!node_module/my_module/` <= excludes the `my_module` subfolder from the ignore // `node_module/my_module/build/` <= re-includes the `build` subfolder in the ignore if (negativeIgnores.length) { const negativeSearcher = fast_glob_1.default.stream(negativeIgnores, { ...fgOptions, cwd, followSymbolicLinks: symlinksEnabled, baseNameMatch: false, // Exclude rules should still be respected ignore: policies.excludes, }); for await (const filePath of negativeSearcher) { if (isMatch(filePath.toString(), deepPatterns)) yield filePath; } } } /** * Returns bundle files from requested paths * If a file exceeds the maximum file size, it returns a string with its path * */ async function* collectBundleFiles({ symlinksEnabled = false, baseDir, filePolicies, paths, supportedFiles, }) { const cache = new cache_1.Cache(constants_1.CACHE_KEY, baseDir); const files = []; const dirs = []; // Split into directories and files and exclude symlinks if needed for (const path of paths) { // eslint-disable-next-line no-await-in-loop const fileStats = await lStat(path); // Check if symlink and exclude if requested if (!fileStats || (fileStats.isSymbolicLink() && !symlinksEnabled)) continue; if (fileStats.isFile()) { fileStats.size <= constants_1.MAX_FILE_SIZE ? files.push(path) : yield path; } else if (fileStats.isDirectory()) { dirs.push(path); } } // Scan folders const globPatterns = getGlobPatterns(supportedFiles); for (const folder of dirs) { const searcher = searchFiles(globPatterns, folder, symlinksEnabled, filePolicies); // eslint-disable-next-line no-await-in-loop for await (const filePath of searcher) { const fileInfo = await getFileInfo(filePath.toString(), baseDir, false, cache); // dc ignore AttrAccessOnNull: false positive, there is a precondition with && if (fileInfo) { fileInfo.size <= constants_1.MAX_FILE_SIZE ? yield fileInfo : yield fileInfo.bundlePath; } } } // Sanitize files if (files.length) { const searcher = searchFiles(filterSupportedFiles(files, supportedFiles), baseDir, symlinksEnabled, filePolicies); for await (const filePath of searcher) { const fileInfo = await getFileInfo(filePath.toString(), baseDir, false, cache); // dc ignore AttrAccessOnNull: false positive, there is a precondition with && if (fileInfo) { fileInfo.size <= constants_1.MAX_FILE_SIZE ? yield fileInfo : yield fileInfo.bundlePath; } } } cache.save(); } exports.collectBundleFiles = collectBundleFiles; async function prepareExtendingBundle(baseDir, supportedFiles, fileIgnores = constants_1.IGNORES_DEFAULT, files, symlinksEnabled = false) { let removedFiles = []; let bundleFiles = []; const cache = new cache_1.Cache(constants_1.CACHE_KEY, baseDir); // Filter for supported extensions/files only let processingFiles = filterSupportedFiles(files, supportedFiles); // Exclude files to be ignored based on ignore rules. We assume here, that ignore rules have not been changed. processingFiles = processingFiles.map(f => resolveBundleFilePath(baseDir, f)).filter(f => !isMatch(f, fileIgnores)); if (processingFiles.length) { // Determine existing files (minus removed) if (isWindows) { processingFiles = processingFiles.map(f => f.replace(/\\/g, '/')); // fg requires forward-slashes in Windows globs } const entries = await fast_glob_1.default(processingFiles, { ...fgOptions, cwd: baseDir, followSymbolicLinks: symlinksEnabled, objectMode: true, stats: true, }); let foundFiles = new Set(); // This initialization is needed to help Typescript checker foundFiles = entries.reduce((s, e) => { if (e.stats && e.stats.size <= constants_1.MAX_FILE_SIZE) { s.add(e.path); } return s; }, foundFiles); removedFiles = processingFiles.reduce((s, p) => { if (!foundFiles.has(p)) { s.push(getBundleFilePath(p, baseDir)); } return s; }, []); if (foundFiles.size) { bundleFiles = (await Promise.all([...foundFiles].map((p) => getFileInfo(p, baseDir, false, cache)))).filter(notEmpty); } } return { files: bundleFiles, removedFiles, }; } exports.prepareExtendingBundle = prepareExtendingBundle; function getBundleFilePath(filePath, baseDir) { const relPath = baseDir ? nodePath.relative(baseDir, filePath) : filePath; // relPath without explicit base makes no sense const posixPath = !isWindows ? relPath : relPath.replace(/\\/g, '/'); return encodeURI(posixPath); } exports.getBundleFilePath = getBundleFilePath; function calcHash(content) { return crypto_1.default.createHash(constants_1.HASH_ALGORITHM).update(content).digest(constants_1.ENCODE_TYPE); } exports.calcHash = calcHash; async function getFileInfo(filePath, baseDir, withContent = false, cache = null) { const fileStats = await lStat(filePath); if (fileStats === null) { return fileStats; } const bundlePath = getBundleFilePath(filePath, baseDir); let fileContent = ''; let fileHash = ''; if (!withContent && !!cache) { // Try to get hash from cache const cachedData = cache.getKey(filePath); if (cachedData) { if (cachedData[0] === fileStats.size && cachedData[1] === fileStats.mtimeMs) { fileHash = cachedData[2]; } else { // console.log(`did not match cache for: ${filePath} | ${cachedData} !== ${[fileStats.size, fileStats.mtime]}`); } } } if (!fileHash) { try { fileContent = fs.readFileSync(filePath, { encoding: 'utf8' }); fileHash = calcHash(fileContent); cache === null || cache === void 0 ? void 0 : cache.setKey(filePath, [fileStats.size, fileStats.mtimeMs, fileHash]); } catch (err) { // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access if (err.code === 'EACCES' || err.code === 'EPERM') { console.log(`${filePath} is not accessible. Please check permissions and adjust .dcignore file to not even test this file`); } } } return { filePath, bundlePath, size: fileStats.size, hash: fileHash, content: withContent ? fileContent : undefined, }; } exports.getFileInfo = getFileInfo; async function resolveBundleFiles(baseDir, bundleMissingFiles) { const cache = new cache_1.Cache('.dccache', baseDir); const tasks = bundleMissingFiles.map(mf => { const filePath = resolveBundleFilePath(baseDir, mf); return getFileInfo(filePath, baseDir, true, cache); }); const res = (await Promise.all(tasks)).filter(notEmpty); cache.save(true); return res; } exports.resolveBundleFiles = resolveBundleFiles; function resolveBundleFilePath(baseDir, bundleFilePath) { let relPath = bundleFilePath; if (isWindows) { relPath = relPath.replace(/\//g, '\\'); } if (baseDir) { return nodePath.resolve(baseDir, decodeURI(relPath)); } return decodeURI(relPath); } exports.resolveBundleFilePath = resolveBundleFilePath; // MAX_PAYLOAD / 2 is because every char takes 2 bytes in the payload function* composeFilePayloads(files, bucketSize = constants_1.MAX_PAYLOAD / 2) { const buckets = [{ size: bucketSize, files: [] }]; let bucketIndex = -1; const getFileDataPayloadSize = (fileData) => { var _a; return (((_a = fileData.content) === null || _a === void 0 ? void 0 : _a.length) ? fileData.content.length + 16 : 0) + fileData.bundlePath.length + fileData.hash.length + 6; }; // constants is for the separators const isLowerSize = (size, fileData) => size >= getFileDataPayloadSize(fileData); for (const fileData of files) { // This file is empty or too large to send, it should be skipped. if (!fileData.size || !isLowerSize(bucketSize, fileData)) continue; // Find suitable bucket bucketIndex = buckets.findIndex(b => isLowerSize(b.size, fileData)); if (bucketIndex === -1) { // Create a new bucket buckets.push({ size: bucketSize, files: [] }); bucketIndex = buckets.length - 1; } buckets[bucketIndex].files.push(fileData); buckets[bucketIndex].size -= getFileDataPayloadSize(fileData); if (buckets[bucketIndex].size < bucketSize * 0.01) { yield buckets[bucketIndex].files; // Give bucket to requester buckets.splice(bucketIndex); // Remove it as fullfilled } } // Send all left-over buckets for (const bucket of buckets.filter(b => b.files.length)) { yield bucket.files; } } exports.composeFilePayloads = composeFilePayloads; function isMatch(filePath, rules) { return !!multimatch_1.default([filePath], rules, { ...multiMatchOptions, matchBase: false }).length; } exports.isMatch = isMatch; //# sourceMappingURL=files.js.map /***/ }), /***/ 60776: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getScmReport = exports.initScmReport = exports.getReport = exports.initReport = exports.getAnalysis = exports.AnalysisStatus = exports.extendBundle = exports.checkBundle = exports.createBundle = exports.getFilters = exports.checkSession = exports.getIpFamily = exports.getVerifyCallbackUrl = exports.startSession = exports.compressAndEncode = void 0; const uuid_1 = __webpack_require__(96771); const lodash_pick_1 = __importDefault(__webpack_require__(25030)); const zlib_1 = __webpack_require__(59796); const util_1 = __webpack_require__(73837); const constants_1 = __webpack_require__(65765); const needle_1 = __webpack_require__(14577); const httpUtils_1 = __webpack_require__(11294); // The trick to typecast union type alias // eslint-disable-next-line @typescript-eslint/no-explicit-any function isSubsetErrorCode(code, messages) { return code in messages; } function generateError(errorCode, messages, apiName, errorMessage, errors) { if (errors) { return httpUtils_1.generateErrorWithDetail(errors[0], errorCode, apiName); } if (!isSubsetErrorCode(errorCode, messages)) { throw { statusCode: errorCode, statusText: errorMessage || 'unknown error occurred', apiName }; } const statusCode = errorCode; const statusText = errorMessage !== null && errorMessage !== void 0 ? errorMessage : messages[errorCode]; return { type: 'error', error: { apiName, statusCode, statusText, }, }; } const GENERIC_ERROR_MESSAGES = { [constants_1.ErrorCodes.serverError]: constants_1.DEFAULT_ERROR_MESSAGES[constants_1.ErrorCodes.serverError], [constants_1.ErrorCodes.badGateway]: constants_1.DEFAULT_ERROR_MESSAGES[constants_1.ErrorCodes.badGateway], [constants_1.ErrorCodes.serviceUnavailable]: constants_1.DEFAULT_ERROR_MESSAGES[constants_1.ErrorCodes.serviceUnavailable], [constants_1.ErrorCodes.timeout]: constants_1.DEFAULT_ERROR_MESSAGES[constants_1.ErrorCodes.timeout], [constants_1.ErrorCodes.dnsNotFound]: constants_1.DEFAULT_ERROR_MESSAGES[constants_1.ErrorCodes.dnsNotFound], [constants_1.ErrorCodes.connectionRefused]: constants_1.DEFAULT_ERROR_MESSAGES[constants_1.ErrorCodes.connectionRefused], }; async function compressAndEncode(payload) { // encode payload and compress; const deflate = util_1.promisify(zlib_1.gzip); return await deflate(Buffer.from(JSON.stringify(payload)).toString('base64')); } exports.compressAndEncode = compressAndEncode; function startSession(options) { const { source, authHost } = options; const draftToken = uuid_1.v4(); return { draftToken, loginURL: `${authHost}/login?token=${draftToken}&utm_medium=${source}&utm_source=${source}&utm_campaign=${source}&docker=false`, }; } exports.startSession = startSession; function getVerifyCallbackUrl(authHost) { return `${authHost}/api/verify/callback`; } exports.getVerifyCallbackUrl = getVerifyCallbackUrl; /** * Dispatches a FORCED IPv6 request to test client's ISP and network capability. * * @return {number} IP family number used by the client. */ async function getIpFamily(authHost) { const family = 6; // Dispatch a FORCED IPv6 request to test client's ISP and network capability const res = await needle_1.makeRequest({ url: getVerifyCallbackUrl(authHost), method: 'post', family, // family param forces the handler to dispatch a request using IP at "family" version }, 0); const ipv6Incompatible = res.error; return ipv6Incompatible ? undefined : family; } exports.getIpFamily = getIpFamily; const CHECK_SESSION_ERROR_MESSAGES = { ...GENERIC_ERROR_MESSAGES, [constants_1.ErrorCodes.unauthorizedUser]: constants_1.DEFAULT_ERROR_MESSAGES[constants_1.ErrorCodes.unauthorizedUser], [constants_1.ErrorCodes.loginInProgress]: constants_1.DEFAULT_ERROR_MESSAGES[constants_1.ErrorCodes.loginInProgress], }; async function checkSession(options) { const defaultValue = { type: 'success', value: '', }; const res = await needle_1.makeRequest({ url: getVerifyCallbackUrl(options.authHost), body: { token: options.draftToken, }, family: options.ipFamily, method: 'post', }); if (res.success) { return { ...defaultValue, value: (res.body.ok && res.body.api) || '' }; } else if ([constants_1.ErrorCodes.loginInProgress, constants_1.ErrorCodes.badRequest, constants_1.ErrorCodes.unauthorizedUser].includes(res.errorCode)) { return defaultValue; } return generateError(res.errorCode, CHECK_SESSION_ERROR_MESSAGES, 'checkSession'); } exports.checkSession = checkSession; async function getFilters({ baseURL, orgId, attempts, source, extraHeaders, requestId, }) { const apiName = 'filters'; let url; try { url = httpUtils_1.getURL(baseURL, '/' + apiName, orgId); } catch (err) { return generateError(400, err.message, apiName); } const res = await needle_1.makeRequest({ headers: { source, ...extraHeaders, ...(requestId && { 'snyk-request-id': requestId }), }, url, method: 'get', }, attempts); if (res.success) { return { type: 'success', value: res.body }; } return generateError(res.errorCode, GENERIC_ERROR_MESSAGES, apiName, undefined, res.errors); } exports.getFilters = getFilters; function commonHttpHeaders(options) { return { Authorization: options.sessionToken, source: options.source, ...(options.requestId && { 'snyk-request-id': options.requestId }), ...(options.org && { 'snyk-org-name': options.org }), ...options.extraHeaders, }; } const CREATE_BUNDLE_ERROR_MESSAGES = { ...GENERIC_ERROR_MESSAGES, [constants_1.ErrorCodes.unauthorizedUser]: constants_1.DEFAULT_ERROR_MESSAGES[constants_1.ErrorCodes.unauthorizedUser], [constants_1.ErrorCodes.unauthorizedBundleAccess]: constants_1.DEFAULT_ERROR_MESSAGES[constants_1.ErrorCodes.unauthorizedBundleAccess], [constants_1.ErrorCodes.bigPayload]: constants_1.DEFAULT_ERROR_MESSAGES[constants_1.ErrorCodes.bigPayload], [constants_1.ErrorCodes.badRequest]: `Request payload doesn't match the specifications`, [constants_1.ErrorCodes.notFound]: 'Unable to resolve requested oid', }; async function createBundle(options) { const payloadBody = await compressAndEncode(options.files); let url; try { url = httpUtils_1.getURL(options.baseURL, '/bundle', options.orgId); } catch (err) { return generateError(400, err.message, 'createBundle'); } const payload = { headers: { 'content-type': 'application/octet-stream', 'content-encoding': 'gzip', ...commonHttpHeaders(options), }, url, method: 'post', body: payloadBody, isJson: false, }; const res = await needle_1.makeRequest(payload); if (res.success) { return { type: 'success', value: res.body }; } return generateError(res.errorCode, CREATE_BUNDLE_ERROR_MESSAGES, 'createBundle', undefined, res.errors); } exports.createBundle = createBundle; const CHECK_BUNDLE_ERROR_MESSAGES = { ...GENERIC_ERROR_MESSAGES, [constants_1.ErrorCodes.unauthorizedUser]: constants_1.DEFAULT_ERROR_MESSAGES[constants_1.ErrorCodes.unauthorizedUser], [constants_1.ErrorCodes.unauthorizedBundleAccess]: constants_1.DEFAULT_ERROR_MESSAGES[constants_1.ErrorCodes.unauthorizedBundleAccess], [constants_1.ErrorCodes.notFound]: 'Uploaded bundle has expired', }; async function checkBundle(options) { let url; try { url = httpUtils_1.getURL(options.baseURL, `/bundle/${options.bundleHash}`, options.orgId); } catch (err) { return generateError(400, err.message, 'checkBundle'); } const res = await needle_1.makeRequest({ headers: { ...commonHttpHeaders(options), }, url, method: 'get', }); if (res.success) return { type: 'success', value: res.body }; return generateError(res.errorCode, CHECK_BUNDLE_ERROR_MESSAGES, 'checkBundle', undefined, res.errors); } exports.checkBundle = checkBundle; const EXTEND_BUNDLE_ERROR_MESSAGES = { ...GENERIC_ERROR_MESSAGES, [constants_1.ErrorCodes.unauthorizedUser]: constants_1.DEFAULT_ERROR_MESSAGES[constants_1.ErrorCodes.unauthorizedUser], [constants_1.ErrorCodes.bigPayload]: constants_1.DEFAULT_ERROR_MESSAGES[constants_1.ErrorCodes.bigPayload], [constants_1.ErrorCodes.badRequest]: `Bad request`, [constants_1.ErrorCodes.unauthorizedBundleAccess]: 'Unauthorized access to parent bundle', [constants_1.ErrorCodes.notFound]: 'Parent bundle has expired', }; async function extendBundle(options) { const payloadBody = await compressAndEncode(lodash_pick_1.default(options, ['files', 'removedFiles'])); let url; try { url = httpUtils_1.getURL(options.baseURL, `/bundle/${options.bundleHash}`, options.orgId); } catch (err) { return generateError(400, err.message, 'extendBundle'); } const res = await needle_1.makeRequest({ headers: { 'content-type': 'application/octet-stream', 'content-encoding': 'gzip', ...commonHttpHeaders(options), }, url, method: 'put', body: payloadBody, isJson: false, }); if (res.success) return { type: 'success', value: res.body }; return generateError(res.errorCode, EXTEND_BUNDLE_ERROR_MESSAGES, 'extendBundle', undefined, res.errors); } exports.extendBundle = extendBundle; // eslint-disable-next-line no-shadow var AnalysisStatus; (function (AnalysisStatus) { AnalysisStatus["waiting"] = "WAITING"; AnalysisStatus["fetching"] = "FETCHING"; AnalysisStatus["analyzing"] = "ANALYZING"; AnalysisStatus["done"] = "DONE"; AnalysisStatus["failed"] = "FAILED"; AnalysisStatus["complete"] = "COMPLETE"; })(AnalysisStatus = exports.AnalysisStatus || (exports.AnalysisStatus = {})); const GET_ANALYSIS_ERROR_MESSAGES = { ...GENERIC_ERROR_MESSAGES, [constants_1.ErrorCodes.unauthorizedUser]: constants_1.DEFAULT_ERROR_MESSAGES[constants_1.ErrorCodes.unauthorizedUser], [constants_1.ErrorCodes.unauthorizedBundleAccess]: constants_1.DEFAULT_ERROR_MESSAGES[constants_1.ErrorCodes.unauthorizedBundleAccess], [constants_1.ErrorCodes.notFound]: constants_1.DEFAULT_ERROR_MESSAGES[constants_1.ErrorCodes.notFound], [constants_1.ErrorCodes.badRequest]: constants_1.DEFAULT_ERROR_MESSAGES[constants_1.ErrorCodes.badRequest], [constants_1.ErrorCodes.serverError]: 'Getting analysis failed', }; async function getAnalysis(options) { let url; try { url = httpUtils_1.getURL(options.baseURL, '/analysis', options.orgId); } catch (err) { return generateError(400, err.message, 'getAnalysis'); } const config = { headers: { ...commonHttpHeaders(options), }, url, method: 'post', body: { key: { type: 'file', hash: options.bundleHash, limitToFiles: options.limitToFiles || [], ...(options.shard ? { shard: options.shard } : null), }, ...lodash_pick_1.default(options, ['severity', 'prioritized', 'legacy', 'analysisContext']), }, }; const res = await needle_1.makeRequest(config); if (res.success) { return { type: 'success', value: res.body }; } return generateError(res.errorCode, GET_ANALYSIS_ERROR_MESSAGES, 'getAnalysis', undefined, res.errors); } exports.getAnalysis = getAnalysis; const REPORT_ERROR_MESSAGES = { ...GENERIC_ERROR_MESSAGES, [constants_1.ErrorCodes.unauthorizedUser]: constants_1.DEFAULT_ERROR_MESSAGES[constants_1.ErrorCodes.unauthorizedUser], [constants_1.ErrorCodes.unauthorizedBundleAccess]: constants_1.DEFAULT_ERROR_MESSAGES[constants_1.ErrorCodes.unauthorizedBundleAccess], [constants_1.ErrorCodes.notFound]: constants_1.DEFAULT_ERROR_MESSAGES[constants_1.ErrorCodes.notFound], [constants_1.ErrorCodes.badRequest]: constants_1.DEFAULT_ERROR_MESSAGES[constants_1.ErrorCodes.badRequest], [constants_1.ErrorCodes.serverError]: 'Getting report failed', }; /** * Trigger a file-based test with reporting. */ async function initReport(options) { let url; try { url = httpUtils_1.getURL(options.baseURL, `/report`, options.orgId); } catch (err) { return generateError(400, err.message, 'initReport'); } const config = { headers: { ...commonHttpHeaders(options), }, url, method: 'post', body: { workflowData: { projectName: options.report.projectName, targetName: options.report.targetName, targetRef: options.report.targetRef, remoteRepoUrl: options.report.remoteRepoUrl, }, key: { type: 'file', hash: options.bundleHash, limitToFiles: options.limitToFiles || [], ...(options.shard ? { shard: options.shard } : null), }, ...lodash_pick_1.default(options, ['severity', 'prioritized', 'legacy', 'analysisContext']), }, }; const res = await needle_1.makeRequest(config); if (res.success) return { type: 'success', value: res.body.reportId }; return generateError(res.errorCode, REPORT_ERROR_MESSAGES, 'initReport', undefined, res.errors); } exports.initReport = initReport; /** * Retrieve a file-based test with reporting. */ async function getReport(options) { var _a; let url; try { url = httpUtils_1.getURL(options.baseURL, `/report/${options.pollId}`, options.orgId); } catch (err) { return generateError(400, err.message, 'getReport'); } const config = { headers: { ...commonHttpHeaders(options), }, url, method: 'get', }; const res = await needle_1.makeRequest(config); if (res.success) return { type: 'success', value: res.body }; return generateError(res.errorCode, REPORT_ERROR_MESSAGES, 'getReport', (_a = res.error) === null || _a === void 0 ? void 0 : _a.message, res.errors); } exports.getReport = getReport; /** * Trigger an SCM-based test with reporting. */ async function initScmReport(options) { let url; try { url = httpUtils_1.getURL(options.baseURL, `/test`, options.orgId); } catch (err) { return generateError(400, err.message, 'initReport'); } const config = { headers: { ...commonHttpHeaders(options), }, url, method: 'post', body: { workflowData: { projectId: options.projectId, commitHash: options.commitId, }, ...lodash_pick_1.default(options, ['severity', 'prioritized', 'analysisContext']), }, }; const res = await needle_1.makeRequest(config); if (res.success) return { type: 'success', value: res.body.testId }; return generateError(res.errorCode, REPORT_ERROR_MESSAGES, 'initReport', undefined, res.errors); } exports.initScmReport = initScmReport; /** * Fetch an SCM-based test with reporting. */ async function getScmReport(options) { var _a; let url; try { url = httpUtils_1.getURL(options.baseURL, `/test/${options.pollId}`, options.orgId); } catch (err) { return generateError(400, err.message, 'getReport'); } const config = { headers: { ...commonHttpHeaders(options), }, url, method: 'get', }; const res = await needle_1.makeRequest(config); if (res.success) return { type: 'success', value: res.body }; return generateError(res.errorCode, REPORT_ERROR_MESSAGES, 'getReport', (_a = res.error) === null || _a === void 0 ? void 0 : _a.message, res.errors); } exports.getScmReport = getScmReport; //# sourceMappingURL=http.js.map /***/ }), /***/ 95951: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getIpFamily = exports.checkSession = exports.startSession = exports.getAnalysis = exports.AnalysisSeverity = exports.constants = exports.MAX_FILE_SIZE = exports.emitter = exports.extendAnalysis = exports.createBundleWithCustomFiles = exports.createBundleFromFolders = exports.getSupportedFiles = exports.analyzeScmProject = exports.analyzeFolders = exports.getGlobPatterns = void 0; const analysis_1 = __webpack_require__(54151); Object.defineProperty(exports, "analyzeFolders", ({ enumerable: true, get: function () { return analysis_1.analyzeFolders; } })); Object.defineProperty(exports, "extendAnalysis", ({ enumerable: true, get: function () { return analysis_1.extendAnalysis; } })); Object.defineProperty(exports, "analyzeScmProject", ({ enumerable: true, get: function () { return analysis_1.analyzeScmProject; } })); const bundles_1 = __webpack_require__(86639); Object.defineProperty(exports, "getSupportedFiles", ({ enumerable: true, get: function () { return bundles_1.getSupportedFiles; } })); Object.defineProperty(exports, "createBundleFromFolders", ({ enumerable: true, get: function () { return bundles_1.createBundleFromFolders; } })); Object.defineProperty(exports, "createBundleWithCustomFiles", ({ enumerable: true, get: function () { return bundles_1.createBundleWithCustomFiles; } })); const emitter_1 = __webpack_require__(37544); Object.defineProperty(exports, "emitter", ({ enumerable: true, get: function () { return emitter_1.emitter; } })); const http_1 = __webpack_require__(60776); Object.defineProperty(exports, "startSession", ({ enumerable: true, get: function () { return http_1.startSession; } })); Object.defineProperty(exports, "checkSession", ({ enumerable: true, get: function () { return http_1.checkSession; } })); Object.defineProperty(exports, "getAnalysis", ({ enumerable: true, get: function () { return http_1.getAnalysis; } })); Object.defineProperty(exports, "getIpFamily", ({ enumerable: true, get: function () { return http_1.getIpFamily; } })); const constants_1 = __webpack_require__(65765); Object.defineProperty(exports, "MAX_FILE_SIZE", ({ enumerable: true, get: function () { return constants_1.MAX_FILE_SIZE; } })); const constants = __importStar(__webpack_require__(65765)); exports.constants = constants; const files_1 = __webpack_require__(32083); Object.defineProperty(exports, "getGlobPatterns", ({ enumerable: true, get: function () { return files_1.getGlobPatterns; } })); const analysis_options_interface_1 = __webpack_require__(4775); Object.defineProperty(exports, "AnalysisSeverity", ({ enumerable: true, get: function () { return analysis_options_interface_1.AnalysisSeverity; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 4775: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AnalysisSeverity = void 0; // eslint-disable-next-line import/prefer-default-export, no-shadow var AnalysisSeverity; (function (AnalysisSeverity) { AnalysisSeverity[AnalysisSeverity["info"] = 1] = "info"; AnalysisSeverity[AnalysisSeverity["warning"] = 2] = "warning"; AnalysisSeverity[AnalysisSeverity["critical"] = 3] = "critical"; })(AnalysisSeverity = exports.AnalysisSeverity || (exports.AnalysisSeverity = {})); //# sourceMappingURL=analysis-options.interface.js.map /***/ }), /***/ 14577: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.makeRequest = void 0; /* eslint-disable camelcase */ const http_1 = __importDefault(__webpack_require__(13685)); const needle_1 = __importDefault(__webpack_require__(64484)); const querystring = __importStar(__webpack_require__(63477)); const https_1 = __importDefault(__webpack_require__(95687)); const url_1 = __webpack_require__(57310); const emitter_1 = __webpack_require__(37544); const constants_1 = __webpack_require__(65765); const sleep = (duration) => new Promise(resolve => setTimeout(resolve, duration)); const TIMEOUT_DEFAULT = 600000; const agentOptions = { keepAlive: true, keepAliveMsecs: 1000, maxSockets: 256, maxFreeSockets: 256, freeSocketTimeout: 60000, socketActiveTTL: 1000 * 60 * 10, rejectUnauthorized: !global.ignoreUnknownCA, }; async function makeRequest(payload, attempts = constants_1.MAX_RETRY_ATTEMPTS) { var _a, _b; let data; if (!payload.isJson && payload.body) { data = payload.body; } else { data = JSON.stringify(payload.body); } const parsedUrl = new url_1.URL(payload.url); const agent = parsedUrl.protocol === 'http:' ? new http_1.default.Agent(agentOptions) : new https_1.default.Agent(agentOptions); const method = (payload.method || 'get').toLowerCase(); let { url } = payload; if (payload.qs) { // Parse the URL and append the search part - this will take care of adding the '/?' part if it's missing const urlObject = new url_1.URL(url); urlObject.search = querystring.stringify(payload.qs); url = urlObject.toString(); delete payload.qs; } const options = { use_proxy_from_env_var: false, headers: payload.headers, open_timeout: TIMEOUT_DEFAULT, response_timeout: payload.timeout || TIMEOUT_DEFAULT, read_timeout: payload.timeout || TIMEOUT_DEFAULT, family: payload.family, json: payload.isJson || true, compressed: true, follow_max: 5, rejectUnauthorized: !global.ignoreUnknownCA, agent, }; emitter_1.emitter.apiRequestLog(`=> HTTP ${method === null || method === void 0 ? void 0 : method.toUpperCase()} ${url} ${data !== null && data !== void 0 ? data : ''}`.slice(0, 399)); do { let errorCode; let error; let response; try { response = await needle_1.default(method, url, data, options); emitter_1.emitter.apiRequestLog(`<= Response: ${response.statusCode} ${JSON.stringify(response.body)}`); const success = !!(response.statusCode && response.statusCode >= 200 && response.statusCode < 300); if (success) return { success, body: response.body }; errorCode = response.statusCode; } catch (err) { error = err; // do not swallow the error, pass further to the caller instead errorCode = constants_1.NETWORK_ERRORS[err.code || err.errno]; emitter_1.emitter.apiRequestLog(`Requested url --> ${url} | error --> ${err}`); } // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access const errorMessage = (_a = response === null || response === void 0 ? void 0 : response.body) === null || _a === void 0 ? void 0 : _a.error; // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access const errors = (_b = response === null || response === void 0 ? void 0 : response.body) === null || _b === void 0 ? void 0 : _b.errors; if (errorMessage) { error = error !== null && error !== void 0 ? error : new Error(errorMessage); } errorCode = errorCode !== null && errorCode !== void 0 ? errorCode : constants_1.ErrorCodes.serviceUnavailable; // Try to avoid breaking requests due to temporary network errors if (attempts > 1 && [ constants_1.ErrorCodes.serviceUnavailable, constants_1.ErrorCodes.badGateway, constants_1.ErrorCodes.connectionRefused, constants_1.ErrorCodes.timeout, constants_1.ErrorCodes.dnsNotFound, constants_1.ErrorCodes.serverError, ].includes(errorCode)) { attempts--; await sleep(constants_1.REQUEST_RETRY_DELAY); } else { attempts = 0; return { success: false, errorCode, error, errors }; } } while (attempts > 0); return { success: false, errorCode: constants_1.ErrorCodes.serviceUnavailable, error: undefined }; } exports.makeRequest = makeRequest; //# sourceMappingURL=needle.js.map /***/ }), /***/ 17608: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.reportScm = exports.reportBundle = void 0; const uuid = __importStar(__webpack_require__(96771)); const lodash_pick_1 = __importDefault(__webpack_require__(25030)); const constants_1 = __webpack_require__(65765); const emitter_1 = __webpack_require__(37544); const http_1 = __webpack_require__(60776); const sleep = (duration) => new Promise(resolve => setTimeout(resolve, duration)); async function initAndPollReportGeneric(initReportFunc, getReportFunc, options) { emitter_1.emitter.analyseProgress({ status: http_1.AnalysisStatus.waiting, progress: 0, }); // First init the report const initResponse = await initReportFunc(options); if (initResponse.type === 'error') { return initResponse; } const pollId = initResponse.value; let apiResponse; let response; // eslint-disable-next-line no-constant-condition while (true) { // eslint-disable-next-line no-await-in-loop apiResponse = await getReportFunc({ ...lodash_pick_1.default(options, ['baseURL', 'sessionToken', 'source', 'requestId', 'org', 'orgId']), pollId, }); if (apiResponse.type === 'error') { return apiResponse; } response = apiResponse.value; if (response.status === http_1.AnalysisStatus.waiting || response.status === http_1.AnalysisStatus.fetching || response.status === http_1.AnalysisStatus.analyzing || response.status === http_1.AnalysisStatus.done) { // Report progress of fetching emitter_1.emitter.analyseProgress(response); } else if (response.status === http_1.AnalysisStatus.complete) { // Return data of analysis return apiResponse; // deepcode ignore DuplicateIfBody: false positive it seems that interface is not taken into account } else if (response.status === http_1.AnalysisStatus.failed) { // Report failure of analysing return apiResponse; } // eslint-disable-next-line no-await-in-loop await sleep(constants_1.POLLING_INTERVAL); } } async function reportBundle(options) { var _a, _b; const projectName = (_b = (_a = options.report) === null || _a === void 0 ? void 0 : _a.projectName) === null || _b === void 0 ? void 0 : _b.trim(); if (!projectName || projectName.length === 0) { throw new Error('"project-name" must be provided for "report"'); } if (/[^A-Za-z0-9-_/]/g.test(projectName)) { throw new Error(`"project-name" must not contain spaces or special characters except [/-_]`); } // Trigger bundle analysis and emit intermediate progress. const response = await initAndPollReportGeneric(http_1.initReport, http_1.getReport, options); if (response.type === 'error') { throw response.error; } else if (response.value.status === http_1.AnalysisStatus.failed) { throw new Error('Analysis has failed'); } return response.value; } exports.reportBundle = reportBundle; async function reportScm(options) { var _a, _b; const projectId = (_a = options.projectId) === null || _a === void 0 ? void 0 : _a.trim(); if (!projectId || projectId.length === 0) { throw new Error('"project-id" must be provided for "report"'); } if (!uuid.validate(projectId)) { throw new Error('"project-id" must be a valid UUID'); } const commitId = (_b = options.commitId) === null || _b === void 0 ? void 0 : _b.trim(); if (!commitId || commitId.length === 0) { throw new Error('"commit-id" must be provided for "report"'); } // Trigger SCM project analysis and emit intermediate progress. const response = await initAndPollReportGeneric(http_1.initScmReport, http_1.getScmReport, options); if (response.type === 'error') { throw response.error; } else if (response.value.status === http_1.AnalysisStatus.failed) { throw new Error('Analysis has failed'); } return response.value; } exports.reportScm = reportScm; //# sourceMappingURL=report.js.map /***/ }), /***/ 11294: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.generateErrorWithDetail = exports.getURL = void 0; const constants_1 = __webpack_require__(65765); function getURL(baseURL, path, orgId) { if (routeToGateway(baseURL)) { if (!isValidOrg(orgId)) { throw new Error('A valid Org id is required for this operation'); } return `${baseURL}/hidden/orgs/${orgId}/code${path}`; } return `${baseURL}${path}`; } exports.getURL = getURL; function routeToGateway(baseURL) { return baseURL.includes('snykgov.io'); } function isValidOrg(orgId) { return orgId !== undefined && constants_1.ORG_ID_REGEXP.test(orgId); } function generateErrorWithDetail(error, statusCode, apiName) { var _a; const errorLink = (_a = error.links) === null || _a === void 0 ? void 0 : _a.about; const detail = `${error.title}${error.detail ? `: ${error.detail}` : ''}${errorLink ? ` (more info: ${errorLink})` : ``}`; const statusText = error.title; return { type: 'error', error: { apiName, statusCode: statusCode, statusText, detail, }, }; } exports.generateErrorWithDetail = generateErrorWithDetail; //# sourceMappingURL=httpUtils.js.map /***/ }), /***/ 49503: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const AggregateError = __webpack_require__(56455); module.exports = async ( iterable, mapper, { concurrency = Infinity, stopOnError = true } = {} ) => { return new Promise((resolve, reject) => { if (typeof mapper !== 'function') { throw new TypeError('Mapper function is required'); } if (!(typeof concurrency === 'number' && concurrency >= 1)) { throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${concurrency}\` (${typeof concurrency})`); } const ret = []; const errors = []; const iterator = iterable[Symbol.iterator](); let isRejected = false; let isIterableDone = false; let resolvingCount = 0; let currentIndex = 0; const next = () => { if (isRejected) { return; } const nextItem = iterator.next(); const i = currentIndex; currentIndex++; if (nextItem.done) { isIterableDone = true; if (resolvingCount === 0) { if (!stopOnError && errors.length !== 0) { reject(new AggregateError(errors)); } else { resolve(ret); } } return; } resolvingCount++; (async () => { try { const element = await nextItem.value; ret[i] = await mapper(element, i); resolvingCount--; next(); } catch (error) { if (stopOnError) { isRejected = true; reject(error); } else { errors.push(error); resolvingCount--; next(); } } })(); }; for (let i = 0; i < concurrency; i++) { next(); if (isIterableDone) { break; } } }); }; /***/ }), /***/ 18920: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); var parse_error_1 = __webpack_require__(78558); exports.ParseError = parse_error_1.ParseError; var invalid_user_input_error_1 = __webpack_require__(95362); exports.InvalidUserInputError = invalid_user_input_error_1.InvalidUserInputError; //# sourceMappingURL=index.js.map /***/ }), /***/ 95362: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); class InvalidUserInputError extends Error { constructor(message) { super(message); this.name = 'InvalidUserInputError'; Error.captureStackTrace(this, InvalidUserInputError); } } exports.InvalidUserInputError = InvalidUserInputError; //# sourceMappingURL=invalid-user-input-error.js.map /***/ }), /***/ 78558: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); class ParseError extends Error { constructor(message) { super(message); this.name = 'ParseError'; Error.captureStackTrace(this, ParseError); } } exports.ParseError = ParseError; //# sourceMappingURL=parse-error.js.map /***/ }), /***/ 59794: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const fs = __webpack_require__(57147); const _isEmpty = __webpack_require__(99245); const path = __webpack_require__(71017); const errors_1 = __webpack_require__(18920); const file_parser_1 = __webpack_require__(64702); const composer_parser_1 = __webpack_require__(70054); function buildDepTree(lockFileContent, manifestFileContent, defaultProjectName, systemVersions, includeDev = false) { const lockFileJson = file_parser_1.FileParser.parseLockFile(lockFileContent); const manifestJson = file_parser_1.FileParser.parseManifestFile(manifestFileContent); if (!lockFileJson.packages) { throw new errors_1.InvalidUserInputError('Invalid lock file. Must contain `packages` property'); } const name = manifestJson.name || defaultProjectName; const version = composer_parser_1.ComposerParser.getVersion(manifestJson) || '0.0.0'; const dependencies = composer_parser_1.ComposerParser.buildDependencies(manifestJson, lockFileJson, manifestJson, systemVersions, includeDev); const hasDevDependencies = !_isEmpty(manifestJson['require-dev']); return { name, version, dependencies, hasDevDependencies, packageFormatVersion: 'composer:0.0.1', }; } exports.buildDepTree = buildDepTree; function buildDepTreeFromFiles(basePath, lockFileName, systemVersions, includeDev = false) { if (!basePath) { throw new errors_1.InvalidUserInputError('Missing `basePath` parameter for buildDepTreeFromFiles()'); } if (!lockFileName) { throw new errors_1.InvalidUserInputError('Missing `lockfile` parameter for buildDepTreeFromFiles()'); } if (!systemVersions) { throw new errors_1.InvalidUserInputError('Missing `systemVersions` parameter for buildDepTreeFromFiles()'); } const lockFilePath = path.resolve(basePath, lockFileName); const manifestFilePath = path.resolve(basePath, path.dirname(lockFilePath), 'composer.json'); if (!fs.existsSync(lockFilePath)) { throw new errors_1.InvalidUserInputError(`Lockfile not found at location: ${lockFilePath}`); } if (!fs.existsSync(manifestFilePath)) { throw new errors_1.InvalidUserInputError(`Target file composer.json not found at location: ${manifestFilePath}`); } const lockFileContent = fs.readFileSync(lockFilePath, 'utf-8'); const manifestFileContent = fs.readFileSync(manifestFilePath, 'utf-8'); const defaultProjectName = getDefaultProjectName(basePath, lockFileName); return buildDepTree(lockFileContent, manifestFileContent, defaultProjectName, systemVersions, includeDev); } exports.buildDepTreeFromFiles = buildDepTreeFromFiles; function getDefaultProjectName(basePath, lockFileName) { return path.dirname(path.resolve(path.join(basePath, lockFileName))).split(path.sep).pop(); } //# sourceMappingURL=index.js.map /***/ }), /***/ 70054: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const _findKey = __webpack_require__(7495); const _get = __webpack_require__(29208); const _invert = __webpack_require__(6668); const _isEmpty = __webpack_require__(99245); const types_1 = __webpack_require__(69932); const _ = { get: _get, isEmpty: _isEmpty, invert: _invert, findKey: _findKey, }; class ComposerParser { static getVersion(depObj) { // check for `version` property. may not exist const versionFound = _.get(depObj, 'version', ''); // even if found, may be an alias, so check const availableAliases = _.get(depObj, "extra['branch-alias']", []); // if the version matches the alias (either as is, or without 'dev-'), use the aliases version. // otherwise, use the version as is, and if not, the first found alias return _.get(availableAliases, versionFound) || _.get(_.invert(availableAliases), versionFound.replace('dev-', '')) && versionFound.replace('dev-', '') || versionFound || _.findKey(_.invert(availableAliases), '0'); // first available alias } static buildDependencies(composerJsonObj, composerLockObj, depObj, systemPackages, includeDev = false, isDevTree = false, depRecursiveArray = [], packageRefCount = {}) { const result = {}; // find depObj properties const depName = _.get(depObj, 'name'); const require = _.get(depObj, 'require', {}); const requireDev = includeDev ? _.get(depObj, 'require-dev', {}) : {}; // recursion tests const inRecursiveArray = depRecursiveArray.indexOf(depName) > -1; const exceedsMaxRepeats = packageRefCount[depName] >= this.MAX_PACKAGE_REPEATS; const hasNoDependencies = _.isEmpty(require) && _.isEmpty(requireDev); // break recursion when if (inRecursiveArray || exceedsMaxRepeats || hasNoDependencies) { return result; } // prevent circular dependencies depRecursiveArray.push(depName); // get locked packages const packages = _.get(composerLockObj, 'packages', []); const packagesDev = includeDev ? _.get(composerLockObj, 'packages-dev', []) : []; const allPackages = [ ...packages, ...packagesDev, ]; // parse require dependencies for (const name of Object.keys(require)) { let version = ''; // lets find if this dependency has an object in composer.lock const lockedPackage = allPackages.find((dep) => dep.name === name); if (lockedPackage) { version = this.getVersion(lockedPackage); } else { // here we use the system version or composer json - not a locked version version = _.get(systemPackages, name) || _.get(require, name); } // remove any starting 'v' from version numbers version = version.replace(/^v(\d)/, '$1'); // bump package reference count (or assign to 1 if we haven't seen this before) packageRefCount[name] = (packageRefCount[name] || 0) + 1; result[name] = { name, version, dependencies: this.buildDependencies(composerJsonObj, composerLockObj, lockedPackage, // undefined if transitive dependency systemPackages, includeDev, false, depRecursiveArray, packageRefCount), labels: { scope: isDevTree ? types_1.Scope.dev : types_1.Scope.prod, }, }; } // parse require-dev dependencies for (const name of Object.keys(requireDev)) { let version = ''; // lets find if this dependency has an object in composer.lock const lockedPackage = allPackages.find((dep) => dep.name === name); if (lockedPackage) { version = this.getVersion(lockedPackage); } else { // here we use the system version or composer json - not a locked version version = _.get(systemPackages, name) || _.get(requireDev, name); } // remove any starting 'v' from version numbers version = version.replace(/^v(\d)/, '$1'); // bump package reference count (or assign to 1 if we haven't seen this before) packageRefCount[name] = (packageRefCount[name] || 0) + 1; result[name] = { name, version, dependencies: this.buildDependencies(composerJsonObj, composerLockObj, lockedPackage, // undefined if transitive dependency systemPackages, includeDev, true, depRecursiveArray, packageRefCount), labels: { scope: types_1.Scope.dev, }, }; } // remove from recursive check depRecursiveArray.pop(); // return dep tree return result; } } exports.ComposerParser = ComposerParser; // After this threshold, a package node in the dep tree won't have expanded dependencies. // This is a cheap protection against combinatorial explosion when there's N packages // that depend on each other (producing N! branches of the dep tree). // The value of 150 was chosen as a lowest one that doesn't break existing tests. // Switching to dependency graph would render this trick obsolete. ComposerParser.MAX_PACKAGE_REPEATS = 150; //# sourceMappingURL=composer-parser.js.map /***/ }), /***/ 64702: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const errors_1 = __webpack_require__(18920); class FileParser { static parseLockFile(lockFileContent) { try { return JSON.parse(lockFileContent); } catch (e) { throw new errors_1.ParseError(`Failed to parse lock file. Error: ${e.message}`); } } static parseManifestFile(manifestFileContent) { try { return JSON.parse(manifestFileContent); } catch (e) { throw new errors_1.ParseError(`Failed to parse manifest file. Error: ${e.message}`); } } } exports.FileParser = FileParser; //# sourceMappingURL=file-parser.js.map /***/ }), /***/ 69932: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); var Scope; (function (Scope) { Scope["prod"] = "prod"; Scope["dev"] = "dev"; })(Scope = exports.Scope || (exports.Scope = {})); //# sourceMappingURL=index.js.map /***/ }), /***/ 81608: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DepGraphBuilder = void 0; const graphlib = __webpack_require__(77947); const dep_graph_1 = __webpack_require__(80918); const validate_graph_1 = __webpack_require__(80753); class DepGraphBuilder { constructor(pkgManager, rootPkg) { this._pkgs = {}; this._pkgNodes = {}; const graph = new graphlib.Graph({ directed: true, multigraph: false, compound: false, }); if (!rootPkg) { rootPkg = { name: '_root', version: '0.0.0', }; } this._rootNodeId = 'root-node'; this._rootPkgId = DepGraphBuilder._getPkgId(rootPkg); this._pkgs[this._rootPkgId] = rootPkg; graph.setNode(this._rootNodeId, { pkgId: this._rootPkgId }); this._pkgNodes[this._rootPkgId] = new Set([this._rootNodeId]); this._graph = graph; this._pkgManager = pkgManager; } get rootNodeId() { return this._rootNodeId; } static _getPkgId(pkg) { return `${pkg.name}@${pkg.version || ''}`; } getPkgs() { return Object.values(this._pkgs); } // TODO: this can create disconnected nodes addPkgNode(pkgInfo, nodeId, nodeInfo) { if (nodeId === this._rootNodeId) { throw new Error('DepGraphBuilder.addPkgNode() cant override root node'); } (0, validate_graph_1.validatePackageURL)(pkgInfo); const pkgId = DepGraphBuilder._getPkgId(pkgInfo); this._pkgs[pkgId] = pkgInfo; this._pkgNodes[pkgId] = this._pkgNodes[pkgId] || new Set(); this._pkgNodes[pkgId].add(nodeId); this._graph.setNode(nodeId, { pkgId, info: nodeInfo }); return this; } // TODO: this can create cycles connectDep(parentNodeId, depNodeId) { if (!this._graph.hasNode(parentNodeId)) { throw new Error('parentNodeId does not exist'); } if (!this._graph.hasNode(depNodeId)) { throw new Error('depNodeId does not exist'); } this._graph.setEdge(parentNodeId, depNodeId); return this; } build() { return new dep_graph_1.DepGraphImpl(this._graph, this._rootNodeId, this._pkgs, this._pkgNodes, this._pkgManager); } } exports.DepGraphBuilder = DepGraphBuilder; //# sourceMappingURL=builder.js.map /***/ }), /***/ 20212: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createChangedPackagesGraph = void 0; const dep_graph_1 = __webpack_require__(80918); const builder_1 = __webpack_require__(81608); const event_loop_spinner_1 = __webpack_require__(77158); /** * Creates an induced subgraph of {@param graphB} with only packages * that are not present in {@param graphA} or have a different version. * * @param graphA * @param graphB */ async function createChangedPackagesGraph(graphA, graphB) { const depGraph = graphB; const graphAPackageIds = new Set(graphA.getDepPkgs().map(dep_graph_1.DepGraphImpl.getPkgId)); const addedOrUpdatedPackages = depGraph .getDepPkgs() .filter((pkg) => !graphAPackageIds.has(dep_graph_1.DepGraphImpl.getPkgId(pkg))); const depGraphBuilder = new builder_1.DepGraphBuilder(depGraph.pkgManager, depGraph.rootPkg); const parentQueue = []; for (const changedPackage of addedOrUpdatedPackages) { for (const changedNodeId of depGraph.getPkgNodeIds(changedPackage)) { //we add all nodes with new and changed packages to the new graph. //a newly added node will also have its dependencies added here, since they are "new". depGraphBuilder.addPkgNode(depGraph.getNodePkg(changedNodeId), changedNodeId, getNodeInfo(depGraph, changedNodeId)); //Push all direct parents of the changed nodes to a queue to later build up a path to root from that node for (const parentId of depGraph.getNodeParentsNodeIds(changedNodeId)) { parentQueue.push([parentId, changedNodeId]); if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } } } //add direct and transitive parents for the changed nodes const visited = new Set([depGraph.rootNodeId]); while (parentQueue.length > 0) { const [nodeId, dependencyNodeId] = parentQueue.pop(); if (visited.has(nodeId)) { //ensure we link parents even if visited through another path depGraphBuilder.connectDep(nodeId, dependencyNodeId); continue; } visited.add(nodeId); depGraphBuilder.addPkgNode(depGraph.getNodePkg(nodeId), nodeId, getNodeInfo(depGraph, nodeId)); depGraphBuilder.connectDep(nodeId, dependencyNodeId); for (const parentId of depGraph.getNodeParentsNodeIds(nodeId)) { parentQueue.push([parentId, nodeId]); if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } } return depGraphBuilder.build(); } exports.createChangedPackagesGraph = createChangedPackagesGraph; function getNodeInfo(depGraph, nodeId) { const nodeInfo = depGraph.getNode(nodeId); if (!nodeInfo || Object.keys(nodeInfo).length === 0) { return undefined; } return nodeInfo; } //# sourceMappingURL=create-changed-packages-graph.js.map /***/ }), /***/ 6139: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createFromJSON = exports.SUPPORTED_SCHEMA_RANGE = void 0; const semver = __webpack_require__(21663); const graphlib = __webpack_require__(77947); const errors_1 = __webpack_require__(79651); const validate_graph_1 = __webpack_require__(80753); const dep_graph_1 = __webpack_require__(80918); exports.SUPPORTED_SCHEMA_RANGE = '^1.0.0'; /** * Create a DepGraph instance from a JSON representation of a dep graph. This * is typically used after passing the graph over the wire as `DepGraphData`. */ function createFromJSON(depGraphData) { validateDepGraphData(depGraphData); const graph = new graphlib.Graph({ directed: true, multigraph: false, compound: false, }); const pkgs = {}; const pkgNodes = {}; for (const { id, info } of depGraphData.pkgs) { pkgs[id] = info.version ? info : { ...info, version: undefined }; } for (const node of depGraphData.graph.nodes) { const pkgId = node.pkgId; if (!pkgNodes[pkgId]) { pkgNodes[pkgId] = new Set(); } pkgNodes[pkgId].add(node.nodeId); graph.setNode(node.nodeId, { pkgId, info: node.info }); } for (const node of depGraphData.graph.nodes) { for (const depNodeId of node.deps) { graph.setEdge(node.nodeId, depNodeId.nodeId); } } (0, validate_graph_1.validateGraph)(graph, depGraphData.graph.rootNodeId, pkgs, pkgNodes); return new dep_graph_1.DepGraphImpl(graph, depGraphData.graph.rootNodeId, pkgs, pkgNodes, depGraphData.pkgManager); } exports.createFromJSON = createFromJSON; function assert(condition, msg) { if (!condition) { throw new errors_1.ValidationError(msg); } } function validateDepGraphData(depGraphData) { assert(!!semver.valid(depGraphData.schemaVersion) && semver.satisfies(depGraphData.schemaVersion, exports.SUPPORTED_SCHEMA_RANGE), `dep-graph schemaVersion not in "${exports.SUPPORTED_SCHEMA_RANGE}"`); assert(depGraphData.pkgManager && !!depGraphData.pkgManager.name, '.pkgManager.name is missing'); const pkgsMap = depGraphData.pkgs.reduce((acc, cur) => { assert(!(cur.id in acc), 'more than one pkg with same id'); assert(!!cur.info, '.pkgs item missing .info'); acc[cur.id] = cur.info; return acc; }, {}); const nodesMap = depGraphData.graph.nodes.reduce((acc, cur) => { assert(!(cur.nodeId in acc), 'more than on node with same id'); acc[cur.nodeId] = cur; return acc; }, {}); const rootNodeId = depGraphData.graph.rootNodeId; const rootNode = nodesMap[rootNodeId]; assert(rootNodeId in nodesMap, `.${rootNodeId} root graph node is missing`); const rootPkgId = rootNode.pkgId; assert(rootPkgId in pkgsMap, `.${rootPkgId} root pkg missing`); assert(nodesMap[rootNodeId].pkgId === rootPkgId, `the root node .pkgId should be "${rootPkgId}"`); const pkgIds = Object.keys(pkgsMap); // NOTE: this name@version check is very strict, // we can relax it later, it just makes things easier now assert(pkgIds.filter((pkgId) => pkgId !== dep_graph_1.DepGraphImpl.getPkgId(pkgsMap[pkgId])) .length === 0, 'pkgs ids should be name@version'); assert(Object.values(nodesMap).filter((node) => !(node.pkgId in pkgsMap)) .length === 0, 'some instance nodes belong to non-existing pkgIds'); assert(Object.values(pkgsMap).filter((pkg) => !pkg.name) .length === 0, 'some .pkgs elements have no .name field'); } //# sourceMappingURL=create-from-json.js.map /***/ }), /***/ 80918: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DepGraphImpl = void 0; const _isEqual = __webpack_require__(72307); const graphlib = __webpack_require__(77947); const create_from_json_1 = __webpack_require__(6139); class DepGraphImpl { constructor(_graph, _rootNodeId, _pkgs, _pkgNodes, _pkgManager) { this._graph = _graph; this._rootNodeId = _rootNodeId; this._pkgs = _pkgs; this._pkgNodes = _pkgNodes; this._pkgManager = _pkgManager; this._countNodePathsToRootCache = new Map(); this._rootPkgId = _graph.node(_rootNodeId).pkgId; this._pkgList = Object.values(_pkgs); this._depPkgsList = this._pkgList.filter((pkg) => pkg !== this.rootPkg); } static getPkgId(pkg) { return `${pkg.name}@${pkg.version || ''}`; } get pkgManager() { return this._pkgManager; } get rootPkg() { return this._pkgs[this._rootPkgId]; } get rootNodeId() { return this._rootNodeId; } /** * Get all unique packages in the graph (including the root package) */ getPkgs() { return this._pkgList; } /** * Get all unique packages in the graph (excluding the root package) */ getDepPkgs() { return this._depPkgsList; } getPkgNodes(pkg) { const pkgId = DepGraphImpl.getPkgId(pkg); const nodes = []; for (const nodeId of Array.from(this._pkgNodes[pkgId])) { const graphNode = this.getGraphNode(nodeId); nodes.push({ info: graphNode.info || {}, }); } return nodes; } getNode(nodeId) { return this.getGraphNode(nodeId).info || {}; } getNodePkg(nodeId) { return this._pkgs[this.getGraphNode(nodeId).pkgId]; } getPkgNodeIds(pkg) { const pkgId = DepGraphImpl.getPkgId(pkg); if (!this._pkgs[pkgId]) { throw new Error(`no such pkg: ${pkgId}`); } return Array.from(this._pkgNodes[pkgId]); } getNodeDepsNodeIds(nodeId) { const deps = this._graph.successors(nodeId); if (!deps) { throw new Error(`no such node: ${nodeId}`); } return deps; } getNodeParentsNodeIds(nodeId) { const parents = this._graph.predecessors(nodeId); if (!parents) { throw new Error(`no such node: ${nodeId}`); } return parents; } hasCycles() { // `isAcyclic` is expensive, so memoize if (this._hasCycles === undefined) { this._hasCycles = !graphlib.alg.isAcyclic(this._graph); } return this._hasCycles; } pkgPathsToRoot(pkg, opts) { const pathsToRoot = []; const limit = opts === null || opts === void 0 ? void 0 : opts.limit; for (const nodeId of this.getPkgNodeIds(pkg)) { const pathsFromNodeToRoot = this.pathsFromNodeToRoot(nodeId, [], { limit, }); for (const path of pathsFromNodeToRoot) { pathsToRoot.push(path); } if (limit && pathsToRoot.length >= limit) { break; } } // note: sorting to get shorter paths first - // it's nicer - and better resembles older behaviour return pathsToRoot.sort((a, b) => a.length - b.length); } countPathsToRoot(pkg, opts) { let count = 0; const limit = opts === null || opts === void 0 ? void 0 : opts.limit; for (const nodeId of this.getPkgNodeIds(pkg)) { if (this._countNodePathsToRootCache.has(nodeId)) { count += this._countNodePathsToRootCache.get(nodeId); } else { const c = this.countNodePathsToRoot(nodeId, limit); // don't cache if a limit was supplied if (!limit) { this._countNodePathsToRootCache.set(nodeId, c); } count += c; } if (limit && count >= limit) { return limit; } } return count; } isTransitive(pkg) { const checking = new Set(this.getPkgNodeIds(pkg)); for (const directDep of this.getNodeDepsNodeIds(this.rootNodeId)) { if (checking.has(directDep)) return false; } return true; } equals(other, { compareRoot = true } = {}) { let otherDepGraph; if (other instanceof DepGraphImpl) { otherDepGraph = other; } else { // At runtime theoretically we can have multiple versions of // @snyk/dep-graph. If "other" is not an instance of the same class it is // safer to rebuild it from JSON. otherDepGraph = (0, create_from_json_1.createFromJSON)(other.toJSON()); } // In theory, for the graphs created by standard means, `_.isEquals(this._data, otherDepGraph._data)` // should suffice, since node IDs will be generated in a predictable way. // However, there might be different versions of graph and inconsistencies // in the ordering of the arrays, so we perform a deep comparison. return this.nodeEquals(this, this.rootNodeId, otherDepGraph, otherDepGraph.rootNodeId, compareRoot); } directDepsLeadingTo(pkg) { const pkgNodes = this.getPkgNodeIds(pkg); const directDeps = this.getNodeDepsNodeIds(this.rootNodeId); const nodes = directDeps.filter((directDep) => { const reachableNodes = graphlib.alg.postorder(this._graph, [directDep]); return reachableNodes.filter((node) => pkgNodes.includes(node)).length; }); return nodes.map((node) => this.getNodePkg(node)); } /** * Create a JSON representation of a dep graph. This is typically used to * send the dep graph over the wire */ toJSON() { const nodeIds = this._graph.nodes(); const nodes = nodeIds.reduce((acc, nodeId) => { const deps = (this._graph.successors(nodeId) || []).map((depNodeId) => ({ nodeId: depNodeId, })); const node = this._graph.node(nodeId); const elem = { nodeId, pkgId: node.pkgId, deps, }; if (node.info && Object.keys(node.info).length > 0) { elem.info = node.info; } acc.push(elem); return acc; }, []); const pkgs = Object.keys(this._pkgs).map((pkgId) => ({ id: pkgId, info: this._pkgs[pkgId], })); return { schemaVersion: DepGraphImpl.SCHEMA_VERSION, pkgManager: this._pkgManager, pkgs, graph: { rootNodeId: this._rootNodeId, nodes, }, }; } nodeEquals(graphA, nodeIdA, graphB, nodeIdB, compareRoot, traversedPairs = new Set()) { // Skip root nodes comparison if needed. if (compareRoot || (nodeIdA !== graphA.rootNodeId && nodeIdB !== graphB.rootNodeId)) { const pkgA = graphA.getNodePkg(nodeIdA); const pkgB = graphB.getNodePkg(nodeIdB); // Compare PkgInfo (name and version). if (!_isEqual(pkgA, pkgB)) { return false; } const infoA = graphA.getNode(nodeIdA); const infoB = graphB.getNode(nodeIdB); // Compare NodeInfo (VersionProvenance and labels). if (!_isEqual(infoA, infoB)) { return false; } } let depsA = graphA.getNodeDepsNodeIds(nodeIdA); let depsB = graphB.getNodeDepsNodeIds(nodeIdB); // Number of dependencies should be the same. if (depsA.length !== depsB.length) { return false; } // Sort dependencies by name@version string. const sortFn = (graph) => (idA, idB) => { const pkgA = graph.getNodePkg(idA); const pkgB = graph.getNodePkg(idB); return DepGraphImpl.getPkgId(pkgA).localeCompare(DepGraphImpl.getPkgId(pkgB)); }; depsA = depsA.sort(sortFn(graphA)); depsB = depsB.sort(sortFn(graphB)); // Compare Each dependency recursively. for (let i = 0; i < depsA.length; i++) { const pairKey = `${depsA[i]}_${depsB[i]}`; // Prevent cycles. if (traversedPairs.has(pairKey)) { continue; } traversedPairs.add(pairKey); if (!this.nodeEquals(graphA, depsA[i], graphB, depsB[i], compareRoot, traversedPairs)) { return false; } } return true; } getGraphNode(nodeId) { const node = this._graph.node(nodeId); if (!node) { throw new Error(`no such node: ${nodeId}`); } return node; } pathsFromNodeToRoot(nodeId, ancestors = [], opts) { const parentNodesIds = this.getNodeParentsNodeIds(nodeId); const pkgInfo = this.getNodePkg(nodeId); if (parentNodesIds.length === 0) { return [[pkgInfo]]; } const allPaths = []; ancestors = ancestors.concat(nodeId); const limit = opts.limit; for (const id of parentNodesIds) { if (ancestors.includes(id)) continue; const pathsFromNodeToRoot = this.pathsFromNodeToRoot(id, ancestors, opts); for (const path of pathsFromNodeToRoot) { allPaths.push([pkgInfo].concat(path)); } if (limit && allPaths.length >= limit) { break; } } return allPaths; } countNodePathsToRoot(nodeId, limit = 0, count = 0, visited = []) { if (nodeId === this._rootNodeId) { return count + 1; } visited = visited.concat(nodeId); for (const parentNodeId of this.getNodeParentsNodeIds(nodeId)) { if (!visited.includes(parentNodeId)) { count = this.countNodePathsToRoot(parentNodeId, limit, count, visited); if (limit && count >= limit) { return limit; } } } return count; } } exports.DepGraphImpl = DepGraphImpl; DepGraphImpl.SCHEMA_VERSION = '1.3.0'; //# sourceMappingURL=dep-graph.js.map /***/ }), /***/ 54519: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CustomError = void 0; class CustomError extends Error { constructor(message) { super(message); Object.setPrototypeOf(this, CustomError.prototype); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; } } exports.CustomError = CustomError; //# sourceMappingURL=custom-error.js.map /***/ }), /***/ 79651: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ValidationError = void 0; const validation_error_1 = __webpack_require__(85151); Object.defineProperty(exports, "ValidationError", ({ enumerable: true, get: function () { return validation_error_1.ValidationError; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 85151: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ValidationError = void 0; const custom_error_1 = __webpack_require__(54519); class ValidationError extends custom_error_1.CustomError { constructor(message) { super(message); Object.setPrototypeOf(this, ValidationError.prototype); } } exports.ValidationError = ValidationError; //# sourceMappingURL=validation-error.js.map /***/ }), /***/ 80753: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.validatePackageURL = exports.validateGraph = void 0; const graphlib = __webpack_require__(77947); const packageurl_js_1 = __webpack_require__(38382); const errors_1 = __webpack_require__(79651); const reGolangPseudoVersion = /(v\d+\.\d+\.\d+)-(.*?)(\d{14})-([0-9a-f]{12})/; const reGolangExactVersion = /^(.*?)(\+incompatible)?$/; function assert(condition, msg) { if (!condition) { throw new errors_1.ValidationError(msg); } } function validateGraph(graph, rootNodeId, pkgs, pkgNodes) { assert((graph.predecessors(rootNodeId) || []).length === 0, `"${rootNodeId}" is not really the root`); const reachableFromRoot = graphlib.alg.postorder(graph, [rootNodeId]); const nodeIds = graph.nodes(); assert(JSON.stringify(nodeIds.sort()) === JSON.stringify(reachableFromRoot.sort()), 'not all graph nodes are reachable from root'); const pkgIds = Object.keys(pkgs); const pkgsWithoutInstances = pkgIds.filter((pkgId) => !pkgNodes[pkgId] || pkgNodes[pkgId].size === 0); assert(pkgsWithoutInstances.length === 0, 'not all pkgs have instance nodes'); for (const pkgId in pkgs) { try { validatePackageURL(pkgs[pkgId]); } catch (e) { throw new errors_1.ValidationError(`invalid pkg ${pkgId}: ${e}`); } } } exports.validateGraph = validateGraph; function validatePackageURL(pkg) { var _a; if (!pkg.purl) { return; } try { const purl = packageurl_js_1.PackageURL.fromString(pkg.purl); // validate package name switch (purl.type) { // Within Snyk, maven packages use : as their *name*, but // we expect those to be separated correctly in the PackageURL. case 'maven': assert(pkg.name === purl.namespace + ':' + purl.name, `name and packageURL name do not match`); break; // CocoaPods have an optional subspec encoded in the subpath // component of the purl, which – if present – should // be appended to the spec. case 'cocoapods': assert(pkg.name === (purl.subpath ? `${purl.name}/${purl.subpath}` : purl.name), `name and packageURL name do not match`); break; case 'golang': { let expected = purl.namespace ? `${purl.namespace}/${purl.name}` : purl.name; if (purl.subpath) expected += `/${purl.subpath}`; assert(pkg.name === expected, `name and packageURL name do not match`); break; } case 'composer': case 'npm': case 'swift': assert(pkg.name === (purl.namespace ? `${purl.namespace}/${purl.name}` : purl.name), `name and packageURL name do not match`); break; // The PURL spec for Linux distros does not include the source in the name. // This is why we relax the assertion here and match only on the package name: // / - we omit the source name // For now, make this exception only for deb to cover a support case. case 'deb': { const pkgName = pkg.name.split('/').pop(); assert(pkgName === purl.name, 'name and packageURL name do not match'); if (((_a = purl.qualifiers) === null || _a === void 0 ? void 0 : _a['upstream']) && pkg.name.includes('/')) { const pkgSrc = pkg.name.split('/')[0]; const pkgUpstream = purl.qualifiers['upstream'].split('@')[0]; assert(pkgSrc === pkgUpstream, 'source and packageURL source do not match'); } break; } default: assert(pkg.name === purl.name, `name and packageURL name do not match`); } // validate package version switch (purl.type) { // the Snyk version of a golang module is either // - the version without "v", e.g. v1.2.3 -> 1.2.3 // - the pseudo-version hash, e.g. v0.0.0-000-acf48ae230a1 -> #acf48ae230a1 case 'golang': { let version = purl.version; if (purl.version) { const maybePseudoVersion = reGolangPseudoVersion.exec(purl.version); const maybeExactVersion = reGolangExactVersion.exec(purl.version); if (maybePseudoVersion) { version = `#${maybePseudoVersion[4]}`; } else if (maybeExactVersion) { version = maybeExactVersion[1].replace(/^v/, ''); } } assert(pkg.version === version, `version and packageURL version do not match. want ${pkg.version} have: ${version}`); break; } default: assert(pkg.version === purl.version, `version and packageURL version do not match`); } } catch (e) { throw new errors_1.ValidationError(`packageURL validation failed: ${e}`); } } exports.validatePackageURL = validatePackageURL; //# sourceMappingURL=validate-graph.js.map /***/ }), /***/ 25261: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.dfs = void 0; const each = __webpack_require__(43590); /* * A helper that preforms a pre- or post-order traversal on the input graph * and returns the nodes in the order they were visited. If the graph is * undirected then this algorithm will navigate using neighbors. If the graph * is directed then this algorithm will navigate using successors. * * Order must be one of "pre" or "post". */ function dfs(g, vs, order) { if (!Array.isArray(vs)) { vs = [vs]; } const navigation = (g.isDirected() ? g.successors : g.neighbors).bind(g); const acc = []; const visited = {}; each(vs, (v) => { if (!g.hasNode(v)) { throw new Error('Graph does not have node: ' + v); } doDfs(g, v, order === 'post', visited, navigation, acc); }); return acc; } exports.dfs = dfs; function doDfs(g, v, postorder, visited, navigation, acc) { if (!(v in visited)) { visited[v] = true; if (!postorder) { acc.push(v); } each(navigation(v), function (w) { doDfs(g, w, postorder, visited, navigation, acc); }); if (postorder) { acc.push(v); } } } //# sourceMappingURL=dfs.js.map /***/ }), /***/ 40976: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isAcyclic = void 0; const topsort_1 = __webpack_require__(29865); function isAcyclic(g) { try { (0, topsort_1.topsort)(g); } catch (e) { if (e instanceof topsort_1.CycleException) { return false; } throw e; } return true; } exports.isAcyclic = isAcyclic; //# sourceMappingURL=is-acyclic.js.map /***/ }), /***/ 45300: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.postorder = void 0; const dfs_1 = __webpack_require__(25261); function postorder(g, vs) { return (0, dfs_1.dfs)(g, vs, 'post'); } exports.postorder = postorder; //# sourceMappingURL=postorder.js.map /***/ }), /***/ 29865: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CycleException = exports.topsort = void 0; const each = __webpack_require__(43590); const size = __webpack_require__(27946); function topsort(g) { const visited = {}; const stack = {}; const results = []; function visit(node) { if (node in stack) { throw new CycleException(); } if (!(node in visited)) { stack[node] = true; visited[node] = true; each(g.predecessors(node), visit); delete stack[node]; results.push(node); } } each(g.sinks(), visit); if (size(visited) !== g.nodeCount()) { throw new CycleException(); } return results; } exports.topsort = topsort; class CycleException extends Error { } exports.CycleException = CycleException; //# sourceMappingURL=topsort.js.map /***/ }), /***/ 69946: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Graph = void 0; /* eslint-disable prefer-rest-params */ /* eslint-disable @typescript-eslint/no-this-alias */ const constant = __webpack_require__(4254); const each = __webpack_require__(43590); const _filter = __webpack_require__(43590); const isEmpty = __webpack_require__(99245); const isFunction = __webpack_require__(98423); const isUndefined = __webpack_require__(28801); const reduce = __webpack_require__(34766); const union = __webpack_require__(96744); const values = __webpack_require__(17720); const DEFAULT_EDGE_NAME = '\x00'; const GRAPH_NODE = '\x00'; const EDGE_KEY_DELIM = '\x01'; // Implementation notes: // // * Node id query functions should return string ids for the nodes // * Edge id query functions should return an "edgeObj", edge object, that is // composed of enough information to uniquely identify an edge: {v, w, name}. // * Internally we use an "edgeId", a stringified form of the edgeObj, to // reference edges. This is because we need a performant way to look these // edges up and, object properties, which have string keys, are the closest // we're going to get to a performant hashtable in JavaScript. class Graph { constructor(opts) { var _a, _b, _c; /* Number of nodes in the graph. Should only be changed by the implementation. */ this._nodeCount = 0; /* Number of edges in the graph. Should only be changed by the implementation. */ this._edgeCount = 0; this._isDirected = (_a = opts === null || opts === void 0 ? void 0 : opts.directed) !== null && _a !== void 0 ? _a : true; this._isMultigraph = (_b = opts === null || opts === void 0 ? void 0 : opts.multigraph) !== null && _b !== void 0 ? _b : false; this._isCompound = (_c = opts === null || opts === void 0 ? void 0 : opts.compound) !== null && _c !== void 0 ? _c : false; // Label for the graph itself this._label = undefined; // Defaults to be set when creating a new node this._defaultNodeLabelFn = constant(undefined); // Defaults to be set when creating a new edge this._defaultEdgeLabelFn = constant(undefined); // v -> label this._nodes = {}; if (this._isCompound) { // v -> parent this._parent = {}; // v -> children this._children = {}; this._children[GRAPH_NODE] = {}; } // v -> edgeObj this._in = {}; // u -> v -> Number this._preds = {}; // v -> edgeObj this._out = {}; // v -> w -> Number this._sucs = {}; // e -> edgeObj this._edgeObjs = {}; // e -> label this._edgeLabels = {}; } /* === Graph functions ========= */ isDirected() { return this._isDirected; } isMultigraph() { return this._isMultigraph; } isCompound() { return this._isCompound; } setGraph(label) { this._label = label; return this; } graph() { return this._label; } /* === Node functions ========== */ setDefaultNodeLabel(newDefault) { if (!isFunction(newDefault)) { newDefault = constant(newDefault); } this._defaultNodeLabelFn = newDefault; return this; } nodeCount() { return this._nodeCount; } nodes() { return Object.keys(this._nodes); } sources() { const self = this; return _filter(this.nodes(), function (v) { return isEmpty(self._in[v]); }); } sinks() { const self = this; return _filter(this.nodes(), function (v) { return isEmpty(self._out[v]); }); } setNodes(vs, value) { const args = arguments; const self = this; each(vs, function (v) { if (args.length > 1) { self.setNode(v, value); } else { self.setNode(v); } }); return this; } setNode(v, value) { if (v in this._nodes) { if (arguments.length > 1) { this._nodes[v] = value; } return this; } this._nodes[v] = arguments.length > 1 ? value : this._defaultNodeLabelFn(v); if (this._isCompound) { this._parent[v] = GRAPH_NODE; this._children[v] = {}; this._children[GRAPH_NODE][v] = true; } this._in[v] = {}; this._preds[v] = {}; this._out[v] = {}; this._sucs[v] = {}; ++this._nodeCount; return this; } node(v) { return this._nodes[v]; } hasNode(v) { return v in this._nodes; } removeNode(v) { const self = this; if (v in this._nodes) { const removeEdge = function (e) { self.removeEdge(self._edgeObjs[e]); }; delete this._nodes[v]; if (this._isCompound) { this._removeFromParentsChildList(v); delete this._parent[v]; each(this.children(v), function (child) { self.setParent(child); }); delete this._children[v]; } each(Object.keys(this._in[v]), removeEdge); delete this._in[v]; delete this._preds[v]; each(Object.keys(this._out[v]), removeEdge); delete this._out[v]; delete this._sucs[v]; --this._nodeCount; } return this; } setParent(v, parent) { if (!this._isCompound) { throw new Error('Cannot set parent in a non-compound graph'); } if (isUndefined(parent)) { parent = GRAPH_NODE; } else { // Coerce parent to string parent += ''; for (let ancestor = parent; !isUndefined(ancestor); ancestor = this.parent(ancestor)) { if (ancestor === v) { throw new Error('Setting ' + parent + ' as parent of ' + v + ' would create a cycle'); } } this.setNode(parent); } this.setNode(v); this._removeFromParentsChildList(v); this._parent[v] = parent; this._children[parent][v] = true; return this; } _removeFromParentsChildList(v) { delete this._children[this._parent[v]][v]; } parent(v) { if (this._isCompound) { const parent = this._parent[v]; if (parent !== GRAPH_NODE) { return parent; } } } children(v) { if (isUndefined(v)) { v = GRAPH_NODE; } if (this._isCompound) { const children = this._children[v]; if (children) { return Object.keys(children); } } else if (v === GRAPH_NODE) { return this.nodes(); } else if (this.hasNode(v)) { return []; } } predecessors(v) { const predsV = this._preds[v]; if (predsV) { return Object.keys(predsV); } } successors(v) { const sucsV = this._sucs[v]; if (sucsV) { return Object.keys(sucsV); } } neighbors(v) { const preds = this.predecessors(v); if (preds) { return union(preds, this.successors(v)); } } isLeaf(v) { let neighbors; if (this.isDirected()) { neighbors = this.successors(v); } else { neighbors = this.neighbors(v); } return neighbors.length === 0; } filterNodes(filter) { const copy = new Graph({ directed: this._isDirected, multigraph: this._isMultigraph, compound: this._isCompound, }); copy.setGraph(this.graph()); const self = this; each(this._nodes, function (value, v) { if (filter(v)) { copy.setNode(v, value); } }); each(this._edgeObjs, function (e) { if (copy.hasNode(e.v) && copy.hasNode(e.w)) { copy.setEdge(e, self.edge(e)); } }); const parents = {}; function findParent(v) { const parent = self.parent(v); if (parent === undefined || copy.hasNode(parent)) { parents[v] = parent; return parent; } else if (parent in parents) { return parents[parent]; } else { return findParent(parent); } } if (this._isCompound) { each(copy.nodes(), function (v) { copy.setParent(v, findParent(v)); }); } return copy; } /* === Edge functions ========== */ setDefaultEdgeLabel(newDefault) { if (!isFunction(newDefault)) { newDefault = constant(newDefault); } this._defaultEdgeLabelFn = newDefault; return this; } edgeCount() { return this._edgeCount; } edges() { return values(this._edgeObjs); } setPath(vs, value) { const self = this; const args = arguments; reduce(vs, function (v, w) { if (args.length > 1) { self.setEdge(v, w, value); } else { self.setEdge(v, w); } return w; }); return this; } // eslint-disable-next-line @typescript-eslint/no-unused-vars setEdge(...args) { let v, w, name, value; let valueSpecified = false; const arg0 = arguments[0]; if (typeof arg0 === 'object' && arg0 !== null && 'v' in arg0) { v = arg0.v; w = arg0.w; name = arg0.name; if (arguments.length === 2) { value = arguments[1]; valueSpecified = true; } } else { v = arg0; w = arguments[1]; name = arguments[3]; if (arguments.length > 2) { value = arguments[2]; valueSpecified = true; } } v = '' + v; w = '' + w; if (!isUndefined(name)) { name = '' + name; } const e = edgeArgsToId(this._isDirected, v, w, name); if (e in this._edgeLabels) { if (valueSpecified) { this._edgeLabels[e] = value; } return this; } if (!isUndefined(name) && !this._isMultigraph) { throw new Error('Cannot set a named edge when isMultigraph = false'); } // It didn't exist, so we need to create it. // First ensure the nodes exist. this.setNode(v); this.setNode(w); this._edgeLabels[e] = valueSpecified ? value : this._defaultEdgeLabelFn(v, w, name); const edgeObj = edgeArgsToObj(this._isDirected, v, w, name); // Ensure we add undirected edges in a consistent way. v = edgeObj.v; w = edgeObj.w; Object.freeze(edgeObj); this._edgeObjs[e] = edgeObj; incrementOrInitEntry(this._preds[w], v); incrementOrInitEntry(this._sucs[v], w); this._in[w][e] = edgeObj; this._out[v][e] = edgeObj; this._edgeCount++; return this; } edge(v, w, name) { const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); return this._edgeLabels[e]; } hasEdge(v, w, name) { const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); return e in this._edgeLabels; } removeEdge(v, w, name) { const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); const edge = this._edgeObjs[e]; if (edge) { v = edge.v; w = edge.w; delete this._edgeLabels[e]; delete this._edgeObjs[e]; decrementOrRemoveEntry(this._preds[w], v); decrementOrRemoveEntry(this._sucs[v], w); delete this._in[w][e]; delete this._out[v][e]; this._edgeCount--; } return this; } inEdges(v, u) { const inV = this._in[v]; if (inV) { const edges = values(inV); if (!u) { return edges; } return _filter(edges, function (edge) { return edge.v === u; }); } } outEdges(v, w) { const outV = this._out[v]; if (outV) { const edges = values(outV); if (!w) { return edges; } return _filter(edges, function (edge) { return edge.w === w; }); } } nodeEdges(v, w) { const inEdges = this.inEdges(v, w); if (inEdges) { return inEdges.concat(this.outEdges(v, w)); } } } exports.Graph = Graph; function incrementOrInitEntry(map, k) { if (map[k]) { map[k]++; } else { map[k] = 1; } } function decrementOrRemoveEntry(map, k) { if (!--map[k]) { delete map[k]; } } function edgeArgsToId(isDirected, v_, w_, name) { let v = '' + v_; let w = '' + w_; if (!isDirected && v > w) { const tmp = v; v = w; w = tmp; } return (v + EDGE_KEY_DELIM + w + EDGE_KEY_DELIM + (isUndefined(name) ? DEFAULT_EDGE_NAME : name)); } function edgeArgsToObj(isDirected, v_, w_, name) { let v = '' + v_; let w = '' + w_; if (!isDirected && v > w) { const tmp = v; v = w; w = tmp; } const edgeObj = { v: v, w: w }; if (name) { edgeObj.name = name; } return edgeObj; } function edgeObjToId(isDirected, edgeObj) { return edgeArgsToId(isDirected, edgeObj.v, edgeObj.w, edgeObj.name); } //# sourceMappingURL=graph.js.map /***/ }), /***/ 77947: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.alg = exports.Graph = void 0; var graph_1 = __webpack_require__(69946); Object.defineProperty(exports, "Graph", ({ enumerable: true, get: function () { return graph_1.Graph; } })); const is_acyclic_1 = __webpack_require__(40976); const postorder_1 = __webpack_require__(45300); exports.alg = { isAcyclic: is_acyclic_1.isAcyclic, postorder: postorder_1.postorder, }; //# sourceMappingURL=index.js.map /***/ }), /***/ 71479: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.legacy = exports.Errors = exports.createChangedPackagesGraph = exports.DepGraphBuilder = exports.createFromJSON = void 0; var create_from_json_1 = __webpack_require__(6139); Object.defineProperty(exports, "createFromJSON", ({ enumerable: true, get: function () { return create_from_json_1.createFromJSON; } })); var builder_1 = __webpack_require__(81608); Object.defineProperty(exports, "DepGraphBuilder", ({ enumerable: true, get: function () { return builder_1.DepGraphBuilder; } })); var create_changed_packages_graph_1 = __webpack_require__(20212); Object.defineProperty(exports, "createChangedPackagesGraph", ({ enumerable: true, get: function () { return create_changed_packages_graph_1.createChangedPackagesGraph; } })); const Errors = __webpack_require__(79651); exports.Errors = Errors; const legacy = __webpack_require__(67790); exports.legacy = legacy; //# sourceMappingURL=index.js.map /***/ }), /***/ 83422: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.partitionCycles = exports.getCycle = void 0; function getCycle(ancestors, nodeId) { if (!ancestors.includes(nodeId)) { return null; } // first item is where the cycle starts and ends. return ancestors.slice(ancestors.indexOf(nodeId)); } exports.getCycle = getCycle; function partitionCycles(nodeId, allCyclesTheNodeIsPartOf) { const cyclesStartWithThisNode = []; const cyclesWithThisNode = []; for (const cycle of allCyclesTheNodeIsPartOf) { const nodeStartsCycle = cycle[0] === nodeId; if (nodeStartsCycle) { cyclesStartWithThisNode.push(cycle); } else { cyclesWithThisNode.push(cycle); } } return { cyclesStartWithThisNode, cyclesWithThisNode }; } exports.partitionCycles = partitionCycles; //# sourceMappingURL=cycles.js.map /***/ }), /***/ 67790: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.graphToDepTree = exports.depTreeToGraph = void 0; const crypto = __webpack_require__(6113); const event_loop_spinner_1 = __webpack_require__(77158); const builder_1 = __webpack_require__(81608); const objectHash = __webpack_require__(49807); const cycles_1 = __webpack_require__(83422); const memiozation_1 = __webpack_require__(98155); function addLabel(dep, key, value) { if (!dep.labels) { dep.labels = {}; } dep.labels[key] = value; } /** * @deprecated Don't use dep trees as an intermediate step, because they are * large structures, resulting in high memory usage and high CPU costs from * serializing / deserializing. Instead, create a graph directly with * {@link DepGraphBuilder} */ async function depTreeToGraph(depTree, pkgManagerName) { const rootPkg = { name: depTree.name, version: depTree.version || undefined, }; if (depTree.purl) { rootPkg.purl = depTree.purl; } const pkgManagerInfo = { name: pkgManagerName, }; const targetOS = depTree.targetOS; if (targetOS) { pkgManagerInfo.repositories = [ { alias: `${targetOS.name}:${targetOS.version}`, }, ]; } const builder = new builder_1.DepGraphBuilder(pkgManagerInfo, rootPkg); await buildGraph(builder, depTree, depTree.name, true); const depGraph = await builder.build(); return shortenNodeIds(depGraph); } exports.depTreeToGraph = depTreeToGraph; async function buildGraph(builder, depTree, pkgName, isRoot = false, memoizationMap = new Map()) { if (memoizationMap.has(depTree)) { return memoizationMap.get(depTree); } const getNodeId = (name, version, hashId) => `${name}@${version || ''}|${hashId}`; const depNodesIds = []; const hash = crypto.createHash('sha1'); if (depTree.versionProvenance) { hash.update(objectHash(depTree.versionProvenance)); } if (depTree.labels) { hash.update(objectHash(depTree.labels)); } const deps = depTree.dependencies || {}; // filter-out invalid null deps (shouldn't happen - but did...) const depNames = Object.keys(deps).filter((d) => !!deps[d]); for (const depName of depNames.sort()) { const dep = deps[depName]; const subtreeHash = await buildGraph(builder, dep, depName, false, memoizationMap); const depPkg = { name: depName, version: dep.version, }; if (dep.purl) { depPkg.purl = dep.purl; } const depNodeId = getNodeId(depPkg.name, depPkg.version, subtreeHash); depNodesIds.push(depNodeId); const nodeInfo = {}; if (dep.versionProvenance) { nodeInfo.versionProvenance = dep.versionProvenance; } if (dep.labels) { nodeInfo.labels = dep.labels; } builder.addPkgNode(depPkg, depNodeId, nodeInfo); hash.update(depNodeId); } const treeHash = hash.digest('hex'); let pkgNodeId; if (isRoot) { pkgNodeId = builder.rootNodeId; } else { // we don't assume depTree has a .name to support output of `npm list --json` const pkg = { name: pkgName, version: depTree.version, }; pkgNodeId = getNodeId(pkg.name, pkg.version, treeHash); const nodeInfo = {}; if (depTree.versionProvenance) { nodeInfo.versionProvenance = depTree.versionProvenance; } if (depTree.labels) { nodeInfo.labels = depTree.labels; } builder.addPkgNode(pkg, pkgNodeId, nodeInfo); } for (const depNodeId of depNodesIds) { builder.connectDep(pkgNodeId, depNodeId); } if (depNodesIds.length > 0 && event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } memoizationMap.set(depTree, treeHash); return treeHash; } async function shortenNodeIds(depGraph) { const builder = new builder_1.DepGraphBuilder(depGraph.pkgManager, depGraph.rootPkg); const nodesMap = {}; // create nodes with shorter ids for (const pkg of depGraph.getPkgs()) { const nodeIds = depGraph.getPkgNodeIds(pkg); for (let i = 0; i < nodeIds.length; i++) { const nodeId = nodeIds[i]; if (nodeId === depGraph.rootNodeId) { continue; } const nodeInfo = depGraph.getNode(nodeId); let newNodeId; if (nodeIds.length === 1) { newNodeId = `${trimAfterLastSep(nodeId, '|')}`; } else { newNodeId = `${trimAfterLastSep(nodeId, '|')}|${i + 1}`; } nodesMap[nodeId] = newNodeId; builder.addPkgNode(pkg, newNodeId, nodeInfo); } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } // connect nodes for (const pkg of depGraph.getPkgs()) { for (const nodeId of depGraph.getPkgNodeIds(pkg)) { for (const depNodeId of depGraph.getNodeDepsNodeIds(nodeId)) { const parentNode = nodesMap[nodeId] || nodeId; const childNode = nodesMap[depNodeId] || depNodeId; builder.connectDep(parentNode, childNode); } } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } return builder.build(); } /** * @deprecated Don't use dep trees. You should adapt your code to use graphs, * and enhance the dep-graph library if there is missing functionality from * the graph structure */ async function graphToDepTree(depGraphInterface, pkgType, opts = { deduplicateWithinTopLevelDeps: false }) { const depGraph = depGraphInterface; const [depTree] = await buildSubtree(depGraph, depGraph.rootNodeId, opts.deduplicateWithinTopLevelDeps ? null : false); depTree.type = depGraph.pkgManager.name; depTree.packageFormatVersion = constructPackageFormatVersion(pkgType); const targetOS = constructTargetOS(depGraph); if (targetOS) { depTree.targetOS = targetOS; } return depTree; } exports.graphToDepTree = graphToDepTree; function constructPackageFormatVersion(pkgType) { if (pkgType === 'maven') { pkgType = 'mvn'; } return `${pkgType}:0.0.1`; } function constructTargetOS(depGraph) { if (['apk', 'apt', 'deb', 'rpm', 'linux'].indexOf(depGraph.pkgManager.name) === -1) { // .targetOS is undefined unless its a linux pkgManager return; } if (!depGraph.pkgManager.repositories || !depGraph.pkgManager.repositories.length || !depGraph.pkgManager.repositories[0].alias) { throw new Error('Incomplete .pkgManager, could not create .targetOS'); } const [name, version] = depGraph.pkgManager.repositories[0].alias.split(':'); return { name, version }; } async function buildSubtree(depGraph, nodeId, maybeDeduplicationSet = false, // false = disabled; null = not in deduplication scope yet ancestors = [], memoizationMap = new Map()) { if (!maybeDeduplicationSet) { const memoizedDepTree = (0, memiozation_1.getMemoizedDepTree)(nodeId, ancestors, memoizationMap); if (memoizedDepTree) { return [memoizedDepTree, undefined]; } } const isRoot = nodeId === depGraph.rootNodeId; const nodePkg = depGraph.getNodePkg(nodeId); const nodeInfo = depGraph.getNode(nodeId); const depTree = {}; depTree.name = nodePkg.name; depTree.version = nodePkg.version; if (nodeInfo.versionProvenance) { depTree.versionProvenance = nodeInfo.versionProvenance; } if (nodeInfo.labels) { depTree.labels = { ...nodeInfo.labels }; } const depInstanceIds = depGraph.getNodeDepsNodeIds(nodeId); if (!depInstanceIds || depInstanceIds.length === 0) { memoizationMap.set(nodeId, { depTree }); return [depTree, undefined]; } const cycle = (0, cycles_1.getCycle)(ancestors, nodeId); if (cycle) { // This node starts a cycle and now it's the second visit. addLabel(depTree, 'pruned', 'cyclic'); return [depTree, [cycle]]; } if (maybeDeduplicationSet) { if (maybeDeduplicationSet.has(nodeId)) { if (depInstanceIds.length > 0) { addLabel(depTree, 'pruned', 'true'); } return [depTree, undefined]; } maybeDeduplicationSet.add(nodeId); } const cycles = []; for (const depInstId of depInstanceIds) { // Deduplication of nodes occurs only within a scope of a top-level dependency. // Therefore, every top-level dep gets an independent set to track duplicates. if (isRoot && maybeDeduplicationSet !== false) { maybeDeduplicationSet = new Set(); } const [subtree, subtreeCycles] = await buildSubtree(depGraph, depInstId, maybeDeduplicationSet, ancestors.concat(nodeId), memoizationMap); if (subtreeCycles) { for (const cycle of subtreeCycles) { cycles.push(cycle); } } if (!subtree) { continue; } if (!depTree.dependencies) { depTree.dependencies = {}; } depTree.dependencies[subtree.name] = subtree; } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } const partitionedCycles = (0, cycles_1.partitionCycles)(nodeId, cycles); (0, memiozation_1.memoize)(nodeId, memoizationMap, depTree, partitionedCycles); return [depTree, partitionedCycles.cyclesWithThisNode]; } function trimAfterLastSep(str, sep) { return str.slice(0, str.lastIndexOf(sep)); } //# sourceMappingURL=index.js.map /***/ }), /***/ 98155: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getMemoizedDepTree = exports.memoize = void 0; function memoize(nodeId, memoizationMap, depTree, partitionedCycles) { const { cyclesStartWithThisNode, cyclesWithThisNode } = partitionedCycles; if (cyclesStartWithThisNode.length > 0) { const cycleNodeIds = new Set(...cyclesStartWithThisNode); memoizationMap.set(nodeId, { depTree, cycleNodeIds }); } else if (cyclesWithThisNode.length === 0) { memoizationMap.set(nodeId, { depTree }); } // Don't memoize nodes in cycles (cyclesWithThisNode.length > 0) } exports.memoize = memoize; function getMemoizedDepTree(nodeId, ancestors, memoizationMap) { if (!memoizationMap.has(nodeId)) return null; const { depTree, cycleNodeIds } = memoizationMap.get(nodeId); if (!cycleNodeIds) return depTree; const ancestorsArePartOfTheCycle = ancestors.some((nodeId) => cycleNodeIds.has(nodeId)); return ancestorsArePartOfTheCycle ? null : depTree; } exports.getMemoizedDepTree = getMemoizedDepTree; //# sourceMappingURL=memiozation.js.map /***/ }), /***/ 75616: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // A linked list to keep track of recently-used-ness const Yallist = __webpack_require__(74918) const MAX = Symbol('max') const LENGTH = Symbol('length') const LENGTH_CALCULATOR = Symbol('lengthCalculator') const ALLOW_STALE = Symbol('allowStale') const MAX_AGE = Symbol('maxAge') const DISPOSE = Symbol('dispose') const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') const LRU_LIST = Symbol('lruList') const CACHE = Symbol('cache') const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') const naiveLength = () => 1 // lruList is a yallist where the head is the youngest // item, and the tail is the oldest. the list contains the Hit // objects as the entries. // Each Hit object has a reference to its Yallist.Node. This // never changes. // // cache is a Map (or PseudoMap) that matches the keys to // the Yallist.Node object. class LRUCache { constructor (options) { if (typeof options === 'number') options = { max: options } if (!options) options = {} if (options.max && (typeof options.max !== 'number' || options.max < 0)) throw new TypeError('max must be a non-negative number') // Kind of weird to have a default max of Infinity, but oh well. const max = this[MAX] = options.max || Infinity const lc = options.length || naiveLength this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc this[ALLOW_STALE] = options.stale || false if (options.maxAge && typeof options.maxAge !== 'number') throw new TypeError('maxAge must be a number') this[MAX_AGE] = options.maxAge || 0 this[DISPOSE] = options.dispose this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false this.reset() } // resize the cache when the max changes. set max (mL) { if (typeof mL !== 'number' || mL < 0) throw new TypeError('max must be a non-negative number') this[MAX] = mL || Infinity trim(this) } get max () { return this[MAX] } set allowStale (allowStale) { this[ALLOW_STALE] = !!allowStale } get allowStale () { return this[ALLOW_STALE] } set maxAge (mA) { if (typeof mA !== 'number') throw new TypeError('maxAge must be a non-negative number') this[MAX_AGE] = mA trim(this) } get maxAge () { return this[MAX_AGE] } // resize the cache when the lengthCalculator changes. set lengthCalculator (lC) { if (typeof lC !== 'function') lC = naiveLength if (lC !== this[LENGTH_CALCULATOR]) { this[LENGTH_CALCULATOR] = lC this[LENGTH] = 0 this[LRU_LIST].forEach(hit => { hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) this[LENGTH] += hit.length }) } trim(this) } get lengthCalculator () { return this[LENGTH_CALCULATOR] } get length () { return this[LENGTH] } get itemCount () { return this[LRU_LIST].length } rforEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].tail; walker !== null;) { const prev = walker.prev forEachStep(this, fn, walker, thisp) walker = prev } } forEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].head; walker !== null;) { const next = walker.next forEachStep(this, fn, walker, thisp) walker = next } } keys () { return this[LRU_LIST].toArray().map(k => k.key) } values () { return this[LRU_LIST].toArray().map(k => k.value) } reset () { if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) { this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) } this[CACHE] = new Map() // hash of items by key this[LRU_LIST] = new Yallist() // list of items in order of use recency this[LENGTH] = 0 // length of items in the list } dump () { return this[LRU_LIST].map(hit => isStale(this, hit) ? false : { k: hit.key, v: hit.value, e: hit.now + (hit.maxAge || 0) }).toArray().filter(h => h) } dumpLru () { return this[LRU_LIST] } set (key, value, maxAge) { maxAge = maxAge || this[MAX_AGE] if (maxAge && typeof maxAge !== 'number') throw new TypeError('maxAge must be a number') const now = maxAge ? Date.now() : 0 const len = this[LENGTH_CALCULATOR](value, key) if (this[CACHE].has(key)) { if (len > this[MAX]) { del(this, this[CACHE].get(key)) return false } const node = this[CACHE].get(key) const item = node.value // dispose of the old one before overwriting // split out into 2 ifs for better coverage tracking if (this[DISPOSE]) { if (!this[NO_DISPOSE_ON_SET]) this[DISPOSE](key, item.value) } item.now = now item.maxAge = maxAge item.value = value this[LENGTH] += len - item.length item.length = len this.get(key) trim(this) return true } const hit = new Entry(key, value, len, now, maxAge) // oversized objects fall out of cache automatically. if (hit.length > this[MAX]) { if (this[DISPOSE]) this[DISPOSE](key, value) return false } this[LENGTH] += hit.length this[LRU_LIST].unshift(hit) this[CACHE].set(key, this[LRU_LIST].head) trim(this) return true } has (key) { if (!this[CACHE].has(key)) return false const hit = this[CACHE].get(key).value return !isStale(this, hit) } get (key) { return get(this, key, true) } peek (key) { return get(this, key, false) } pop () { const node = this[LRU_LIST].tail if (!node) return null del(this, node) return node.value } del (key) { del(this, this[CACHE].get(key)) } load (arr) { // reset the cache this.reset() const now = Date.now() // A previous serialized cache has the most recent items first for (let l = arr.length - 1; l >= 0; l--) { const hit = arr[l] const expiresAt = hit.e || 0 if (expiresAt === 0) // the item was created without expiration in a non aged cache this.set(hit.k, hit.v) else { const maxAge = expiresAt - now // dont add already expired items if (maxAge > 0) { this.set(hit.k, hit.v, maxAge) } } } } prune () { this[CACHE].forEach((value, key) => get(this, key, false)) } } const get = (self, key, doUse) => { const node = self[CACHE].get(key) if (node) { const hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) return undefined } else { if (doUse) { if (self[UPDATE_AGE_ON_GET]) node.value.now = Date.now() self[LRU_LIST].unshiftNode(node) } } return hit.value } } const isStale = (self, hit) => { if (!hit || (!hit.maxAge && !self[MAX_AGE])) return false const diff = Date.now() - hit.now return hit.maxAge ? diff > hit.maxAge : self[MAX_AGE] && (diff > self[MAX_AGE]) } const trim = self => { if (self[LENGTH] > self[MAX]) { for (let walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) { // We know that we're about to delete this one, and also // what the next least recently used key will be, so just // go ahead and set it now. const prev = walker.prev del(self, walker) walker = prev } } } const del = (self, node) => { if (node) { const hit = node.value if (self[DISPOSE]) self[DISPOSE](hit.key, hit.value) self[LENGTH] -= hit.length self[CACHE].delete(hit.key) self[LRU_LIST].removeNode(node) } } class Entry { constructor (key, value, length, now, maxAge) { this.key = key this.value = value this.length = length this.now = now this.maxAge = maxAge || 0 } } const forEachStep = (self, fn, node, thisp) => { let hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) hit = undefined } if (hit) fn.call(thisp, hit.value, hit.key, self) } module.exports = LRUCache /***/ }), /***/ 95622: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const ANY = Symbol('SemVer ANY') // hoisted class for cyclic dependency class Comparator { static get ANY () { return ANY } constructor (comp, options) { options = parseOptions(options) if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } comp = comp.trim().split(/\s+/).join(' ') debug('comparator', comp, options) this.options = options this.loose = !!options.loose this.parse(comp) if (this.semver === ANY) { this.value = '' } else { this.value = this.operator + this.semver.version } debug('comp', this) } parse (comp) { const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] const m = comp.match(r) if (!m) { throw new TypeError(`Invalid comparator: ${comp}`) } this.operator = m[1] !== undefined ? m[1] : '' if (this.operator === '=') { this.operator = '' } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY } else { this.semver = new SemVer(m[2], this.options.loose) } } toString () { return this.value } test (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY || version === ANY) { return true } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } return cmp(version, this.operator, this.semver, this.options) } intersects (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (this.operator === '') { if (this.value === '') { return true } return new Range(comp.value, options).test(this.value) } else if (comp.operator === '') { if (comp.value === '') { return true } return new Range(this.value, options).test(comp.semver) } options = parseOptions(options) // Special cases where nothing can possibly be lower if (options.includePrerelease && (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { return false } if (!options.includePrerelease && (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { return false } // Same direction increasing (> or >=) if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { return true } // Same direction decreasing (< or <=) if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { return true } // same SemVer and both sides are inclusive (<= or >=) if ( (this.semver.version === comp.semver.version) && this.operator.includes('=') && comp.operator.includes('=')) { return true } // opposite directions less than if (cmp(this.semver, '<', comp.semver, options) && this.operator.startsWith('>') && comp.operator.startsWith('<')) { return true } // opposite directions greater than if (cmp(this.semver, '>', comp.semver, options) && this.operator.startsWith('<') && comp.operator.startsWith('>')) { return true } return false } } module.exports = Comparator const parseOptions = __webpack_require__(23856) const { safeRe: re, t } = __webpack_require__(90996) const cmp = __webpack_require__(35637) const debug = __webpack_require__(75236) const SemVer = __webpack_require__(81538) const Range = __webpack_require__(3577) /***/ }), /***/ 3577: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // hoisted class for cyclic dependency class Range { constructor (range, options) { options = parseOptions(options) if (range instanceof Range) { if ( range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease ) { return range } else { return new Range(range.raw, options) } } if (range instanceof Comparator) { // just put it in the set and return this.raw = range.value this.set = [[range]] this.format() return this } this.options = options this.loose = !!options.loose this.includePrerelease = !!options.includePrerelease // First reduce all whitespace as much as possible so we do not have to rely // on potentially slow regexes like \s*. This is then stored and used for // future error messages as well. this.raw = range .trim() .split(/\s+/) .join(' ') // First, split on || this.set = this.raw .split('||') // map the range to a 2d array of comparators .map(r => this.parseRange(r.trim())) // throw out any comparator lists that are empty // this generally means that it was not a valid range, which is allowed // in loose mode, but will still throw if the WHOLE range is invalid. .filter(c => c.length) if (!this.set.length) { throw new TypeError(`Invalid SemVer Range: ${this.raw}`) } // if we have any that are not the null set, throw out null sets. if (this.set.length > 1) { // keep the first one, in case they're all null sets const first = this.set[0] this.set = this.set.filter(c => !isNullSet(c[0])) if (this.set.length === 0) { this.set = [first] } else if (this.set.length > 1) { // if we have any that are *, then the range is just * for (const c of this.set) { if (c.length === 1 && isAny(c[0])) { this.set = [c] break } } } } this.format() } format () { this.range = this.set .map((comps) => comps.join(' ').trim()) .join('||') .trim() return this.range } toString () { return this.range } parseRange (range) { // memoize range parsing for performance. // this is a very hot path, and fully deterministic. const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE) const memoKey = memoOpts + ':' + range const cached = cache.get(memoKey) if (cached) { return cached } const loose = this.options.loose // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range) // `~ 1.2.3` => `~1.2.3` range = range.replace(re[t.TILDETRIM], tildeTrimReplace) debug('tilde trim', range) // `^ 1.2.3` => `^1.2.3` range = range.replace(re[t.CARETTRIM], caretTrimReplace) debug('caret trim', range) // At this point, the range is completely trimmed and // ready to be split into comparators. let rangeList = range .split(' ') .map(comp => parseComparator(comp, this.options)) .join(' ') .split(/\s+/) // >=0.0.0 is equivalent to * .map(comp => replaceGTE0(comp, this.options)) if (loose) { // in loose mode, throw out any that are not valid comparators rangeList = rangeList.filter(comp => { debug('loose invalid filter', comp, this.options) return !!comp.match(re[t.COMPARATORLOOSE]) }) } debug('range list', rangeList) // if any comparators are the null set, then replace with JUST null set // if more than one comparator, remove any * comparators // also, don't include the same comparator more than once const rangeMap = new Map() const comparators = rangeList.map(comp => new Comparator(comp, this.options)) for (const comp of comparators) { if (isNullSet(comp)) { return [comp] } rangeMap.set(comp.value, comp) } if (rangeMap.size > 1 && rangeMap.has('')) { rangeMap.delete('') } const result = [...rangeMap.values()] cache.set(memoKey, result) return result } intersects (range, options) { if (!(range instanceof Range)) { throw new TypeError('a Range is required') } return this.set.some((thisComparators) => { return ( isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => { return ( isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { return rangeComparators.every((rangeComparator) => { return thisComparator.intersects(rangeComparator, options) }) }) ) }) ) }) } // if ANY of the sets match ALL of its comparators, then pass test (version) { if (!version) { return false } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } for (let i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true } } return false } } module.exports = Range const LRU = __webpack_require__(75616) const cache = new LRU({ max: 1000 }) const parseOptions = __webpack_require__(23856) const Comparator = __webpack_require__(95622) const debug = __webpack_require__(75236) const SemVer = __webpack_require__(81538) const { safeRe: re, t, comparatorTrimReplace, tildeTrimReplace, caretTrimReplace, } = __webpack_require__(90996) const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __webpack_require__(14031) const isNullSet = c => c.value === '<0.0.0-0' const isAny = c => c.value === '' // take a set of comparators and determine whether there // exists a version which can satisfy it const isSatisfiable = (comparators, options) => { let result = true const remainingComparators = comparators.slice() let testComparator = remainingComparators.pop() while (result && remainingComparators.length) { result = remainingComparators.every((otherComparator) => { return testComparator.intersects(otherComparator, options) }) testComparator = remainingComparators.pop() } return result } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. const parseComparator = (comp, options) => { debug('comp', comp, options) comp = replaceCarets(comp, options) debug('caret', comp) comp = replaceTildes(comp, options) debug('tildes', comp) comp = replaceXRanges(comp, options) debug('xrange', comp) comp = replaceStars(comp, options) debug('stars', comp) return comp } const isX = id => !id || id.toLowerCase() === 'x' || id === '*' // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 // ~0.0.1 --> >=0.0.1 <0.1.0-0 const replaceTildes = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceTilde(c, options)) .join(' ') } const replaceTilde = (comp, options) => { const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] return comp.replace(r, (_, M, m, p, pr) => { debug('tilde', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0 <${+M + 1}.0.0-0` } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0-0 ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` } else if (pr) { debug('replaceTilde pr', pr) ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } else { // ~1.2.3 == >=1.2.3 <1.3.0-0 ret = `>=${M}.${m}.${p } <${M}.${+m + 1}.0-0` } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 // ^1.2.3 --> >=1.2.3 <2.0.0-0 // ^1.2.0 --> >=1.2.0 <2.0.0-0 // ^0.0.1 --> >=0.0.1 <0.0.2-0 // ^0.1.0 --> >=0.1.0 <0.2.0-0 const replaceCarets = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceCaret(c, options)) .join(' ') } const replaceCaret = (comp, options) => { debug('caret', comp, options) const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] const z = options.includePrerelease ? '-0' : '' return comp.replace(r, (_, M, m, p, pr) => { debug('caret', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` } else if (isX(p)) { if (M === '0') { ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` } else { ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p}-${pr } <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p}-${pr } <${+M + 1}.0.0-0` } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p }${z} <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p }${z} <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p } <${+M + 1}.0.0-0` } } debug('caret return', ret) return ret }) } const replaceXRanges = (comp, options) => { debug('replaceXRanges', comp, options) return comp .split(/\s+/) .map((c) => replaceXRange(c, options)) .join(' ') } const replaceXRange = (comp, options) => { comp = comp.trim() const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] return comp.replace(r, (ret, gtlt, M, m, p, pr) => { debug('xRange', comp, ret, gtlt, M, m, p, pr) const xM = isX(M) const xm = xM || isX(m) const xp = xm || isX(p) const anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } // if we're including prereleases in the match, then we need // to fix this to -0, the lowest possible prerelease value pr = options.includePrerelease ? '-0' : '' if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0-0' } else { // nothing is forbidden ret = '*' } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0 } p = 0 if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 gtlt = '>=' if (xm) { M = +M + 1 m = 0 p = 0 } else { m = +m + 1 p = 0 } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<' if (xm) { M = +M + 1 } else { m = +m + 1 } } if (gtlt === '<') { pr = '-0' } ret = `${gtlt + M}.${m}.${p}${pr}` } else if (xm) { ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` } else if (xp) { ret = `>=${M}.${m}.0${pr } <${M}.${+m + 1}.0-0` } debug('xRange return', ret) return ret }) } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. const replaceStars = (comp, options) => { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp .trim() .replace(re[t.STAR], '') } const replaceGTE0 = (comp, options) => { debug('replaceGTE0', comp, options) return comp .trim() .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') } // This function is passed to string.replace(re[t.HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 const hyphenReplace = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) => { if (isX(fM)) { from = '' } else if (isX(fm)) { from = `>=${fM}.0.0${incPr ? '-0' : ''}` } else if (isX(fp)) { from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` } else if (fpr) { from = `>=${from}` } else { from = `>=${from}${incPr ? '-0' : ''}` } if (isX(tM)) { to = '' } else if (isX(tm)) { to = `<${+tM + 1}.0.0-0` } else if (isX(tp)) { to = `<${tM}.${+tm + 1}.0-0` } else if (tpr) { to = `<=${tM}.${tm}.${tp}-${tpr}` } else if (incPr) { to = `<${tM}.${tm}.${+tp + 1}-0` } else { to = `<=${to}` } return `${from} ${to}`.trim() } const testSet = (set, version, options) => { for (let i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (let i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === Comparator.ANY) { continue } if (set[i].semver.prerelease.length > 0) { const allowed = set[i].semver if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } /***/ }), /***/ 81538: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const debug = __webpack_require__(75236) const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(14031) const { safeRe: re, t } = __webpack_require__(90996) const parseOptions = __webpack_require__(23856) const { compareIdentifiers } = __webpack_require__(6857) class SemVer { constructor (version, options) { options = parseOptions(options) if (version instanceof SemVer) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) } if (version.length > MAX_LENGTH) { throw new TypeError( `version is longer than ${MAX_LENGTH} characters` ) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose // this isn't actually relevant for versions, but keep it so that we // don't run into trouble passing this.options around. this.includePrerelease = !!options.includePrerelease const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) if (!m) { throw new TypeError(`Invalid Version: ${version}`) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map((id) => { if (/^[0-9]+$/.test(id)) { const num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } format () { this.version = `${this.major}.${this.minor}.${this.patch}` if (this.prerelease.length) { this.version += `-${this.prerelease.join('.')}` } return this.version } toString () { return this.version } compare (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { if (typeof other === 'string' && other === this.version) { return 0 } other = new SemVer(other, this.options) } if (other.version === this.version) { return 0 } return this.compareMain(other) || this.comparePre(other) } compareMain (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return ( compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) ) } comparePre (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } let i = 0 do { const a = this.prerelease[i] const b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } compareBuild (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } let i = 0 do { const a = this.build[i] const b = other.build[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc (release, identifier, identifierBase) { switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier, identifierBase) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier, identifierBase) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier, identifierBase) this.inc('pre', identifier, identifierBase) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier, identifierBase) } this.inc('pre', identifier, identifierBase) break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if ( this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0 ) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. case 'pre': { const base = Number(identifierBase) ? 1 : 0 if (!identifier && identifierBase === false) { throw new Error('invalid increment argument: identifier is empty') } if (this.prerelease.length === 0) { this.prerelease = [base] } else { let i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything if (identifier === this.prerelease.join('.') && identifierBase === false) { throw new Error('invalid increment argument: identifier already exists') } this.prerelease.push(base) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 let prerelease = [identifier, base] if (identifierBase === false) { prerelease = [identifier] } if (compareIdentifiers(this.prerelease[0], identifier) === 0) { if (isNaN(this.prerelease[1])) { this.prerelease = prerelease } } else { this.prerelease = prerelease } } break } default: throw new Error(`invalid increment argument: ${release}`) } this.raw = this.format() if (this.build.length) { this.raw += `+${this.build.join('.')}` } return this } } module.exports = SemVer /***/ }), /***/ 65105: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(83896) const clean = (version, options) => { const s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } module.exports = clean /***/ }), /***/ 35637: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const eq = __webpack_require__(28179) const neq = __webpack_require__(83568) const gt = __webpack_require__(78203) const gte = __webpack_require__(66658) const lt = __webpack_require__(1926) const lte = __webpack_require__(46266) const cmp = (a, op, b, loose) => { switch (op) { case '===': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a === b case '!==': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError(`Invalid operator: ${op}`) } } module.exports = cmp /***/ }), /***/ 12901: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(81538) const parse = __webpack_require__(83896) const { safeRe: re, t } = __webpack_require__(90996) const coerce = (version, options) => { if (version instanceof SemVer) { return version } if (typeof version === 'number') { version = String(version) } if (typeof version !== 'string') { return null } options = options || {} let match = null if (!options.rtl) { match = version.match(re[t.COERCE]) } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' // // Walk through the string checking with a /g regexp // Manually set the index so as to pick up overlapping matches. // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. let next while ((next = re[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next } re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length } // leave it in a clean state re[t.COERCERTL].lastIndex = -1 } if (match === null) { return null } return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) } module.exports = coerce /***/ }), /***/ 48372: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(81538) const compareBuild = (a, b, loose) => { const versionA = new SemVer(a, loose) const versionB = new SemVer(b, loose) return versionA.compare(versionB) || versionA.compareBuild(versionB) } module.exports = compareBuild /***/ }), /***/ 39309: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(62742) const compareLoose = (a, b) => compare(a, b, true) module.exports = compareLoose /***/ }), /***/ 62742: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(81538) const compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)) module.exports = compare /***/ }), /***/ 3976: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(83896) const diff = (version1, version2) => { const v1 = parse(version1, null, true) const v2 = parse(version2, null, true) const comparison = v1.compare(v2) if (comparison === 0) { return null } const v1Higher = comparison > 0 const highVersion = v1Higher ? v1 : v2 const lowVersion = v1Higher ? v2 : v1 const highHasPre = !!highVersion.prerelease.length const lowHasPre = !!lowVersion.prerelease.length if (lowHasPre && !highHasPre) { // Going from prerelease -> no prerelease requires some special casing // If the low version has only a major, then it will always be a major // Some examples: // 1.0.0-1 -> 1.0.0 // 1.0.0-1 -> 1.1.1 // 1.0.0-1 -> 2.0.0 if (!lowVersion.patch && !lowVersion.minor) { return 'major' } // Otherwise it can be determined by checking the high version if (highVersion.patch) { // anything higher than a patch bump would result in the wrong version return 'patch' } if (highVersion.minor) { // anything higher than a minor bump would result in the wrong version return 'minor' } // bumping major/minor/patch all have same result return 'major' } // add the `pre` prefix if we are going to a prerelease version const prefix = highHasPre ? 'pre' : '' if (v1.major !== v2.major) { return prefix + 'major' } if (v1.minor !== v2.minor) { return prefix + 'minor' } if (v1.patch !== v2.patch) { return prefix + 'patch' } // high and low are preleases return 'prerelease' } module.exports = diff /***/ }), /***/ 28179: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(62742) const eq = (a, b, loose) => compare(a, b, loose) === 0 module.exports = eq /***/ }), /***/ 78203: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(62742) const gt = (a, b, loose) => compare(a, b, loose) > 0 module.exports = gt /***/ }), /***/ 66658: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(62742) const gte = (a, b, loose) => compare(a, b, loose) >= 0 module.exports = gte /***/ }), /***/ 10948: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(81538) const inc = (version, release, options, identifier, identifierBase) => { if (typeof (options) === 'string') { identifierBase = identifier identifier = options options = undefined } try { return new SemVer( version instanceof SemVer ? version.version : version, options ).inc(release, identifier, identifierBase).version } catch (er) { return null } } module.exports = inc /***/ }), /***/ 1926: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(62742) const lt = (a, b, loose) => compare(a, b, loose) < 0 module.exports = lt /***/ }), /***/ 46266: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(62742) const lte = (a, b, loose) => compare(a, b, loose) <= 0 module.exports = lte /***/ }), /***/ 71188: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(81538) const major = (a, loose) => new SemVer(a, loose).major module.exports = major /***/ }), /***/ 90961: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(81538) const minor = (a, loose) => new SemVer(a, loose).minor module.exports = minor /***/ }), /***/ 83568: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(62742) const neq = (a, b, loose) => compare(a, b, loose) !== 0 module.exports = neq /***/ }), /***/ 83896: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(81538) const parse = (version, options, throwErrors = false) => { if (version instanceof SemVer) { return version } try { return new SemVer(version, options) } catch (er) { if (!throwErrors) { return null } throw er } } module.exports = parse /***/ }), /***/ 22793: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(81538) const patch = (a, loose) => new SemVer(a, loose).patch module.exports = patch /***/ }), /***/ 58258: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(83896) const prerelease = (version, options) => { const parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } module.exports = prerelease /***/ }), /***/ 78822: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(62742) const rcompare = (a, b, loose) => compare(b, a, loose) module.exports = rcompare /***/ }), /***/ 13668: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(48372) const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) module.exports = rsort /***/ }), /***/ 71344: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(3577) const satisfies = (version, range, options) => { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } module.exports = satisfies /***/ }), /***/ 71927: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(48372) const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) module.exports = sort /***/ }), /***/ 65202: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(83896) const valid = (version, options) => { const v = parse(version, options) return v ? v.version : null } module.exports = valid /***/ }), /***/ 21663: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // just pre-load all the stuff that index.js lazily exports const internalRe = __webpack_require__(90996) const constants = __webpack_require__(14031) const SemVer = __webpack_require__(81538) const identifiers = __webpack_require__(6857) const parse = __webpack_require__(83896) const valid = __webpack_require__(65202) const clean = __webpack_require__(65105) const inc = __webpack_require__(10948) const diff = __webpack_require__(3976) const major = __webpack_require__(71188) const minor = __webpack_require__(90961) const patch = __webpack_require__(22793) const prerelease = __webpack_require__(58258) const compare = __webpack_require__(62742) const rcompare = __webpack_require__(78822) const compareLoose = __webpack_require__(39309) const compareBuild = __webpack_require__(48372) const sort = __webpack_require__(71927) const rsort = __webpack_require__(13668) const gt = __webpack_require__(78203) const lt = __webpack_require__(1926) const eq = __webpack_require__(28179) const neq = __webpack_require__(83568) const gte = __webpack_require__(66658) const lte = __webpack_require__(46266) const cmp = __webpack_require__(35637) const coerce = __webpack_require__(12901) const Comparator = __webpack_require__(95622) const Range = __webpack_require__(3577) const satisfies = __webpack_require__(71344) const toComparators = __webpack_require__(56780) const maxSatisfying = __webpack_require__(44808) const minSatisfying = __webpack_require__(40776) const minVersion = __webpack_require__(78544) const validRange = __webpack_require__(37709) const outside = __webpack_require__(92054) const gtr = __webpack_require__(9891) const ltr = __webpack_require__(8100) const intersects = __webpack_require__(55128) const simplifyRange = __webpack_require__(2545) const subset = __webpack_require__(32675) module.exports = { parse, valid, clean, inc, diff, major, minor, patch, prerelease, compare, rcompare, compareLoose, compareBuild, sort, rsort, gt, lt, eq, neq, gte, lte, cmp, coerce, Comparator, Range, satisfies, toComparators, maxSatisfying, minSatisfying, minVersion, validRange, outside, gtr, ltr, intersects, simplifyRange, subset, SemVer, re: internalRe.re, src: internalRe.src, tokens: internalRe.t, SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, RELEASE_TYPES: constants.RELEASE_TYPES, compareIdentifiers: identifiers.compareIdentifiers, rcompareIdentifiers: identifiers.rcompareIdentifiers, } /***/ }), /***/ 14031: /***/ ((module) => { // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. const SEMVER_SPEC_VERSION = '2.0.0' const MAX_LENGTH = 256 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. const MAX_SAFE_COMPONENT_LENGTH = 16 // Max safe length for a build identifier. The max length minus 6 characters for // the shortest version with a build 0.0.0+BUILD. const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 const RELEASE_TYPES = [ 'major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease', ] module.exports = { MAX_LENGTH, MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_SAFE_INTEGER, RELEASE_TYPES, SEMVER_SPEC_VERSION, FLAG_INCLUDE_PRERELEASE: 0b001, FLAG_LOOSE: 0b010, } /***/ }), /***/ 75236: /***/ ((module) => { const debug = ( typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ) ? (...args) => console.error('SEMVER', ...args) : () => {} module.exports = debug /***/ }), /***/ 6857: /***/ ((module) => { const numeric = /^[0-9]+$/ const compareIdentifiers = (a, b) => { const anum = numeric.test(a) const bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) module.exports = { compareIdentifiers, rcompareIdentifiers, } /***/ }), /***/ 23856: /***/ ((module) => { // parse out just the options we care about const looseOption = Object.freeze({ loose: true }) const emptyOpts = Object.freeze({ }) const parseOptions = options => { if (!options) { return emptyOpts } if (typeof options !== 'object') { return looseOption } return options } module.exports = parseOptions /***/ }), /***/ 90996: /***/ ((module, exports, __webpack_require__) => { const { MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_LENGTH, } = __webpack_require__(14031) const debug = __webpack_require__(75236) exports = module.exports = {} // The actual regexps go on exports.re const re = exports.re = [] const safeRe = exports.safeRe = [] const src = exports.src = [] const t = exports.t = {} let R = 0 const LETTERDASHNUMBER = '[a-zA-Z0-9-]' // Replace some greedy regex tokens to prevent regex dos issues. These regex are // used internally via the safeRe object since all inputs in this library get // normalized first to trim and collapse all extra whitespace. The original // regexes are exported for userland consumption and lower level usage. A // future breaking change could export the safer regex only with a note that // all input should have extra whitespace removed. const safeRegexReplacements = [ ['\\s', 1], ['\\d', MAX_LENGTH], [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], ] const makeSafeRegex = (value) => { for (const [token, max] of safeRegexReplacements) { value = value .split(`${token}*`).join(`${token}{0,${max}}`) .split(`${token}+`).join(`${token}{1,${max}}`) } return value } const createToken = (name, value, isGlobal) => { const safe = makeSafeRegex(value) const index = R++ debug(name, index, value) t[name] = index src[index] = value re[index] = new RegExp(value, isGlobal ? 'g' : undefined) safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) } // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') createToken('NUMERICIDENTIFIERLOOSE', '\\d+') // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) // ## Main Version // Three dot-separated numeric identifiers. createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`) createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] }|${src[t.NONNUMERICIDENTIFIER]})`) createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] }|${src[t.NONNUMERICIDENTIFIER]})`) // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] }(?:\\.${src[t.BUILDIDENTIFIER]})*))`) // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. createToken('FULLPLAIN', `v?${src[t.MAINVERSION] }${src[t.PRERELEASE]}?${ src[t.BUILD]}?`) createToken('FULL', `^${src[t.FULLPLAIN]}$`) // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] }${src[t.PRERELEASELOOSE]}?${ src[t.BUILD]}?`) createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) createToken('GTLT', '((?:<|>)?=?)') // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) // Coercion. // Extract anything that could conceivably be a part of a valid semver createToken('COERCE', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:$|[^\\d])`) createToken('COERCERTL', src[t.COERCE], true) // Tilde ranges. // Meaning is "reasonably at or greater than" createToken('LONETILDE', '(?:~>?)') createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) exports.tildeTrimReplace = '$1~' createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) // Caret ranges. // Meaning is "at least and backwards compatible with" createToken('LONECARET', '(?:\\^)') createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) exports.caretTrimReplace = '$1^' createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) // A simple gt/lt/eq thing, or just "" to indicate "any version" createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) exports.comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`) createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`) // Star ranges basically just allow anything at all. createToken('STAR', '(<|>)?=?\\s*\\*') // >=0.0.0 is like a star createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') /***/ }), /***/ 9891: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Determine if version is greater than all the versions possible in the range. const outside = __webpack_require__(92054) const gtr = (version, range, options) => outside(version, range, '>', options) module.exports = gtr /***/ }), /***/ 55128: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(3577) const intersects = (r1, r2, options) => { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2, options) } module.exports = intersects /***/ }), /***/ 8100: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const outside = __webpack_require__(92054) // Determine if version is less than all the versions possible in the range const ltr = (version, range, options) => outside(version, range, '<', options) module.exports = ltr /***/ }), /***/ 44808: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(81538) const Range = __webpack_require__(3577) const maxSatisfying = (versions, range, options) => { let max = null let maxSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } module.exports = maxSatisfying /***/ }), /***/ 40776: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(81538) const Range = __webpack_require__(3577) const minSatisfying = (versions, range, options) => { let min = null let minSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } module.exports = minSatisfying /***/ }), /***/ 78544: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(81538) const Range = __webpack_require__(3577) const gt = __webpack_require__(78203) const minVersion = (range, loose) => { range = new Range(range, loose) let minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let setMin = null comparators.forEach((comparator) => { // Clone to avoid manipulating the comparator's semver object. const compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!setMin || gt(compver, setMin)) { setMin = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error(`Unexpected operation: ${comparator.operator}`) } }) if (setMin && (!minver || gt(minver, setMin))) { minver = setMin } } if (minver && range.test(minver)) { return minver } return null } module.exports = minVersion /***/ }), /***/ 92054: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(81538) const Comparator = __webpack_require__(95622) const { ANY } = Comparator const Range = __webpack_require__(3577) const satisfies = __webpack_require__(71344) const gt = __webpack_require__(78203) const lt = __webpack_require__(1926) const lte = __webpack_require__(46266) const gte = __webpack_require__(66658) const outside = (version, range, hilo, options) => { version = new SemVer(version, options) range = new Range(range, options) let gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisfies the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let high = null let low = null comparators.forEach((comparator) => { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } module.exports = outside /***/ }), /***/ 2545: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // given a set of versions and a range, create a "simplified" range // that includes the same versions that the original range does // If the original range is shorter than the simplified one, return that. const satisfies = __webpack_require__(71344) const compare = __webpack_require__(62742) module.exports = (versions, range, options) => { const set = [] let first = null let prev = null const v = versions.sort((a, b) => compare(a, b, options)) for (const version of v) { const included = satisfies(version, range, options) if (included) { prev = version if (!first) { first = version } } else { if (prev) { set.push([first, prev]) } prev = null first = null } } if (first) { set.push([first, null]) } const ranges = [] for (const [min, max] of set) { if (min === max) { ranges.push(min) } else if (!max && min === v[0]) { ranges.push('*') } else if (!max) { ranges.push(`>=${min}`) } else if (min === v[0]) { ranges.push(`<=${max}`) } else { ranges.push(`${min} - ${max}`) } } const simplified = ranges.join(' || ') const original = typeof range.raw === 'string' ? range.raw : String(range) return simplified.length < original.length ? simplified : range } /***/ }), /***/ 32675: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(3577) const Comparator = __webpack_require__(95622) const { ANY } = Comparator const satisfies = __webpack_require__(71344) const compare = __webpack_require__(62742) // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: // - Every simple range `r1, r2, ...` is a null set, OR // - Every simple range `r1, r2, ...` which is not a null set is a subset of // some `R1, R2, ...` // // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: // - If c is only the ANY comparator // - If C is only the ANY comparator, return true // - Else if in prerelease mode, return false // - else replace c with `[>=0.0.0]` // - If C is only the ANY comparator // - if in prerelease mode, return true // - else replace C with `[>=0.0.0]` // - Let EQ be the set of = comparators in c // - If EQ is more than one, return true (null set) // - Let GT be the highest > or >= comparator in c // - Let LT be the lowest < or <= comparator in c // - If GT and LT, and GT.semver > LT.semver, return true (null set) // - If any C is a = range, and GT or LT are set, return false // - If EQ // - If GT, and EQ does not satisfy GT, return true (null set) // - If LT, and EQ does not satisfy LT, return true (null set) // - If EQ satisfies every C, return true // - Else return false // - If GT // - If GT.semver is lower than any > or >= comp in C, return false // - If GT is >=, and GT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the GT.semver tuple, return false // - If LT // - If LT.semver is greater than any < or <= comp in C, return false // - If LT is <=, and LT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the LT.semver tuple, return false // - Else return true const subset = (sub, dom, options = {}) => { if (sub === dom) { return true } sub = new Range(sub, options) dom = new Range(dom, options) let sawNonNull = false OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { const isSub = simpleSubset(simpleSub, simpleDom, options) sawNonNull = sawNonNull || isSub !== null if (isSub) { continue OUTER } } // the null set is a subset of everything, but null simple ranges in // a complex range should be ignored. so if we saw a non-null range, // then we know this isn't a subset, but if EVERY simple range was null, // then it is a subset. if (sawNonNull) { return false } } return true } const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] const minimumVersion = [new Comparator('>=0.0.0')] const simpleSubset = (sub, dom, options) => { if (sub === dom) { return true } if (sub.length === 1 && sub[0].semver === ANY) { if (dom.length === 1 && dom[0].semver === ANY) { return true } else if (options.includePrerelease) { sub = minimumVersionWithPreRelease } else { sub = minimumVersion } } if (dom.length === 1 && dom[0].semver === ANY) { if (options.includePrerelease) { return true } else { dom = minimumVersion } } const eqSet = new Set() let gt, lt for (const c of sub) { if (c.operator === '>' || c.operator === '>=') { gt = higherGT(gt, c, options) } else if (c.operator === '<' || c.operator === '<=') { lt = lowerLT(lt, c, options) } else { eqSet.add(c.semver) } } if (eqSet.size > 1) { return null } let gtltComp if (gt && lt) { gtltComp = compare(gt.semver, lt.semver, options) if (gtltComp > 0) { return null } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { return null } } // will iterate one or zero times for (const eq of eqSet) { if (gt && !satisfies(eq, String(gt), options)) { return null } if (lt && !satisfies(eq, String(lt), options)) { return null } for (const c of dom) { if (!satisfies(eq, String(c), options)) { return false } } return true } let higher, lower let hasDomLT, hasDomGT // if the subset has a prerelease, we need a comparator in the superset // with the same tuple and a prerelease, or it's not a subset let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false // exception: <1.2.3-0 is the same as <1.2.3 if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { needDomLTPre = false } for (const c of dom) { hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' if (gt) { if (needDomGTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { needDomGTPre = false } } if (c.operator === '>' || c.operator === '>=') { higher = higherGT(gt, c, options) if (higher === c && higher !== gt) { return false } } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { return false } } if (lt) { if (needDomLTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { needDomLTPre = false } } if (c.operator === '<' || c.operator === '<=') { lower = lowerLT(lt, c, options) if (lower === c && lower !== lt) { return false } } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { return false } } if (!c.operator && (lt || gt) && gtltComp !== 0) { return false } } // if there was a < or >, and nothing in the dom, then must be false // UNLESS it was limited by another range in the other direction. // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 if (gt && hasDomLT && !lt && gtltComp !== 0) { return false } if (lt && hasDomGT && !gt && gtltComp !== 0) { return false } // we needed a prerelease range in a specific tuple, but didn't get one // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, // because it includes prereleases in the 1.2.3 tuple if (needDomGTPre || needDomLTPre) { return false } return true } // >=1.2.3 is lower than >1.2.3 const higherGT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp > 0 ? a : comp < 0 ? b : b.operator === '>' && a.operator === '>=' ? b : a } // <=1.2.3 is higher than <1.2.3 const lowerLT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp < 0 ? a : comp > 0 ? b : b.operator === '<' && a.operator === '<=' ? b : a } module.exports = subset /***/ }), /***/ 56780: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(3577) // Mostly just for testing and legacy API reasons const toComparators = (range, options) => new Range(range, options).set .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) module.exports = toComparators /***/ }), /***/ 37709: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(3577) const validRange = (range, options) => { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } module.exports = validRange /***/ }), /***/ 44137: /***/ ((module) => { "use strict"; module.exports = function (Yallist) { Yallist.prototype[Symbol.iterator] = function* () { for (let walker = this.head; walker; walker = walker.next) { yield walker.value } } } /***/ }), /***/ 74918: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = Yallist Yallist.Node = Node Yallist.create = Yallist function Yallist (list) { var self = this if (!(self instanceof Yallist)) { self = new Yallist() } self.tail = null self.head = null self.length = 0 if (list && typeof list.forEach === 'function') { list.forEach(function (item) { self.push(item) }) } else if (arguments.length > 0) { for (var i = 0, l = arguments.length; i < l; i++) { self.push(arguments[i]) } } return self } Yallist.prototype.removeNode = function (node) { if (node.list !== this) { throw new Error('removing node which does not belong to this list') } var next = node.next var prev = node.prev if (next) { next.prev = prev } if (prev) { prev.next = next } if (node === this.head) { this.head = next } if (node === this.tail) { this.tail = prev } node.list.length-- node.next = null node.prev = null node.list = null return next } Yallist.prototype.unshiftNode = function (node) { if (node === this.head) { return } if (node.list) { node.list.removeNode(node) } var head = this.head node.list = this node.next = head if (head) { head.prev = node } this.head = node if (!this.tail) { this.tail = node } this.length++ } Yallist.prototype.pushNode = function (node) { if (node === this.tail) { return } if (node.list) { node.list.removeNode(node) } var tail = this.tail node.list = this node.prev = tail if (tail) { tail.next = node } this.tail = node if (!this.head) { this.head = node } this.length++ } Yallist.prototype.push = function () { for (var i = 0, l = arguments.length; i < l; i++) { push(this, arguments[i]) } return this.length } Yallist.prototype.unshift = function () { for (var i = 0, l = arguments.length; i < l; i++) { unshift(this, arguments[i]) } return this.length } Yallist.prototype.pop = function () { if (!this.tail) { return undefined } var res = this.tail.value this.tail = this.tail.prev if (this.tail) { this.tail.next = null } else { this.head = null } this.length-- return res } Yallist.prototype.shift = function () { if (!this.head) { return undefined } var res = this.head.value this.head = this.head.next if (this.head) { this.head.prev = null } else { this.tail = null } this.length-- return res } Yallist.prototype.forEach = function (fn, thisp) { thisp = thisp || this for (var walker = this.head, i = 0; walker !== null; i++) { fn.call(thisp, walker.value, i, this) walker = walker.next } } Yallist.prototype.forEachReverse = function (fn, thisp) { thisp = thisp || this for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { fn.call(thisp, walker.value, i, this) walker = walker.prev } } Yallist.prototype.get = function (n) { for (var i = 0, walker = this.head; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.next } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.getReverse = function (n) { for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.prev } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.map = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.head; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.next } return res } Yallist.prototype.mapReverse = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.tail; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.prev } return res } Yallist.prototype.reduce = function (fn, initial) { var acc var walker = this.head if (arguments.length > 1) { acc = initial } else if (this.head) { walker = this.head.next acc = this.head.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = 0; walker !== null; i++) { acc = fn(acc, walker.value, i) walker = walker.next } return acc } Yallist.prototype.reduceReverse = function (fn, initial) { var acc var walker = this.tail if (arguments.length > 1) { acc = initial } else if (this.tail) { walker = this.tail.prev acc = this.tail.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = this.length - 1; walker !== null; i--) { acc = fn(acc, walker.value, i) walker = walker.prev } return acc } Yallist.prototype.toArray = function () { var arr = new Array(this.length) for (var i = 0, walker = this.head; walker !== null; i++) { arr[i] = walker.value walker = walker.next } return arr } Yallist.prototype.toArrayReverse = function () { var arr = new Array(this.length) for (var i = 0, walker = this.tail; walker !== null; i++) { arr[i] = walker.value walker = walker.prev } return arr } Yallist.prototype.slice = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = 0, walker = this.head; walker !== null && i < from; i++) { walker = walker.next } for (; walker !== null && i < to; i++, walker = walker.next) { ret.push(walker.value) } return ret } Yallist.prototype.sliceReverse = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { walker = walker.prev } for (; walker !== null && i > from; i--, walker = walker.prev) { ret.push(walker.value) } return ret } Yallist.prototype.splice = function (start, deleteCount, ...nodes) { if (start > this.length) { start = this.length - 1 } if (start < 0) { start = this.length + start; } for (var i = 0, walker = this.head; walker !== null && i < start; i++) { walker = walker.next } var ret = [] for (var i = 0; walker && i < deleteCount; i++) { ret.push(walker.value) walker = this.removeNode(walker) } if (walker === null) { walker = this.tail } if (walker !== this.head && walker !== this.tail) { walker = walker.prev } for (var i = 0; i < nodes.length; i++) { walker = insert(this, walker, nodes[i]) } return ret; } Yallist.prototype.reverse = function () { var head = this.head var tail = this.tail for (var walker = head; walker !== null; walker = walker.prev) { var p = walker.prev walker.prev = walker.next walker.next = p } this.head = tail this.tail = head return this } function insert (self, node, value) { var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self) if (inserted.next === null) { self.tail = inserted } if (inserted.prev === null) { self.head = inserted } self.length++ return inserted } function push (self, item) { self.tail = new Node(item, self.tail, null, self) if (!self.head) { self.head = self.tail } self.length++ } function unshift (self, item) { self.head = new Node(item, null, self.head, self) if (!self.tail) { self.tail = self.head } self.length++ } function Node (value, prev, next, list) { if (!(this instanceof Node)) { return new Node(value, prev, next, list) } this.list = list this.value = value if (prev) { prev.next = this this.prev = prev } else { this.prev = null } if (next) { next.prev = this this.next = next } else { this.next = null } } try { // add if support for Symbol.iterator is present __webpack_require__(44137)(Yallist) } catch (er) {} /***/ }), /***/ 87315: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.checkSupport = void 0; const contentTypes = __webpack_require__(42625); const registry_call_1 = __webpack_require__(15271); /** * Root V2 endpoint, useful to check V2 support and validating credentials. */ async function checkSupport(registryBase, username, password, options = {}, callChainObserver = { visitedUrls: [] }) { const result = await (0, registry_call_1.registryV2Call)(registryBase, "/", // full url path should be "/v2/" as per spec contentTypes.JSON, callChainObserver, username, password, options); // always return thruthy object, even for ECR return result || {}; } exports.checkSupport = checkSupport; //# sourceMappingURL=check-support.js.map /***/ }), /***/ 42625: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JSON = exports.LAYER = exports.IMAGE_CONFIG = exports.OCI_INDEX_V1 = exports.OCI_MANIFEST_V1 = exports.MANIFEST_LIST_V2 = exports.MANIFEST_V2 = void 0; exports.MANIFEST_V2 = "application/vnd.docker.distribution.manifest.v2+json"; exports.MANIFEST_LIST_V2 = "application/vnd.docker.distribution.manifest.list.v2+json"; exports.OCI_MANIFEST_V1 = "application/vnd.oci.image.manifest.v1+json"; exports.OCI_INDEX_V1 = "application/vnd.oci.image.index.v1+json"; exports.IMAGE_CONFIG = "application/vnd.docker.container.image.v1+json"; exports.LAYER = "application/vnd.docker.image.rootfs.diff.tar.gzip"; exports.JSON = "application/json"; //# sourceMappingURL=content-types.js.map /***/ }), /***/ 72614: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.downloadLayer = void 0; const registry_call_1 = __webpack_require__(15271); const contentTypes = __webpack_require__(42625); async function downloadLayer(output, registryBase, repo, digest, username, password, options = {}, callChainObserver = { visitedUrls: [] }) { var _a; const accept = `${(_a = options.acceptLayer) !== null && _a !== void 0 ? _a : contentTypes.LAYER}`; const endpoint = `/${repo}/blobs/${digest}`; options = Object.assign({ json: false, encoding: null, snykInternalOutputStream: output }, options); const layerResponse = await (0, registry_call_1.registryV2Call)(registryBase, endpoint, accept, callChainObserver, username, password, options); return layerResponse; } exports.downloadLayer = downloadLayer; //# sourceMappingURL=download-layer.js.map /***/ }), /***/ 80290: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getAuthTokenForEndpoint = void 0; const contentTypes = __webpack_require__(42625); const registry_call_1 = __webpack_require__(15271); const needle_1 = __webpack_require__(48360); /** * getAuthTokenForEndpoint attempts to retrieve a token for an unauthorized endpoint. * It will make a request to the endpoint and in case it returns an Unauthorized (401) * response code with the 'www-Authenticate' header, it will make a consecutive call according * to the details within this header. * More info: https://docs.docker.com/registry/spec/auth/token/#how-to-authenticate * @param registryBase - the container registry base URL * @param endpoint - the endpoint to which we would like to make the request * @param username - the username for authentication * @param password - the password for authentication * @param reqOptions - http request options * @returns an auth token string if authentication succeeded or null if * authorization is not required/not bases on bearer token * @throws an error if http error status code is not 401 */ async function getAuthTokenForEndpoint(registryBase, endpoint, username, password, reqOptions = {}) { const reqConfig = (0, registry_call_1.buildUnauthenticatedV2RequestConfig)(registryBase, endpoint, contentTypes.JSON, reqOptions); try { await (0, needle_1.needleWrapper)(reqConfig); return null; } catch (err) { if (err.statusCode !== 401) { throw err; } const challengeHeaders = err.headers["www-authenticate"]; if (!challengeHeaders) { return null; } const [authBase, service, scope] = (0, registry_call_1.parseChallengeHeaders)(challengeHeaders); if (!authBase) { return null; } else { // Bearer token const token = await (0, registry_call_1.getToken)(registryBase, authBase, service, scope, username, password, reqOptions); return token; } } } exports.getAuthTokenForEndpoint = getAuthTokenForEndpoint; //# sourceMappingURL=get-auth-token-for-endpoint.js.map /***/ }), /***/ 50702: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getImageConfig = void 0; const registry_call_1 = __webpack_require__(15271); const contentTypes = __webpack_require__(42625); const needle_1 = __webpack_require__(48360); async function getImageConfig(registryBase, repo, digest, username, password, options = {}, callChainObserver = { visitedUrls: [] }) { const endpoint = `/${repo}/blobs/${digest}`; const configResponse = await (0, registry_call_1.registryV2Call)(registryBase, endpoint, contentTypes.IMAGE_CONFIG, callChainObserver, username, password, options); return (0, needle_1.parseResponseBody)(configResponse); } exports.getImageConfig = getImageConfig; //# sourceMappingURL=get-image-config.js.map /***/ }), /***/ 70395: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getImageSize = void 0; const get_manifest_1 = __webpack_require__(32603); async function getImageSize(registryBase, repo, tag, username, password, options = {}, callChainObserver = { visitedUrls: [] }) { const manifest = await (0, get_manifest_1.getManifest)(registryBase, repo, tag, username, password, options, undefined, callChainObserver); const layers = manifest.layers || []; return layers.reduce((size, layerConfig) => size + layerConfig.size, 0); } exports.getImageSize = getImageSize; //# sourceMappingURL=get-image-size.js.map /***/ }), /***/ 78924: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getLayer = void 0; const registry_call_1 = __webpack_require__(15271); const contentTypes = __webpack_require__(42625); /** @deprecated use downloadLayer instead. */ async function getLayer(registryBase, repo, digest, username, password, options = {}, callChainObserver = { visitedUrls: [] }) { var _a; const accept = `${(_a = options.acceptLayer) !== null && _a !== void 0 ? _a : contentTypes.LAYER}`; const endpoint = `/${repo}/blobs/${digest}`; options = Object.assign({ json: false, encoding: null }, options); const layerResponse = await (0, registry_call_1.registryV2Call)(registryBase, endpoint, accept, callChainObserver, username, password, options); // When the content type is wrongly set to text instead of binary, response body is returned as string instead of a buffer // This forces a buffer response. if (!(layerResponse.body instanceof Buffer)) { return Buffer.from(layerResponse.raw); } return layerResponse.body; } exports.getLayer = getLayer; //# sourceMappingURL=get-layer.js.map /***/ }), /***/ 32603: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.computeDigest = exports.getManifest = void 0; const registry_call_1 = __webpack_require__(15271); const contentTypes = __webpack_require__(42625); const needle_1 = __webpack_require__(48360); const validation_1 = __webpack_require__(69519); const crypto_1 = __webpack_require__(6113); const digestRegex = /^sha256:[a-f0-9]{64}$/i; /** * A request to get image manifest by tag or digest * @param registryBase the hostname (and optionally base path) from which to get the manifest. * @param repo the requested image repository. * @param tag the manifest tag or digest value * @param username optional, username to be used for basic auth. * @param password optional, password to be used for basic auth. * @param options optional, request options. * @param platform optional, the manifest platform (os and architecture), applicable only for multi-architecture manifests. * Defaults to linux/amd64. In case the requested manifest platform is not found an error is thrown. * @returns */ async function getManifest(registryBase, repo, imageReference, username, password, options = {}, platform, callChainObserver = { visitedUrls: [] }) { var _a; const accept = (_a = options.acceptManifest) !== null && _a !== void 0 ? _a : `${contentTypes.MANIFEST_V2}, ${contentTypes.MANIFEST_LIST_V2}`; const endpoint = `/${repo}/manifests/${imageReference}`; try { (0, validation_1.validateRepoOrImageRef)(repo); (0, validation_1.validateRepoOrImageRef)(imageReference); } catch (err) { throw new needle_1.NeedleWrapperException(err.message, 400); } let manifestResponse = await (0, registry_call_1.registryV2Call)(registryBase, endpoint, accept, callChainObserver, username, password, options); const contentType = manifestResponse.headers["content-type"]; let indexDigest; let manifestDigest; if (contentType === contentTypes.MANIFEST_LIST_V2 || contentType === contentTypes.OCI_INDEX_V1) { indexDigest = computeDigest(manifestResponse.body); manifestDigest = getManifestDigestByPlatform(manifestResponse, platform); // need to call again with actual manifest (and not a list of manifest-lists) const endpoint = `/${repo}/manifests/${manifestDigest}`; manifestResponse = await (0, registry_call_1.registryV2Call)(registryBase, endpoint, accept, callChainObserver !== null && callChainObserver !== void 0 ? callChainObserver : { visitedUrls: [] }, username, password, options); } const dockerContentDigest = manifestResponse.headers["Docker-Content-Digest"]; switch (true) { case manifestDigest != undefined: break; case isManifestDigest(imageReference): manifestDigest = imageReference; break; case isManifestDigest(dockerContentDigest): manifestDigest = dockerContentDigest; break; default: manifestDigest = computeDigest(manifestResponse.body); } const manifestContentType = manifestResponse.headers["content-type"]; const parsedBody = (0, needle_1.parseResponseBody)(manifestResponse); return Object.assign(Object.assign({}, parsedBody), { indexDigest, manifestDigest, manifestContentType }); } exports.getManifest = getManifest; function isManifestDigest(imageReference) { return digestRegex.test(imageReference); } function computeDigest(body) { if (!body) { return undefined; } if (typeof body !== "string") { body = JSON.stringify(body); } const hexDigest = (0, crypto_1.createHash)("sha256") .update(body) .digest("hex") .toLowerCase(); return `sha256:${hexDigest}`; } exports.computeDigest = computeDigest; function getManifestDigestByPlatform(manifestResponse, platform) { const defaultPlatform = { os: "linux", architecture: "amd64", }; const platformFilter = platform ? platform : defaultPlatform; const manifestList = (0, needle_1.parseResponseBody)(manifestResponse); const manifestPlatform = getManifestByOsAndArch(manifestList.manifests, platformFilter.os, platformFilter.architecture, platformFilter.variant); if (manifestPlatform) { return manifestPlatform.digest; } throw new Error(`no supported manifest found for platform: ${JSON.stringify(platformFilter)}`); } function getManifestByOsAndArch(platformManifest, os, architecture, variant) { return platformManifest.find(manifest => { var _a, _b, _c; return ((_a = manifest.platform) === null || _a === void 0 ? void 0 : _a.os) === os && ((_b = manifest.platform) === null || _b === void 0 ? void 0 : _b.architecture) === architecture && ((_c = manifest.platform) === null || _c === void 0 ? void 0 : _c.variant) === variant; }); } //# sourceMappingURL=get-manifest.js.map /***/ }), /***/ 73905: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRepos = void 0; const contentTypes = __webpack_require__(42625); const registry_call_1 = __webpack_require__(15271); async function getRepos(registryBase, username, password, pageSize = 100, maxPages = Number.MAX_SAFE_INTEGER, options = {}, callChainObserver = { visitedUrls: [] }) { const endpoint = "/_catalog"; const result = await (0, registry_call_1.paginatedV2Call)(registryBase, contentTypes.JSON, username, password, endpoint, "repositories", pageSize, maxPages, options, callChainObserver); return result; } exports.getRepos = getRepos; //# sourceMappingURL=get-repos.js.map /***/ }), /***/ 80353: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getTags = void 0; const registry_call_1 = __webpack_require__(15271); const contentTypes = __webpack_require__(42625); async function getTags(registryBase, repo, username, password, pageSize = 1000, maxPages = Number.MAX_SAFE_INTEGER, options = {}, callChainObserver = { visitedUrls: [] }) { const endpoint = `/${repo}/tags/list`; return await (0, registry_call_1.paginatedV2Call)(registryBase, contentTypes.JSON, username, password, endpoint, "tags", pageSize, maxPages, options, callChainObserver); } exports.getTags = getTags; //# sourceMappingURL=get-tags.js.map /***/ }), /***/ 28310: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.contentTypes = exports.types = exports.validation = exports.registryCall = exports.getTags = exports.getRepos = exports.getManifest = exports.getLayer = exports.getImageSize = exports.getImageConfig = exports.getAuthTokenForEndpoint = exports.downloadLayer = exports.checkSupport = void 0; const check_support_1 = __webpack_require__(87315); Object.defineProperty(exports, "checkSupport", ({ enumerable: true, get: function () { return check_support_1.checkSupport; } })); const download_layer_1 = __webpack_require__(72614); Object.defineProperty(exports, "downloadLayer", ({ enumerable: true, get: function () { return download_layer_1.downloadLayer; } })); const get_auth_token_for_endpoint_1 = __webpack_require__(80290); Object.defineProperty(exports, "getAuthTokenForEndpoint", ({ enumerable: true, get: function () { return get_auth_token_for_endpoint_1.getAuthTokenForEndpoint; } })); const get_image_config_1 = __webpack_require__(50702); Object.defineProperty(exports, "getImageConfig", ({ enumerable: true, get: function () { return get_image_config_1.getImageConfig; } })); const get_image_size_1 = __webpack_require__(70395); Object.defineProperty(exports, "getImageSize", ({ enumerable: true, get: function () { return get_image_size_1.getImageSize; } })); const get_layer_1 = __webpack_require__(78924); Object.defineProperty(exports, "getLayer", ({ enumerable: true, get: function () { return get_layer_1.getLayer; } })); const get_manifest_1 = __webpack_require__(32603); Object.defineProperty(exports, "getManifest", ({ enumerable: true, get: function () { return get_manifest_1.getManifest; } })); const get_repos_1 = __webpack_require__(73905); Object.defineProperty(exports, "getRepos", ({ enumerable: true, get: function () { return get_repos_1.getRepos; } })); const get_tags_1 = __webpack_require__(80353); Object.defineProperty(exports, "getTags", ({ enumerable: true, get: function () { return get_tags_1.getTags; } })); const registry_call_1 = __webpack_require__(15271); Object.defineProperty(exports, "registryCall", ({ enumerable: true, get: function () { return registry_call_1.registryCall; } })); const validation = __webpack_require__(69519); exports.validation = validation; const types = __webpack_require__(47235); exports.types = types; const contentTypes = __webpack_require__(42625); exports.contentTypes = contentTypes; //# sourceMappingURL=index.js.map /***/ }), /***/ 48360: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.checkAllowedHosts = exports.NeedleWrapperException = exports.parseResponseBody = exports.needleWrapper = void 0; const fs = __webpack_require__(57147); const net = __webpack_require__(41808); const needle = __webpack_require__(64484); const stream_1 = __webpack_require__(12781); // TODO: this is a temporary code that allows setting needle default timeout (alias for // open_timeout) to check how it affects the stability of our system, and specifically // if it helps reducing 'socket hang up' errors. // More information: https://www.npmjs.com/package/needle if (process.env.DOCKER_REGISTRY_V2_CLIENT_NEEDLE_OPEN_TIMEOUT) { const openTimeout = parseInt(process.env.DOCKER_REGISTRY_V2_CLIENT_NEEDLE_OPEN_TIMEOUT); if (Number.isInteger(openTimeout)) { needle.defaults({ timeout: openTimeout, }); } } /** * A wrapper function that uses `needle` for making HTTP requests, * and returns a response that matches what the response it used to get from `request` library * @param options request options */ async function needleWrapper(options, maxRetries, callChainObserver = { visitedUrls: [] }) { var _a, _b; let uri = options.uri; const allowedHostResult = checkAllowedHosts(uri, { allowedHosts: options.allowedHosts, disallowDangerousHosts: options.disallowDangerousHosts, }); if (!allowedHostResult.allowed) { throw new Error(`Refusing to connect to disallowed host ${uri} with reason ${allowedHostResult.denyReason}`); } // append query parameters if (options.qs) { for (const key in options.qs) { if (options.qs[key] !== undefined) { uri += `&${key}=${options.qs[key]}`; } } if (!uri.includes("?")) { uri = uri.replace("&", "?"); } } callChainObserver.visitedUrls.push(uri); let response; let lastError; let retries = maxRetries !== null && maxRetries !== void 0 ? maxRetries : 0; while (!response && retries >= 0) { retries--; try { if (options.snykInternalOutputStream) { response = await stream(needle.get(uri, Object.assign(Object.assign({}, options), { // needle streams the response to file and memory as convenience if output is set. // causes high memory usage for large binaries. output: null, // we treat the response body as a binary stream parse_response: false })), fs.createWriteStream(options.snykInternalOutputStream)); } else { response = await needle("get", uri, options); } } catch (err) { lastError = err; } } if (!response) { throw lastError; } // throw an error in case status code is not 2xx if (response && response.statusCode >= 300) { let message; if (((_b = (_a = response.body) === null || _a === void 0 ? void 0 : _a.errors) === null || _b === void 0 ? void 0 : _b.length) > 0) { message = response.body.errors[0].message; } else { message = response.body; } if (typeof message !== "string") { try { message = JSON.stringify(message); // eslint-disable-next-line no-empty } catch (_) { } } throw new NeedleWrapperException(message, response.statusCode, response.headers); } return response; } exports.needleWrapper = needleWrapper; function parseResponseBody(response) { let body; try { body = JSON.parse(response.body); } catch (err) { body = response.body; } return body; } exports.parseResponseBody = parseResponseBody; class NeedleWrapperException extends Error { constructor(message, statusCode, headers) { super(message); this.statusCode = statusCode; this.headers = headers; } } exports.NeedleWrapperException = NeedleWrapperException; /** * Streams the readable stream to the writeable stream and returns the response * of the underlying http.ClientRequest. */ async function stream(readable, writeable) { return new Promise((resolve, reject) => { let response; // Emitted when the underlying http.ClientRequest emits a response event. // This is after the connection is established and the header received, but // before any of it is processed (e.g. authorization required or redirect // to be followed). No data has been consumed at this point. readable.on("response", inner => { response = inner; }); // Triggered after the header has been processed, and just before the data // is to be consumed. This implies that no redirect was followed and/or // authentication header was received. In other words, we got a "valid" // response. readable.on("header", (statusCode, headers) => { response.statusCode = statusCode; response.headers = headers; }); // Emitted when an error ocurrs. This should only happen once in the // lifecycle of a Needle request. readable.on("err", err => { reject(err); }); // Emitted when an timeout error occurs. Type can be either 'open', // 'response', or 'read'. This will called right before aborting the // request, which will also trigger an err event, a described above, with // an ECONNRESET (Socket hang up) exception. readable.on("timeout", type => { reject(new Error(type + " timeout")); }); (0, stream_1.pipeline)(readable, writeable, err => err ? reject(err) : resolve(response)); }); } function checkAllowedHosts(uri, options) { let host; try { host = new URL(uri).hostname; } catch (err) { throw new Error(`Failed to parse host from uri: ${uri}`); } if (options.allowedHosts && !options.allowedHosts.includes(host)) { return { allowed: false, denyReason: "host disallowed by allowed hosts filter", }; } if (options.disallowDangerousHosts) { // Disallow IPv4 addresses if (net.isIPv4(host)) { return { allowed: false, denyReason: "host disallowed by IPv4 address filter", }; } if (/^\[.*\]$/.test(host) && net.isIPv6(host.slice(1, -1))) { return { allowed: false, denyReason: "host disallowed by IPv6 address filter", }; } // Disallow hosts in the cluster.local subdomain if (/cluster\.local$/.test(host)) { return { allowed: false, denyReason: "host disallowed by cluster.local subdomains filter", }; } // Disallow hosts without a TLD+1 if (!host.includes(".")) { return { allowed: false, denyReason: "host disallowed by require TLD+1 filter", }; } } return { allowed: true }; } exports.checkAllowedHosts = checkAllowedHosts; //# sourceMappingURL=needle.js.map /***/ }), /***/ 15271: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildUnauthenticatedV2RequestConfig = exports.parseChallengeHeaders = exports.getToken = exports.paginatedV2Call = exports.registryCall = exports.registryV2Call = void 0; const parseLink = __webpack_require__(28490); const url = __webpack_require__(57310); const needle_1 = __webpack_require__(48360); const BEARER_REALM = "Bearer realm"; const MAX_RETRIES = 1; const MAX_REDIRECTS = 5; async function registryV2Call(registryBase, endpoint, accept, callChainObserver, username, password, reqOptions = {}) { const reqConfig = buildUnauthenticatedV2RequestConfig(registryBase, endpoint, accept, reqOptions); try { callChainObserver.visitedUrls.push(); return await (0, needle_1.needleWrapper)(reqConfig, MAX_RETRIES, callChainObserver); } catch (err) { if (err.statusCode === 401) { if (!username || !password) { // Supply and empty username and password if no credentials // are provided. These might be added later by a broker client. username = username ? username : ""; password = password ? password : ""; } const authConfig = await setAuthConfig(registryBase, err, reqConfig, username, password, reqOptions); try { return await (0, needle_1.needleWrapper)(authConfig, MAX_RETRIES, callChainObserver); } catch (err) { if (isRedirectStatus(err.statusCode)) { return await handleRedirect(err, reqConfig, callChainObserver); } throw err; } } if (isRedirectStatus(err.statusCode)) { return await handleRedirect(err, reqConfig, callChainObserver); } throw err; } } exports.registryV2Call = registryV2Call; /** * WARNING!!! * * This function was created for a very specific usecase (https://snyksec.atlassian.net/browse/MAGMA-1262) * It uses the existing mechanism of obtaining a token for authenticating, but can be used to hit any API endpoint, * and not necessarily a Docker V2 endpoint. * This is clearly an abuse of a library that's named after the v2 API, and this function should be considered a tech debt. * Once it's no longer necessary, it is advised that this function is removed. * */ async function registryCall(uri, username, password, reqOptions = {}, callChainObserver = { visitedUrls: [] }) { const reqConfig = applyRequestOptions({ uri: `https://${uri}` }, reqOptions); try { return await (0, needle_1.needleWrapper)(reqConfig, MAX_RETRIES, callChainObserver); } catch (err) { if (err.statusCode === 401) { if (!username || !password) { // Supply and empty username and password if no credentials // are provided. These might be added later by a broker client. username = username ? username : ""; password = password ? password : ""; } const authConfig = await setAuthConfig("", err, reqConfig, username, password, reqOptions); try { return await (0, needle_1.needleWrapper)(authConfig, MAX_RETRIES, callChainObserver); } catch (err) { if (isRedirectStatus(err.statusCode)) { return await handleRedirect(err, reqConfig, callChainObserver); } throw err; } } if (isRedirectStatus(err.statusCode)) { return await handleRedirect(err, reqConfig, callChainObserver); } throw err; } } exports.registryCall = registryCall; async function paginatedV2Call(registryBase, accept, username, password, endpoint, key, pageSize = 1000, maxPages = Number.MAX_SAFE_INTEGER, reqOptions = {}, callChainObserver = { visitedUrls: [] }) { const result = []; let pageEndpoint = `${endpoint}?n=${pageSize}`; let pageCount = 0; while (pageCount < maxPages) { const response = await registryV2Call(registryBase, pageEndpoint, accept, callChainObserver, username, password, reqOptions); const body = (0, needle_1.parseResponseBody)(response); if (body && body[key]) { result.push(...body[key]); } if (!response.headers.link) { break; } pageCount += 1; pageEndpoint = pageEndpointForLink(endpoint, response.headers.link); } return result; } exports.paginatedV2Call = paginatedV2Call; async function getToken(registryBase, authBase, service, scope, username, password, reqOptions = {}) { const reqConfig = applyRequestOptions({ uri: authBase, qs: { service, scope, }, }, Object.assign({}, reqOptions)); // Test truthiness, should be false when username and password are undefined if (username && password) { reqConfig.username = username; reqConfig.password = password; } const response = await (0, needle_1.needleWrapper)(Object.assign(Object.assign({}, reqConfig), { // we always want to read the credentials through the body snykInternalOutputStream: undefined })); const body = (0, needle_1.parseResponseBody)(response); return body.token || body.access_token; } exports.getToken = getToken; function parseChallengeHeaders(challengeHeaders) { const headersMap = {}; const headerSplit = challengeHeaders.split(","); for (let i = 0; i < headerSplit.length; i++) { const entry = headerSplit[i]; if (!entry.includes("=") && i > 0) { // we'll get here in case a value includes a comma. we want to concat what's after the comma to the previous value headerSplit[i - 1] += `,${entry}`; headerSplit.splice(i, 1); i--; } } headerSplit.forEach(entry => { const [key, value] = entry.split("="); headersMap[key] = JSON.parse(value); }); return [headersMap[BEARER_REALM], headersMap.service, headersMap.scope]; } exports.parseChallengeHeaders = parseChallengeHeaders; function buildUnauthenticatedV2RequestConfig(registryBase, endpoint, accept, reqOptions = {}) { return applyRequestOptions({ headers: { Accept: accept }, uri: `https://${registryBase}/v2${endpoint}`, }, reqOptions); } exports.buildUnauthenticatedV2RequestConfig = buildUnauthenticatedV2RequestConfig; function pageEndpointForLink(endpoint, link) { const linkPath = parseLink(link).next.url; const linkQuery = linkPath.split("?")[1]; return `${endpoint}?${linkQuery}`; } async function setAuthConfig(registryBase, err, reqConfig, username, password, reqOptions) { // See: https://docs.docker.com/registry/spec/auth/token/#how-to-authenticate const challengeHeaders = err.headers["www-authenticate"]; if (!challengeHeaders) { throw err; } const [authBase, service, scope] = parseChallengeHeaders(challengeHeaders); if (!authBase) { // basic auth return Object.assign(Object.assign({}, reqConfig), { username, password }); } else { // bearer token const token = await getToken(registryBase, authBase, service, scope, username, password, reqOptions); return Object.assign(Object.assign({}, reqConfig), { headers: Object.assign(Object.assign({}, reqConfig.headers), { Authorization: `Bearer ${token}` }) }); } } // Handle redirect while following up to MAX_REDIRECTS async function handleRedirect(err, config, callChainObserver) { return handleRedirectRec(err, config, MAX_REDIRECTS, callChainObserver); } async function handleRedirectRec(err, config, maxRedirects = 0, callChainObserver) { if (maxRedirects === 0) { throw err; } // ACR does not handle redirects well, where automatic redirects // fail due to an unexpected authorization header. // the solution is to follow the redirect, however discarding // the token. const location = err.headers.location; if (!location) { throw err; } // Only clear the Authorization headers if the redirect is for // azure container registries. if (location.includes("azurecr.io")) { delete config.headers.Authorization; } const redirectUrl = assertFullUrl(location, config.uri); config.uri = redirectUrl; try { return await (0, needle_1.needleWrapper)(config, MAX_RETRIES, callChainObserver); } catch (err) { if (isRedirectStatus(err.statusCode)) { return await handleRedirectRec(err, config, maxRedirects - 1, callChainObserver); } throw err; } } /* * Takes request config and applies allowed options to it. * @param reqConfig - request config that is passed to the request library. * @param reqOptions - options passed in from outside of v2 client library. */ function applyRequestOptions(reqConfig, reqOptions) { const options = Object.assign({}, reqOptions); let uri = applyUriProtocol(reqConfig.uri, options.protocol); delete options.protocol; uri = applyUriHostMappings(uri, options.hostMappings); delete options.hostMappings; const headers = applyHeaders(reqConfig.headers, options.headers); delete options.headers; return Object.assign(Object.assign(Object.assign({}, reqConfig), options), { uri, headers }); } function applyUriProtocol(uri, protocol) { if (!protocol) { return uri; } const updatedUrl = url.parse(uri); updatedUrl.protocol = protocol; return url.format(updatedUrl); } /** * Applies host mappings to given uri. * * @param uri * @param mappings - Array of mappings. Each mapping is represented as array * tuple: [host_regex_matcher, new_host]. */ function applyUriHostMappings(uri, mappings) { if (!mappings) { return uri; } const updatedUrl = url.parse(uri); const mapping = mappings.find(([matcher]) => updatedUrl.host.match(matcher)); if (!mapping) { return uri; } updatedUrl.host = mapping[1]; return url.format(updatedUrl); } function applyHeaders(currentHeaders, addHeaders) { return Object.assign(Object.assign({}, (currentHeaders || {})), (addHeaders || {})); } function assertFullUrl(redirectLocation, originalLocation) { let redirectUrl; try { redirectUrl = new URL(redirectLocation); } catch (_a) { // in case the location is not a proper URL (contains just the path), attach the original URL's origin const originalUrl = new URL(originalLocation); redirectUrl = new URL(redirectLocation, originalUrl.origin); } return redirectUrl.href; } /* Check whether the response status requires redirect. Note: since we only make GET requests, we do not need to handle different redirect statuses having different requirements for handling the request method. */ function isRedirectStatus(statusCode) { return (statusCode === 301 || statusCode === 302 || statusCode === 303 || statusCode === 307 || statusCode === 308); } //# sourceMappingURL=registry-call.js.map /***/ }), /***/ 47235: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); //# sourceMappingURL=types.js.map /***/ }), /***/ 69519: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.validateRepoOrImageRef = exports.ValidationError = exports.REPO_IMAGE_REF_BLANK_ERROR = exports.REPO_IMAGE_REF_INVALID_CHARS_ERROR = void 0; exports.REPO_IMAGE_REF_INVALID_CHARS_ERROR = 'Repository and image reference may not contain & ; " or a space or double slash'; exports.REPO_IMAGE_REF_BLANK_ERROR = "Repository and image reference may not be blank"; class ValidationError extends Error { } exports.ValidationError = ValidationError; function validateRepoOrImageRef(input) { const invalidCharacters = ["&", ";", " ", '"']; if (!input || input.trim().length === 0) { throw new ValidationError(exports.REPO_IMAGE_REF_BLANK_ERROR); } if (invalidCharacters.some(c => input.includes(c))) { throw new ValidationError(exports.REPO_IMAGE_REF_INVALID_CHARS_ERROR); } if (input.includes("//")) { throw new ValidationError(exports.REPO_IMAGE_REF_INVALID_CHARS_ERROR); } } exports.validateRepoOrImageRef = validateRepoOrImageRef; //# sourceMappingURL=validation.js.map /***/ }), /***/ 10635: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const fs = __webpack_require__(57147); const path = __webpack_require__(71017); const assert = __webpack_require__(39491); const GEMFILE_DEFAULT_LOCATION = path.resolve(process.cwd(), 'Gemfile.lock'); const WHITESPACE = /^(\s*)/; const GEMFILE_KEY_VALUE = /^\s*([^:(]*)\s*\:*\s*(.*)/; const ORIGINS = ['GEM', 'GIT', 'PATH']; const RUBY = /^ruby\s(.*)/; module.exports = { interpret, parse, parseSync }; function interpret(string, extractMeta) { assert( typeof string === 'string', 'gemfile.interpret expects a UTF-8 Gemfile.lock string source.' ); const gemfileMeta = {}; let line; let index = 0; let previousWhitespace = -1; let keyCount = {}; let gemfile = {}; let lines = string.split('\n'); let stack = []; while((line = lines[index++]) !== undefined) { // Handle depth stack changes let whitespace = WHITESPACE.exec(line)[1].length; if (whitespace <= previousWhitespace) { let stackIndex = stack.length - 1; while(stack[stackIndex] && (whitespace <= stack[stackIndex].depth)) { stack.pop(); stackIndex--; } } // Make note of line's whitespace depth previousWhitespace = whitespace; // Handle new key/value leaf let parts = GEMFILE_KEY_VALUE.exec(line); let key = parts[1].trim(); let value = parts[2] || ''; if (key) { // Handle path traversal let level = gemfile; for (let stackIndex = 0; stackIndex < stack.length; stackIndex++) { if (level[stack[stackIndex].key]) { level = level[stack[stackIndex].key]; } } // Handle data type inference let data = {}; if (value.indexOf('/') > -1) { data.path = value; } else if (value.indexOf('(') > -1) { if (value[value.length - 1] === '!') { value = value.substring(0, value.length - 1); data.outsourced = true; } if (value[1] !== ')') { data.version = value.substring(1, value.length - 1); } } else if (/\b[0-9a-f]{7,40}\b/.test(value)) { data.sha = value; } // Set key at current level // Do not throw away additional top-level key entries // e.g. multiple GIT/GEM blocks if (level[key]) { if (keyCount[key] === undefined) { keyCount[key] = 0; } else { keyCount[key]++; } level[key + keyCount[key]] = level[key]; } level[key] = data; // Push key on stack stack.push({key, depth: whitespace}); } } let keys = Object.keys(gemfile); let hasGemKey = keys.indexOf('GEM') > -1; let hasDependenciesKey = keys.indexOf('DEPENDENCIES') > -1; let hasPlatformsKey = keys.indexOf('PLATFORMS') > -1; if (!hasGemKey || !hasDependenciesKey || !hasPlatformsKey) { console.warn([ 'Are you sure this a Gemfile.lock?', 'If it is, please file an issue on Github: https://github.com/treycordova/gemfile/issues.', 'Regardless, gemfile parsed whatever you gave it.' ].join('\n')); } if (gemfile['BUNDLED WITH']) { gemfile['BUNDLED WITH'] = Object.keys(gemfile['BUNDLED WITH'])[0]; } if (gemfile['RUBY VERSION']) { const rawVersion= Object.keys(gemfile['RUBY VERSION'])[0]; const version = RUBY.exec(rawVersion)[1]; gemfile['RUBY VERSION'] = version; } if (extractMeta) { gemfileMeta.bundledWith = gemfile['BUNDLED WITH']; gemfileMeta.rubyVersion = gemfile['RUBY VERSION']; gemfileMeta.platforms = gemfile['PLATFORMS']; gemfileMeta.dependencies = gemfile['DEPENDENCIES']; gemfileMeta.specs = Object.keys(gemfile) .filter(key => ORIGINS.some(origin => key.startsWith(origin))) .reduce((specs, key) => { const type = key.match(/[A-Z]+/)[0]; const meta = Object.assign({ type }, gemfile[key]); delete meta.specs; Object.assign(specs, Object.keys(gemfile[key].specs).reduce((specs, gem) => { specs[gem] = Object.assign({}, gemfile[key].specs[gem], meta); return specs; }, {})); return specs; }, {}); return gemfileMeta; } return gemfile; } function parse(path, extractMeta) { path = typeof path === 'string' ? path : GEMFILE_DEFAULT_LOCATION; return new Promise(function(resolve, reject) { let file = fs.readFile(path, {encoding: 'utf8'}, function(error, gemfile) { if (error) { return reject(`Couldn't find a Gemfile at the specified location: ${path}.`); } else { return resolve(interpret(gemfile, extractMeta)); } }); }); } function parseSync(path, extractMeta) { path = typeof path === 'string' ? path : GEMFILE_DEFAULT_LOCATION; return interpret(fs.readFileSync(path, 'utf8'), extractMeta); } /***/ }), /***/ 35185: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.diff = exports.cmp = exports.neq = exports.eq = exports.lte = exports.lt = exports.gte = exports.gt = exports.rcompare = exports.compare = void 0; const assert_1 = __webpack_require__(39491); const goSemver = __webpack_require__(3443); const pseudoVersionRegExp = /(?:\.?0\.)?\d{14}-[0-9a-f]{8,32}$/i; function compare(v, w) { // short-circuit for identical versions if (v === w) { return 0; } let pv, pw; try { pv = goSemver.parse(v); pw = goSemver.parse(w); } catch (e) { // semver.compare properly deals with either or both of the versions // being invalid return goSemver.compare(v, w); } // see: https://golang.org/cmd/go/#hdr-Pseudo_versions const vm = pv.prerelease.match(pseudoVersionRegExp); const wm = pw.prerelease.match(pseudoVersionRegExp); if (!vm && !wm) { // neither is a pseudo-version return goSemver.compareParsed(pv, pw); } if (vm) { pv.prerelease = pv.prerelease.substring(0, vm.index); if (pv.prerelease === '-') { pv.prerelease = ''; } } if (wm) { pw.prerelease = pw.prerelease.substring(0, wm.index); if (pw.prerelease === '-') { pw.prerelease = ''; } } const c = goSemver.compareParsed(pv, pw); if (c !== 0) { return c; } // equal base versions, and at least one pseudo-version if (vm && wm) { // both pseudo-versions return vm[0] === wm[0] ? 0 : vm[0] < wm[0] ? -1 : +1; } else if (vm) { return isPseduoBefore(pv) ? -1 : +1; } else { (0, assert_1.strict)(wm); return isPseduoBefore(pw) ? +1 : -1; } } exports.compare = compare; function isPseduoBefore(pv) { if (pv.minor === '0' && pv.patch === '0') { // vX.0.0-yyyymmddhhmmss-abcdefabcdef return false; } else if (pv.prerelease.substring(1)) { // vX.Y.Z-pre.0.yyyymmddhhmmss-abcdefabcdef return false; } else { // vX.Y.(Z+1)-0.yyyymmddhhmmss-abcdefabcdef return true; } } function rcompare(v1, v2) { return compare(v2, v1); } exports.rcompare = rcompare; function gt(v1, v2) { return compare(v1, v2) > 0; } exports.gt = gt; function gte(v1, v2) { return compare(v1, v2) >= 0; } exports.gte = gte; function lt(v1, v2) { return compare(v1, v2) < 0; } exports.lt = lt; function lte(v1, v2) { return compare(v1, v2) <= 0; } exports.lte = lte; function eq(v1, v2) { return compare(v1, v2) === 0; } exports.eq = eq; function neq(v1, v2) { return compare(v1, v2) !== 0; } exports.neq = neq; function _strictEq(v1, v2) { try { const pv1 = goSemver.parse(v1); const pv2 = goSemver.parse(v2); return goSemver.compareParsed(pv1, pv2) === 0 && pv1.short === pv2.short; } catch (e) { return v1 === v2; } } function _strictNeq(v1, v2) { return !_strictEq(v1, v2); } function cmp(v1, comparator, v2) { switch (comparator) { case '>': return gt(v1, v2); case '>=': return gte(v1, v2); case '<': return lt(v1, v2); case '<=': return lte(v1, v2); case '==': return eq(v1, v2); case '!=': return neq(v1, v2); case '===': return _strictEq(v1, v2); case '!==': return _strictNeq(v1, v2); default: throw new Error(`Invalid comparator: ${comparator}`); } } exports.cmp = cmp; function diff() { throw new Error('Not implemented'); } exports.diff = diff; //# sourceMappingURL=comparison.js.map /***/ }), /***/ 88131: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.inc = exports.prerelease = exports.patch = exports.minor = exports.major = exports.valid = void 0; const semver_1 = __webpack_require__(3443); function valid(v) { return (0, semver_1.isValid)(v); } exports.valid = valid; function major(v) { try { return (0, semver_1.parse)(v).major; } catch (e) { return null; } } exports.major = major; function minor(v) { try { return (0, semver_1.parse)(v).minor; } catch (e) { return null; } } exports.minor = minor; function patch(v) { try { return (0, semver_1.parse)(v).patch; } catch (e) { return null; } } exports.patch = patch; function prerelease(v) { try { // remove leading '-' from prerelease return (0, semver_1.parse)(v).prerelease.substring(1); } catch (e) { return null; } } exports.prerelease = prerelease; // eslint-disable-next-line @typescript-eslint/no-unused-vars function inc(v) { throw new Error('Not implemented'); } exports.inc = inc; //# sourceMappingURL=functions.js.map /***/ }), /***/ 3443: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // // This is a direct translation of the semver/semver.go file in // github.com/golang/mod, with a few changes to match Typescript // conventions. Some string analysis logic was converted to use // regular expressions to improve performance. // // This translation was done by Tal Einat under contract for Snyk Ltd. // during February 2020. All copyright for the translated code not covered // by the copyright for the original Go code belongs to Snyk Ltd. // // Package semver implements comparison of semantic version strings. // In this package, semantic version strings must begin with a leading "v", // as in "v1.0.0". // // The general form of a semantic version string accepted by this package is // // vMAJOR[.MINOR[.PATCH[-PRERELEASE][+BUILD]]] // // where square brackets indicate optional parts of the syntax; // MAJOR, MINOR, and PATCH are decimal integers without extra leading zeros; // PRERELEASE and BUILD are each a series of non-empty dot-separated identifiers // using only alphanumeric characters and hyphens; and // all-numeric PRERELEASE identifiers must not have leading zeros. // // This package follows Semantic Versioning 2.0.0 (see semver.org) // with two exceptions. First, it requires the "v" prefix. Second, it recognizes // vMAJOR and vMAJOR.MINOR (with no prerelease or build suffixes) // as shorthands for vMAJOR.0.0 and vMAJOR.MINOR.0. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parse = exports.JunkOnEnd = exports.InvalidVersion = exports.max = exports.compareParsed = exports.compare = exports.build = exports.prerelease = exports.majorMinor = exports.major = exports.canonical = exports.isValid = void 0; // isValid reports whether v is a valid semantic version string. function isValid(v) { try { parse(v); } catch (e) { return false; } return true; } exports.isValid = isValid; // Canonical returns the canonical formatting of the semantic version v. // It fills in any missing .MINOR or .PATCH and discards build metadata. // Two semantic versions compare equal only if their canonical formattings // are identical strings. // The canonical invalid semantic version is the empty string. function canonical(v) { let p; try { p = parse(v); } catch (e) { return ''; } if (p.build !== '') { return v.slice(0, -p.build.length); } if (p.short !== '') { return v + p.short; } return v; } exports.canonical = canonical; // Major returns the major version prefix of the semantic version v. // For example, Major("v2.1.0") == "v2". // If v is an invalid semantic version string, Major returns the empty string. function major(v) { let pv; try { pv = parse(v); } catch (e) { return ''; } return v.slice(0, 1 + pv.major.length); } exports.major = major; // MajorMinor returns the major.minor version prefix of the semantic version v. // For example, MajorMinor("v2.1.0") == "v2.1". // If v is an invalid semantic version string, MajorMinor returns the empty string. function majorMinor(v) { let pv; try { pv = parse(v); } catch (e) { return ''; } const i = 1 + pv.major.length; const j = i + 1 + pv.minor.length; if (j <= v.length && v[i] === '.' && v.substring(i + 1, j) === pv.minor) { return v.substring(0, j); } return v.substring(0, i) + '.' + pv.minor; } exports.majorMinor = majorMinor; // Prerelease returns the prerelease suffix of the semantic version v. // For example, Prerelease("v2.1.0-pre+meta") == "-pre". // If v is an invalid semantic version string, Prerelease returns the empty string. function prerelease(v) { let pv; try { pv = parse(v); } catch (e) { return ''; } return pv.prerelease; } exports.prerelease = prerelease; // Build returns the build suffix of the semantic version v. // For example, Build("v2.1.0+meta") == "+meta". // If v is an invalid semantic version string, Build returns the empty string. function build(v) { let pv; try { pv = parse(v); } catch (e) { return ''; } return pv.build; } exports.build = build; // Compare returns an integer comparing two versions according to // semantic version precedence. // The result will be 0 if v == w, -1 if v < w, or +1 if v > w. // // An invalid semantic version string is considered less than a valid one. // All invalid semantic version strings compare equal to each other. function compare(v, w) { let pv, pw; try { pv = parse(v); } catch (e) { } try { pw = parse(w); if (!pv) { return +1; } } catch (e) { if (!pv) { return 0; } else { return -1; } } return compareParsed(pv, pw); } exports.compare = compare; function compareParsed(pv, pw) { const majorCompare = compareInt(pv.major, pw.major); if (majorCompare !== 0) { return majorCompare; } const minorCompare = compareInt(pv.minor, pw.minor); if (minorCompare !== 0) { return minorCompare; } const patchCompare = compareInt(pv.patch, pw.patch); if (patchCompare !== 0) { return patchCompare; } return comparePrerelease(pv.prerelease, pw.prerelease); } exports.compareParsed = compareParsed; // Max canonicalizes its arguments and then returns the version string // that compares greater. function max(v, w) { v = canonical(v); w = canonical(w); if (compare(v, w) > 0) { return v; } return w; } exports.max = max; class InvalidVersion extends Error { constructor(message, input) { super(message); this.input = input; } } exports.InvalidVersion = InvalidVersion; class JunkOnEnd extends InvalidVersion { constructor(message, input, junk) { super(message, input); this.junk = junk; } } exports.JunkOnEnd = JunkOnEnd; function parse(v) { if (v === '' || v[0] !== 'v') { throw new InvalidVersion('missing v prefix', v); } const p = { major: '', minor: '', patch: '', short: '', prerelease: '', build: '', }; const input = v; try { [p.major, v] = parseInt(v.substring(1)); } catch (e) { throw new InvalidVersion('bad major version', input); } if (v === '') { p.minor = '0'; p.patch = '0'; p.short = '.0.0'; return p; } if (v[0] !== '.') { throw new InvalidVersion('bad minor prefix', input); } try { [p.minor, v] = parseInt(v.substring(1)); } catch (e) { throw new InvalidVersion('bad minor version', input); } if (v === '') { p.patch = '0'; p.short = '.0.0'; return p; } if (v[0] !== '.') { throw new InvalidVersion('bad patch prefix', input); } try { [p.patch, v] = parseInt(v.substring(1)); } catch (e) { throw new InvalidVersion('bad patch version', input); } if (v.length > 0 && v[0] === '-') { try { [p.prerelease, v] = parsePrerelease(v); } catch (e) { throw new InvalidVersion('bad prerelease', input); } } if (v.length > 0 && v[0] === '+') { try { [p.build, v] = parseBuild(v); } catch (e) { throw new InvalidVersion('bad build', input); } } if (v !== '') { throw new JunkOnEnd('junk on end', input, v); } return p; } exports.parse = parse; const intRegExp = /^0|[1-9][0-9]*/; function parseInt(v) { const m = v.match(intRegExp); if (!m) { throw new Error(); } return [m[0], v.substring(m[0].length)]; } // "A pre-release version MAY be denoted by appending a hyphen and // a series of dot separated identifiers immediately following the patch version. // Identifiers MUST comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. // Identifiers MUST NOT be empty. Numeric identifiers MUST NOT include leading zeroes." const prereleaseRegExp = /^(-[0-9A-Za-z0-9-]+(?:\.[0-9A-Za-z-]+)*)(?:\+|$)/; function parsePrerelease(v) { const m = v.match(prereleaseRegExp); if (!m) { throw new Error(); } const parts = m[1].substring(1).split('.'); if (parts.filter(isBadNum).length > 0) { throw new Error(); } return [m[1], v.substring(m[1].length)]; } const buildRegExp = /^\+[0-9A-Za-z0-9-]+(?:\.[0-9A-Za-z-]+)*$/; function parseBuild(v) { const m = v.match(buildRegExp); if (!m) { throw new Error(); } return [m[0], v.substring(m[0].length)]; } const isBadNumRegexp = /^0[0-9]+$/; function isBadNum(v) { return isBadNumRegexp.test(v); } const isNumRegexp = /^[0-9]*$/; function isNum(v) { return isNumRegexp.test(v); } function compareInt(x, y) { if (x === y) { return 0; } if (x.length < y.length) { return -1; } if (x.length > y.length) { return +1; } if (x < y) { return -1; } else { return +1; } } function comparePrerelease(x, y) { // "When major, minor, and patch are equal, a pre-release version has // lower precedence than a normal version. // Example: 1.0.0-alpha < 1.0.0. // Precedence for two pre-release versions with the same major, minor, // and patch version MUST be determined by comparing each dot separated // identifier from left to right until a difference is found as follows: // identifiers consisting of only digits are compared numerically and // identifiers with letters or hyphens are compared lexically in ASCII // sort order. Numeric identifiers always have lower precedence than // non-numeric identifiers. A larger set of pre-release fields has a // higher precedence than a smaller set, if all of the preceding // identifiers are equal. // Example: 1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-alpha.beta < // 1.0.0-beta < 1.0.0-beta.2 < 1.0.0-beta.11 < 1.0.0-rc.1 < 1.0.0." if (x === y) { return 0; } if (x === '') { return +1; } if (y === '') { return -1; } x = x.substring(1); // skip initial - y = y.substring(1); // skip initial - while (x && y) { let dx, dy; [dx, x] = x.split('.', 2); [dy, y] = y.split('.', 2); if (dx !== dy) { const ix = isNum(dx); const iy = isNum(dy); if (ix !== iy) { if (ix) { return -1; } else { return +1; } } if (ix) { if (dx.length < dy.length) { return -1; } if (dx.length > dy.length) { return +1; } } if (dx < dy) { return -1; } else { return +1; } } } if (!x) { return -1; } else { return +1; } } //# sourceMappingURL=semver.js.map /***/ }), /***/ 61746: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __webpack_require__(85996); tslib_1.__exportStar(__webpack_require__(35185), exports); tslib_1.__exportStar(__webpack_require__(88131), exports); tslib_1.__exportStar(__webpack_require__(95944), exports); //# sourceMappingURL=index.js.map /***/ }), /***/ 95944: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.outside = exports.ltr = exports.gtr = exports.intersects = exports.minSatisfying = exports.maxSatisfying = exports.satisfies = exports.validRange = void 0; const semver_1 = __webpack_require__(3443); const comparison_1 = __webpack_require__(35185); class InvalidRequirementPart extends Error { } class InvalidVersionRange extends Error { } const DEFAULT_REQUIREMENT = [ { startVersion: 'v0.0.0', isStartInclusive: true, isEndInclusive: false }, ]; const OPS = ['>=', '<=', '>', '<', '=']; const OPS_RE = `^(${OPS.join('|')})?(.*)$`; function parsePart(part) { const match = part.trim().match(OPS_RE); if (!match) { throw new InvalidRequirementPart(); } const op = (match[1] || '='); const version = match[2].trim(); if (!(0, semver_1.isValid)(version)) { throw new InvalidRequirementPart(); } return { op, version }; } function parseRange(rangeStr) { let parts; try { parts = rangeStr.split(',').map(parsePart); } catch (error) { if (error instanceof InvalidRequirementPart) { throw new InvalidVersionRange(); } throw error; } const range = {}; function setInclusive(attr, value) { if (range.hasOwnProperty(attr)) { throw new InvalidRequirementPart(); } range[attr] = value; } function setVersion(attr, value) { if (range.hasOwnProperty(attr)) { throw new InvalidRequirementPart(); } range[attr] = value; } for (const { op, version } of parts) { if (op === '=') { setVersion('startVersion', version); setInclusive('isStartInclusive', true); setVersion('endVersion', version); setInclusive('isEndInclusive', true); } else { setVersion(op[0] === '>' ? 'startVersion' : 'endVersion', version); setInclusive(op[0] === '>' ? 'isStartInclusive' : 'isEndInclusive', op.endsWith('=')); } } if (range.startVersion && range.endVersion) { const comp = (0, comparison_1.compare)(range.startVersion, range.endVersion); if (comp === 1 || (comp === 0 && !(range.isStartInclusive && range.isEndInclusive))) { throw new InvalidRequirementPart(); } } return range; } function parseRequirement(requirementStr) { const rangeStrs = requirementStr.split('||').map((part) => part.trim()); if (rangeStrs.length === 0) { return DEFAULT_REQUIREMENT; } return rangeStrs.map(parseRange); } function validRange(range) { if (!range.trim()) { return null; } try { return parseRequirement(range) .map((range) => { const parts = []; if (range.startVersion && range.startVersion == range.endVersion) { return '=' + range.startVersion; } if (range.startVersion) { parts.push((range.isStartInclusive ? '>=' : '>') + range.startVersion); } if (range.endVersion) { parts.push((range.isEndInclusive ? '<=' : '<') + range.endVersion); } return parts.length > 0 ? parts.join(',') : '>=v0.0.0'; }) .join(' || '); } catch (err) { return null; } } exports.validRange = validRange; function satisfies(version, range) { // Throw an exception if the version is invalid. (0, semver_1.parse)(version); for (const part of parseRequirement(range)) { if (part.startVersion) { const comp = (0, comparison_1.compare)(version, part.startVersion); if (comp === -1 || (comp === 0 && !part.isStartInclusive)) { continue; } } if (part.endVersion) { const comp = (0, comparison_1.compare)(version, part.endVersion); if (comp === 1 || (comp === 0 && !part.isEndInclusive)) { continue; } } return true; } return false; } exports.satisfies = satisfies; function maxSatisfying() { throw new Error('Not implemented'); } exports.maxSatisfying = maxSatisfying; function minSatisfying() { throw new Error('Not implemented'); } exports.minSatisfying = minSatisfying; function intersects(r1, r2) { const leftRanges = parseRequirement(r1); const rightRanges = parseRequirement(r2); for (const leftRange of leftRanges) { for (const rightRange of rightRanges) { if (!(isBefore(leftRange, rightRange) || isBefore(rightRange, leftRange))) { return true; } } } return false; } exports.intersects = intersects; function isBefore(leftRange, rightRange) { if (leftRange.endVersion && rightRange.startVersion) { const comp = (0, comparison_1.compare)(leftRange.endVersion, rightRange.startVersion); if (comp === -1 || (comp === 0 && !(leftRange.isEndInclusive && rightRange.isStartInclusive))) { return true; } } return false; } function gtr() { throw new Error('Not implemented'); } exports.gtr = gtr; function ltr() { throw new Error('Not implemented'); } exports.ltr = ltr; function outside() { throw new Error('Not implemented'); } exports.outside = outside; //# sourceMappingURL=ranges.js.map /***/ }), /***/ 85996: /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "__extends": () => (/* binding */ __extends), /* harmony export */ "__assign": () => (/* binding */ __assign), /* harmony export */ "__rest": () => (/* binding */ __rest), /* harmony export */ "__decorate": () => (/* binding */ __decorate), /* harmony export */ "__param": () => (/* binding */ __param), /* harmony export */ "__esDecorate": () => (/* binding */ __esDecorate), /* harmony export */ "__runInitializers": () => (/* binding */ __runInitializers), /* harmony export */ "__propKey": () => (/* binding */ __propKey), /* harmony export */ "__setFunctionName": () => (/* binding */ __setFunctionName), /* harmony export */ "__metadata": () => (/* binding */ __metadata), /* harmony export */ "__awaiter": () => (/* binding */ __awaiter), /* harmony export */ "__generator": () => (/* binding */ __generator), /* harmony export */ "__createBinding": () => (/* binding */ __createBinding), /* harmony export */ "__exportStar": () => (/* binding */ __exportStar), /* harmony export */ "__values": () => (/* binding */ __values), /* harmony export */ "__read": () => (/* binding */ __read), /* harmony export */ "__spread": () => (/* binding */ __spread), /* harmony export */ "__spreadArrays": () => (/* binding */ __spreadArrays), /* harmony export */ "__spreadArray": () => (/* binding */ __spreadArray), /* harmony export */ "__await": () => (/* binding */ __await), /* harmony export */ "__asyncGenerator": () => (/* binding */ __asyncGenerator), /* harmony export */ "__asyncDelegator": () => (/* binding */ __asyncDelegator), /* harmony export */ "__asyncValues": () => (/* binding */ __asyncValues), /* harmony export */ "__makeTemplateObject": () => (/* binding */ __makeTemplateObject), /* harmony export */ "__importStar": () => (/* binding */ __importStar), /* harmony export */ "__importDefault": () => (/* binding */ __importDefault), /* harmony export */ "__classPrivateFieldGet": () => (/* binding */ __classPrivateFieldGet), /* harmony export */ "__classPrivateFieldSet": () => (/* binding */ __classPrivateFieldSet), /* harmony export */ "__classPrivateFieldIn": () => (/* binding */ __classPrivateFieldIn) /* harmony export */ }); /****************************************************************************** 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 */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; } return __assign.apply(this, arguments); } 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; } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } } function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); var _, done = false; for (var i = decorators.length - 1; i >= 0; i--) { var context = {}; for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; for (var p in contextIn.access) context.access[p] = contextIn.access[p]; context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); if (kind === "accessor") { if (result === void 0) continue; if (result === null || typeof result !== "object") throw new TypeError("Object expected"); if (_ = accept(result.get)) descriptor.get = _; if (_ = accept(result.set)) descriptor.set = _; if (_ = accept(result.init)) initializers.push(_); } else if (_ = accept(result)) { if (kind === "field") initializers.push(_); else descriptor[key] = _; } } if (target) Object.defineProperty(target, contextIn.name, descriptor); done = true; }; function __runInitializers(thisArg, initializers, value) { var useValue = arguments.length > 2; for (var i = 0; i < initializers.length; i++) { value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); } return useValue ? value : void 0; }; function __propKey(x) { return typeof x === "symbol" ? x : "".concat(x); }; function __setFunctionName(f, name, prefix) { if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); }; function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var __createBinding = Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; }); function __exportStar(m, o) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } /** @deprecated */ function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } /** @deprecated */ function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; var __setModuleDefault = Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }; function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; } function __importDefault(mod) { return (mod && mod.__esModule) ? mod : { default: mod }; } function __classPrivateFieldGet(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); } function __classPrivateFieldSet(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; } function __classPrivateFieldIn(state, receiver) { if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); return typeof state === "function" ? receiver === state : state.has(receiver); } /***/ }), /***/ 39322: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /** * Copyright (c) 2014, Chris Pettitt * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ var lib = __webpack_require__(19943); module.exports = { Graph: lib.Graph, json: __webpack_require__(40584), alg: __webpack_require__(67550), version: lib.version }; /***/ }), /***/ 94686: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var _ = __webpack_require__(8570); module.exports = components; function components(g) { var visited = {}; var cmpts = []; var cmpt; function dfs(v) { if (_.has(visited, v)) return; visited[v] = true; cmpt.push(v); _.each(g.successors(v), dfs); _.each(g.predecessors(v), dfs); } _.each(g.nodes(), function(v) { cmpt = []; dfs(v); if (cmpt.length) { cmpts.push(cmpt); } }); return cmpts; } /***/ }), /***/ 1647: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var _ = __webpack_require__(8570); module.exports = dfs; /* * A helper that preforms a pre- or post-order traversal on the input graph * and returns the nodes in the order they were visited. If the graph is * undirected then this algorithm will navigate using neighbors. If the graph * is directed then this algorithm will navigate using successors. * * Order must be one of "pre" or "post". */ function dfs(g, vs, order) { if (!_.isArray(vs)) { vs = [vs]; } var navigation = (g.isDirected() ? g.successors : g.neighbors).bind(g); var acc = []; var visited = {}; _.each(vs, function(v) { if (!g.hasNode(v)) { throw new Error("Graph does not have node: " + v); } doDfs(g, v, order === "post", visited, navigation, acc); }); return acc; } function doDfs(g, v, postorder, visited, navigation, acc) { if (!_.has(visited, v)) { visited[v] = true; if (!postorder) { acc.push(v); } _.each(navigation(v), function(w) { doDfs(g, w, postorder, visited, navigation, acc); }); if (postorder) { acc.push(v); } } } /***/ }), /***/ 16342: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var dijkstra = __webpack_require__(70785); var _ = __webpack_require__(8570); module.exports = dijkstraAll; function dijkstraAll(g, weightFunc, edgeFunc) { return _.transform(g.nodes(), function(acc, v) { acc[v] = dijkstra(g, v, weightFunc, edgeFunc); }, {}); } /***/ }), /***/ 70785: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var _ = __webpack_require__(8570); var PriorityQueue = __webpack_require__(85474); module.exports = dijkstra; var DEFAULT_WEIGHT_FUNC = _.constant(1); function dijkstra(g, source, weightFn, edgeFn) { return runDijkstra(g, String(source), weightFn || DEFAULT_WEIGHT_FUNC, edgeFn || function(v) { return g.outEdges(v); }); } function runDijkstra(g, source, weightFn, edgeFn) { var results = {}; var pq = new PriorityQueue(); var v, vEntry; var updateNeighbors = function(edge) { var w = edge.v !== v ? edge.v : edge.w; var wEntry = results[w]; var weight = weightFn(edge); var distance = vEntry.distance + weight; if (weight < 0) { throw new Error("dijkstra does not allow negative edge weights. " + "Bad edge: " + edge + " Weight: " + weight); } if (distance < wEntry.distance) { wEntry.distance = distance; wEntry.predecessor = v; pq.decrease(w, distance); } }; g.nodes().forEach(function(v) { var distance = v === source ? 0 : Number.POSITIVE_INFINITY; results[v] = { distance: distance }; pq.add(v, distance); }); while (pq.size() > 0) { v = pq.removeMin(); vEntry = results[v]; if (vEntry.distance === Number.POSITIVE_INFINITY) { break; } edgeFn(v).forEach(updateNeighbors); } return results; } /***/ }), /***/ 81046: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var _ = __webpack_require__(8570); var tarjan = __webpack_require__(61511); module.exports = findCycles; function findCycles(g) { return _.filter(tarjan(g), function(cmpt) { return cmpt.length > 1 || (cmpt.length === 1 && g.hasEdge(cmpt[0], cmpt[0])); }); } /***/ }), /***/ 71786: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var _ = __webpack_require__(8570); module.exports = floydWarshall; var DEFAULT_WEIGHT_FUNC = _.constant(1); function floydWarshall(g, weightFn, edgeFn) { return runFloydWarshall(g, weightFn || DEFAULT_WEIGHT_FUNC, edgeFn || function(v) { return g.outEdges(v); }); } function runFloydWarshall(g, weightFn, edgeFn) { var results = {}; var nodes = g.nodes(); nodes.forEach(function(v) { results[v] = {}; results[v][v] = { distance: 0 }; nodes.forEach(function(w) { if (v !== w) { results[v][w] = { distance: Number.POSITIVE_INFINITY }; } }); edgeFn(v).forEach(function(edge) { var w = edge.v === v ? edge.w : edge.v; var d = weightFn(edge); results[v][w] = { distance: d, predecessor: v }; }); }); nodes.forEach(function(k) { var rowK = results[k]; nodes.forEach(function(i) { var rowI = results[i]; nodes.forEach(function(j) { var ik = rowI[k]; var kj = rowK[j]; var ij = rowI[j]; var altDistance = ik.distance + kj.distance; if (altDistance < ij.distance) { ij.distance = altDistance; ij.predecessor = kj.predecessor; } }); }); }); return results; } /***/ }), /***/ 67550: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = { components: __webpack_require__(94686), dijkstra: __webpack_require__(70785), dijkstraAll: __webpack_require__(16342), findCycles: __webpack_require__(81046), floydWarshall: __webpack_require__(71786), isAcyclic: __webpack_require__(57200), postorder: __webpack_require__(26877), preorder: __webpack_require__(80573), prim: __webpack_require__(8472), tarjan: __webpack_require__(61511), topsort: __webpack_require__(95626) }; /***/ }), /***/ 57200: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var topsort = __webpack_require__(95626); module.exports = isAcyclic; function isAcyclic(g) { try { topsort(g); } catch (e) { if (e instanceof topsort.CycleException) { return false; } throw e; } return true; } /***/ }), /***/ 26877: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var dfs = __webpack_require__(1647); module.exports = postorder; function postorder(g, vs) { return dfs(g, vs, "post"); } /***/ }), /***/ 80573: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var dfs = __webpack_require__(1647); module.exports = preorder; function preorder(g, vs) { return dfs(g, vs, "pre"); } /***/ }), /***/ 8472: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var _ = __webpack_require__(8570); var Graph = __webpack_require__(6583); var PriorityQueue = __webpack_require__(85474); module.exports = prim; function prim(g, weightFunc) { var result = new Graph(); var parents = {}; var pq = new PriorityQueue(); var v; function updateNeighbors(edge) { var w = edge.v === v ? edge.w : edge.v; var pri = pq.priority(w); if (pri !== undefined) { var edgeWeight = weightFunc(edge); if (edgeWeight < pri) { parents[w] = v; pq.decrease(w, edgeWeight); } } } if (g.nodeCount() === 0) { return result; } _.each(g.nodes(), function(v) { pq.add(v, Number.POSITIVE_INFINITY); result.setNode(v); }); // Start from an arbitrary node pq.decrease(g.nodes()[0], 0); var init = false; while (pq.size() > 0) { v = pq.removeMin(); if (_.has(parents, v)) { result.setEdge(v, parents[v]); } else if (init) { throw new Error("Input graph is not connected: " + g); } else { init = true; } g.nodeEdges(v).forEach(updateNeighbors); } return result; } /***/ }), /***/ 61511: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var _ = __webpack_require__(8570); module.exports = tarjan; function tarjan(g) { var index = 0; var stack = []; var visited = {}; // node id -> { onStack, lowlink, index } var results = []; function dfs(v) { var entry = visited[v] = { onStack: true, lowlink: index, index: index++ }; stack.push(v); g.successors(v).forEach(function(w) { if (!_.has(visited, w)) { dfs(w); entry.lowlink = Math.min(entry.lowlink, visited[w].lowlink); } else if (visited[w].onStack) { entry.lowlink = Math.min(entry.lowlink, visited[w].index); } }); if (entry.lowlink === entry.index) { var cmpt = []; var w; do { w = stack.pop(); visited[w].onStack = false; cmpt.push(w); } while (v !== w); results.push(cmpt); } } g.nodes().forEach(function(v) { if (!_.has(visited, v)) { dfs(v); } }); return results; } /***/ }), /***/ 95626: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var _ = __webpack_require__(8570); module.exports = topsort; topsort.CycleException = CycleException; function topsort(g) { var visited = {}; var stack = {}; var results = []; function visit(node) { if (_.has(stack, node)) { throw new CycleException(); } if (!_.has(visited, node)) { stack[node] = true; visited[node] = true; _.each(g.predecessors(node), visit); delete stack[node]; results.push(node); } } _.each(g.sinks(), visit); if (_.size(visited) !== g.nodeCount()) { throw new CycleException(); } return results; } function CycleException() {} CycleException.prototype = new Error(); // must be an instance of Error to pass testing /***/ }), /***/ 85474: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var _ = __webpack_require__(8570); module.exports = PriorityQueue; /** * A min-priority queue data structure. This algorithm is derived from Cormen, * et al., "Introduction to Algorithms". The basic idea of a min-priority * queue is that you can efficiently (in O(1) time) get the smallest key in * the queue. Adding and removing elements takes O(log n) time. A key can * have its priority decreased in O(log n) time. */ function PriorityQueue() { this._arr = []; this._keyIndices = {}; } /** * Returns the number of elements in the queue. Takes `O(1)` time. */ PriorityQueue.prototype.size = function() { return this._arr.length; }; /** * Returns the keys that are in the queue. Takes `O(n)` time. */ PriorityQueue.prototype.keys = function() { return this._arr.map(function(x) { return x.key; }); }; /** * Returns `true` if **key** is in the queue and `false` if not. */ PriorityQueue.prototype.has = function(key) { return _.has(this._keyIndices, key); }; /** * Returns the priority for **key**. If **key** is not present in the queue * then this function returns `undefined`. Takes `O(1)` time. * * @param {Object} key */ PriorityQueue.prototype.priority = function(key) { var index = this._keyIndices[key]; if (index !== undefined) { return this._arr[index].priority; } }; /** * Returns the key for the minimum element in this queue. If the queue is * empty this function throws an Error. Takes `O(1)` time. */ PriorityQueue.prototype.min = function() { if (this.size() === 0) { throw new Error("Queue underflow"); } return this._arr[0].key; }; /** * Inserts a new key into the priority queue. If the key already exists in * the queue this function returns `false`; otherwise it will return `true`. * Takes `O(n)` time. * * @param {Object} key the key to add * @param {Number} priority the initial priority for the key */ PriorityQueue.prototype.add = function(key, priority) { var keyIndices = this._keyIndices; key = String(key); if (!_.has(keyIndices, key)) { var arr = this._arr; var index = arr.length; keyIndices[key] = index; arr.push({key: key, priority: priority}); this._decrease(index); return true; } return false; }; /** * Removes and returns the smallest key in the queue. Takes `O(log n)` time. */ PriorityQueue.prototype.removeMin = function() { this._swap(0, this._arr.length - 1); var min = this._arr.pop(); delete this._keyIndices[min.key]; this._heapify(0); return min.key; }; /** * Decreases the priority for **key** to **priority**. If the new priority is * greater than the previous priority, this function will throw an Error. * * @param {Object} key the key for which to raise priority * @param {Number} priority the new priority for the key */ PriorityQueue.prototype.decrease = function(key, priority) { var index = this._keyIndices[key]; if (priority > this._arr[index].priority) { throw new Error("New priority is greater than current priority. " + "Key: " + key + " Old: " + this._arr[index].priority + " New: " + priority); } this._arr[index].priority = priority; this._decrease(index); }; PriorityQueue.prototype._heapify = function(i) { var arr = this._arr; var l = 2 * i; var r = l + 1; var largest = i; if (l < arr.length) { largest = arr[l].priority < arr[largest].priority ? l : largest; if (r < arr.length) { largest = arr[r].priority < arr[largest].priority ? r : largest; } if (largest !== i) { this._swap(i, largest); this._heapify(largest); } } }; PriorityQueue.prototype._decrease = function(index) { var arr = this._arr; var priority = arr[index].priority; var parent; while (index !== 0) { parent = index >> 1; if (arr[parent].priority < priority) { break; } this._swap(index, parent); index = parent; } }; PriorityQueue.prototype._swap = function(i, j) { var arr = this._arr; var keyIndices = this._keyIndices; var origArrI = arr[i]; var origArrJ = arr[j]; arr[i] = origArrJ; arr[j] = origArrI; keyIndices[origArrJ.key] = i; keyIndices[origArrI.key] = j; }; /***/ }), /***/ 6583: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var _ = __webpack_require__(8570); module.exports = Graph; var DEFAULT_EDGE_NAME = "\x00"; var GRAPH_NODE = "\x00"; var EDGE_KEY_DELIM = "\x01"; // Implementation notes: // // * Node id query functions should return string ids for the nodes // * Edge id query functions should return an "edgeObj", edge object, that is // composed of enough information to uniquely identify an edge: {v, w, name}. // * Internally we use an "edgeId", a stringified form of the edgeObj, to // reference edges. This is because we need a performant way to look these // edges up and, object properties, which have string keys, are the closest // we're going to get to a performant hashtable in JavaScript. function Graph(opts) { this._isDirected = _.has(opts, "directed") ? opts.directed : true; this._isMultigraph = _.has(opts, "multigraph") ? opts.multigraph : false; this._isCompound = _.has(opts, "compound") ? opts.compound : false; // Label for the graph itself this._label = undefined; // Defaults to be set when creating a new node this._defaultNodeLabelFn = _.constant(undefined); // Defaults to be set when creating a new edge this._defaultEdgeLabelFn = _.constant(undefined); // v -> label this._nodes = {}; if (this._isCompound) { // v -> parent this._parent = {}; // v -> children this._children = {}; this._children[GRAPH_NODE] = {}; } // v -> edgeObj this._in = {}; // u -> v -> Number this._preds = {}; // v -> edgeObj this._out = {}; // v -> w -> Number this._sucs = {}; // e -> edgeObj this._edgeObjs = {}; // e -> label this._edgeLabels = {}; } /* Number of nodes in the graph. Should only be changed by the implementation. */ Graph.prototype._nodeCount = 0; /* Number of edges in the graph. Should only be changed by the implementation. */ Graph.prototype._edgeCount = 0; /* === Graph functions ========= */ Graph.prototype.isDirected = function() { return this._isDirected; }; Graph.prototype.isMultigraph = function() { return this._isMultigraph; }; Graph.prototype.isCompound = function() { return this._isCompound; }; Graph.prototype.setGraph = function(label) { this._label = label; return this; }; Graph.prototype.graph = function() { return this._label; }; /* === Node functions ========== */ Graph.prototype.setDefaultNodeLabel = function(newDefault) { if (!_.isFunction(newDefault)) { newDefault = _.constant(newDefault); } this._defaultNodeLabelFn = newDefault; return this; }; Graph.prototype.nodeCount = function() { return this._nodeCount; }; Graph.prototype.nodes = function() { return _.keys(this._nodes); }; Graph.prototype.sources = function() { var self = this; return _.filter(this.nodes(), function(v) { return _.isEmpty(self._in[v]); }); }; Graph.prototype.sinks = function() { var self = this; return _.filter(this.nodes(), function(v) { return _.isEmpty(self._out[v]); }); }; Graph.prototype.setNodes = function(vs, value) { var args = arguments; var self = this; _.each(vs, function(v) { if (args.length > 1) { self.setNode(v, value); } else { self.setNode(v); } }); return this; }; Graph.prototype.setNode = function(v, value) { if (_.has(this._nodes, v)) { if (arguments.length > 1) { this._nodes[v] = value; } return this; } this._nodes[v] = arguments.length > 1 ? value : this._defaultNodeLabelFn(v); if (this._isCompound) { this._parent[v] = GRAPH_NODE; this._children[v] = {}; this._children[GRAPH_NODE][v] = true; } this._in[v] = {}; this._preds[v] = {}; this._out[v] = {}; this._sucs[v] = {}; ++this._nodeCount; return this; }; Graph.prototype.node = function(v) { return this._nodes[v]; }; Graph.prototype.hasNode = function(v) { return _.has(this._nodes, v); }; Graph.prototype.removeNode = function(v) { var self = this; if (_.has(this._nodes, v)) { var removeEdge = function(e) { self.removeEdge(self._edgeObjs[e]); }; delete this._nodes[v]; if (this._isCompound) { this._removeFromParentsChildList(v); delete this._parent[v]; _.each(this.children(v), function(child) { self.setParent(child); }); delete this._children[v]; } _.each(_.keys(this._in[v]), removeEdge); delete this._in[v]; delete this._preds[v]; _.each(_.keys(this._out[v]), removeEdge); delete this._out[v]; delete this._sucs[v]; --this._nodeCount; } return this; }; Graph.prototype.setParent = function(v, parent) { if (!this._isCompound) { throw new Error("Cannot set parent in a non-compound graph"); } if (_.isUndefined(parent)) { parent = GRAPH_NODE; } else { // Coerce parent to string parent += ""; for (var ancestor = parent; !_.isUndefined(ancestor); ancestor = this.parent(ancestor)) { if (ancestor === v) { throw new Error("Setting " + parent+ " as parent of " + v + " would create a cycle"); } } this.setNode(parent); } this.setNode(v); this._removeFromParentsChildList(v); this._parent[v] = parent; this._children[parent][v] = true; return this; }; Graph.prototype._removeFromParentsChildList = function(v) { delete this._children[this._parent[v]][v]; }; Graph.prototype.parent = function(v) { if (this._isCompound) { var parent = this._parent[v]; if (parent !== GRAPH_NODE) { return parent; } } }; Graph.prototype.children = function(v) { if (_.isUndefined(v)) { v = GRAPH_NODE; } if (this._isCompound) { var children = this._children[v]; if (children) { return _.keys(children); } } else if (v === GRAPH_NODE) { return this.nodes(); } else if (this.hasNode(v)) { return []; } }; Graph.prototype.predecessors = function(v) { var predsV = this._preds[v]; if (predsV) { return _.keys(predsV); } }; Graph.prototype.successors = function(v) { var sucsV = this._sucs[v]; if (sucsV) { return _.keys(sucsV); } }; Graph.prototype.neighbors = function(v) { var preds = this.predecessors(v); if (preds) { return _.union(preds, this.successors(v)); } }; Graph.prototype.isLeaf = function (v) { var neighbors; if (this.isDirected()) { neighbors = this.successors(v); } else { neighbors = this.neighbors(v); } return neighbors.length === 0; }; Graph.prototype.filterNodes = function(filter) { var copy = new this.constructor({ directed: this._isDirected, multigraph: this._isMultigraph, compound: this._isCompound }); copy.setGraph(this.graph()); var self = this; _.each(this._nodes, function(value, v) { if (filter(v)) { copy.setNode(v, value); } }); _.each(this._edgeObjs, function(e) { if (copy.hasNode(e.v) && copy.hasNode(e.w)) { copy.setEdge(e, self.edge(e)); } }); var parents = {}; function findParent(v) { var parent = self.parent(v); if (parent === undefined || copy.hasNode(parent)) { parents[v] = parent; return parent; } else if (parent in parents) { return parents[parent]; } else { return findParent(parent); } } if (this._isCompound) { _.each(copy.nodes(), function(v) { copy.setParent(v, findParent(v)); }); } return copy; }; /* === Edge functions ========== */ Graph.prototype.setDefaultEdgeLabel = function(newDefault) { if (!_.isFunction(newDefault)) { newDefault = _.constant(newDefault); } this._defaultEdgeLabelFn = newDefault; return this; }; Graph.prototype.edgeCount = function() { return this._edgeCount; }; Graph.prototype.edges = function() { return _.values(this._edgeObjs); }; Graph.prototype.setPath = function(vs, value) { var self = this; var args = arguments; _.reduce(vs, function(v, w) { if (args.length > 1) { self.setEdge(v, w, value); } else { self.setEdge(v, w); } return w; }); return this; }; /* * setEdge(v, w, [value, [name]]) * setEdge({ v, w, [name] }, [value]) */ Graph.prototype.setEdge = function() { var v, w, name, value; var valueSpecified = false; var arg0 = arguments[0]; if (typeof arg0 === "object" && arg0 !== null && "v" in arg0) { v = arg0.v; w = arg0.w; name = arg0.name; if (arguments.length === 2) { value = arguments[1]; valueSpecified = true; } } else { v = arg0; w = arguments[1]; name = arguments[3]; if (arguments.length > 2) { value = arguments[2]; valueSpecified = true; } } v = "" + v; w = "" + w; if (!_.isUndefined(name)) { name = "" + name; } var e = edgeArgsToId(this._isDirected, v, w, name); if (_.has(this._edgeLabels, e)) { if (valueSpecified) { this._edgeLabels[e] = value; } return this; } if (!_.isUndefined(name) && !this._isMultigraph) { throw new Error("Cannot set a named edge when isMultigraph = false"); } // It didn't exist, so we need to create it. // First ensure the nodes exist. this.setNode(v); this.setNode(w); this._edgeLabels[e] = valueSpecified ? value : this._defaultEdgeLabelFn(v, w, name); var edgeObj = edgeArgsToObj(this._isDirected, v, w, name); // Ensure we add undirected edges in a consistent way. v = edgeObj.v; w = edgeObj.w; Object.freeze(edgeObj); this._edgeObjs[e] = edgeObj; incrementOrInitEntry(this._preds[w], v); incrementOrInitEntry(this._sucs[v], w); this._in[w][e] = edgeObj; this._out[v][e] = edgeObj; this._edgeCount++; return this; }; Graph.prototype.edge = function(v, w, name) { var e = (arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name)); return this._edgeLabels[e]; }; Graph.prototype.hasEdge = function(v, w, name) { var e = (arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name)); return _.has(this._edgeLabels, e); }; Graph.prototype.removeEdge = function(v, w, name) { var e = (arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name)); var edge = this._edgeObjs[e]; if (edge) { v = edge.v; w = edge.w; delete this._edgeLabels[e]; delete this._edgeObjs[e]; decrementOrRemoveEntry(this._preds[w], v); decrementOrRemoveEntry(this._sucs[v], w); delete this._in[w][e]; delete this._out[v][e]; this._edgeCount--; } return this; }; Graph.prototype.inEdges = function(v, u) { var inV = this._in[v]; if (inV) { var edges = _.values(inV); if (!u) { return edges; } return _.filter(edges, function(edge) { return edge.v === u; }); } }; Graph.prototype.outEdges = function(v, w) { var outV = this._out[v]; if (outV) { var edges = _.values(outV); if (!w) { return edges; } return _.filter(edges, function(edge) { return edge.w === w; }); } }; Graph.prototype.nodeEdges = function(v, w) { var inEdges = this.inEdges(v, w); if (inEdges) { return inEdges.concat(this.outEdges(v, w)); } }; function incrementOrInitEntry(map, k) { if (map[k]) { map[k]++; } else { map[k] = 1; } } function decrementOrRemoveEntry(map, k) { if (!--map[k]) { delete map[k]; } } function edgeArgsToId(isDirected, v_, w_, name) { var v = "" + v_; var w = "" + w_; if (!isDirected && v > w) { var tmp = v; v = w; w = tmp; } return v + EDGE_KEY_DELIM + w + EDGE_KEY_DELIM + (_.isUndefined(name) ? DEFAULT_EDGE_NAME : name); } function edgeArgsToObj(isDirected, v_, w_, name) { var v = "" + v_; var w = "" + w_; if (!isDirected && v > w) { var tmp = v; v = w; w = tmp; } var edgeObj = { v: v, w: w }; if (name) { edgeObj.name = name; } return edgeObj; } function edgeObjToId(isDirected, edgeObj) { return edgeArgsToId(isDirected, edgeObj.v, edgeObj.w, edgeObj.name); } /***/ }), /***/ 19943: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Includes only the "core" of graphlib module.exports = { Graph: __webpack_require__(6583), version: __webpack_require__(79554) }; /***/ }), /***/ 40584: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var _ = __webpack_require__(8570); var Graph = __webpack_require__(6583); module.exports = { write: write, read: read }; function write(g) { var json = { options: { directed: g.isDirected(), multigraph: g.isMultigraph(), compound: g.isCompound() }, nodes: writeNodes(g), edges: writeEdges(g) }; if (!_.isUndefined(g.graph())) { json.value = _.clone(g.graph()); } return json; } function writeNodes(g) { return _.map(g.nodes(), function(v) { var nodeValue = g.node(v); var parent = g.parent(v); var node = { v: v }; if (!_.isUndefined(nodeValue)) { node.value = nodeValue; } if (!_.isUndefined(parent)) { node.parent = parent; } return node; }); } function writeEdges(g) { return _.map(g.edges(), function(e) { var edgeValue = g.edge(e); var edge = { v: e.v, w: e.w }; if (!_.isUndefined(e.name)) { edge.name = e.name; } if (!_.isUndefined(edgeValue)) { edge.value = edgeValue; } return edge; }); } function read(json) { var g = new Graph(json.options).setGraph(json.value); _.each(json.nodes, function(entry) { g.setNode(entry.v, entry.value); if (entry.parent) { g.setParent(entry.v, entry.parent); } }); _.each(json.edges, function(entry) { g.setEdge({ v: entry.v, w: entry.w, name: entry.name }, entry.value); }); return g; } /***/ }), /***/ 8570: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // eslint-disable-next-line no-redeclare /* global window */ var lodash; if (true) { try { lodash = { clone: __webpack_require__(33543), constant: __webpack_require__(4254), each: __webpack_require__(43590), filter: __webpack_require__(4474), has: __webpack_require__(38394), isArray: Array.isArray, isEmpty: __webpack_require__(99245), isFunction: __webpack_require__(98423), isUndefined: __webpack_require__(28801), keys: __webpack_require__(44799), map: __webpack_require__(80820), reduce: __webpack_require__(34766), size: __webpack_require__(27946), transform: __webpack_require__(10684), union: __webpack_require__(96744), values: __webpack_require__(17720) }; } catch (e) { // continue regardless of error } } if (!lodash) { lodash = window._; } module.exports = lodash; /***/ }), /***/ 79554: /***/ ((module) => { module.exports = '2.1.9-patch.3'; /***/ }), /***/ 59468: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildDepGraphs = void 0; const dep_graph_1 = __webpack_require__(74565); const out_of_sync_error_1 = __webpack_require__(71757); const is_dev_dependency_1 = __webpack_require__(92700); const get_non_hex_version_1 = __webpack_require__(3749); function buildDepGraphs(mixJsonResult, includeDev = false, strict = true, allProjects = false) { const manifest = mixJsonResult === null || mixJsonResult === void 0 ? void 0 : mixJsonResult.manifest; if (!manifest) throw new Error('No manifest found'); const lock = mixJsonResult.lock[0]; if (!lock) throw new Error('No lock file found'); const lockDepMap = Object.entries(lock).reduce((acc, [key, dep]) => { const [packageManager, name, version, hash, , dependencies] = dep; acc[key] = { packageManager, name, version, hash, dependencies, }; return acc; }, {}); if (mixJsonResult.parent_umbrella_manifest) { const umbrella = mixJsonResult.parent_umbrella_manifest; const prefix = `${getManifestName(umbrella)}/${umbrella.apps_path}/`; const name = `${umbrella.apps_path}/${getManifestName(manifest)}`; return { [name]: getDepGraph(prefix, manifest, includeDev, lockDepMap, strict), }; } const apps = allProjects || isEmpty(mixJsonResult.apps) ? {} : mixJsonResult.apps; const projects = { root: manifest, ...apps }; const appsPrefix = `${getManifestName(manifest)}/${manifest.apps_path}/`; return Object.entries(projects).reduce((acc, [key, manifest]) => { const prefix = key === 'root' ? '' : appsPrefix; acc[key] = getDepGraph(prefix, manifest, includeDev, lockDepMap, strict); return acc; }, {}); } exports.buildDepGraphs = buildDepGraphs; function isEmpty(obj) { return !obj || Object.keys(obj).length === 0; } function getDepGraph(prefix, manifest, includeDev, lockDepMap, strict) { const builder = new dep_graph_1.DepGraphBuilder({ name: 'hex' }, getRootPkg(prefix, manifest)); if (!manifest.deps) return builder.build(); const transitivesQueue = []; const deps = getTopLevelDeps(manifest); for (const topLevelDep of deps) { // eslint-disable-next-line prefer-const let [depName, depVersionSpec, options] = topLevelDep; if (typeof depVersionSpec === 'object') { options = depVersionSpec; depVersionSpec = undefined; } const isDev = is_dev_dependency_1.isDevDependency(options); if (!includeDev && isDev) continue; const scope = isDev ? 'dev' : 'prod'; const parentNodeId = builder.rootNodeId; let dep = lockDepMap[depName]; let labels; if (!dep) { const nonHexVersion = get_non_hex_version_1.getNonHexVersion(options); if (!nonHexVersion && strict) throw new out_of_sync_error_1.OutOfSyncError(depName); labels = { missingLockFileEntry: 'true', ...((nonHexVersion === null || nonHexVersion === void 0 ? void 0 : nonHexVersion.labels) || {}), }; dep = { name: depName, version: (nonHexVersion === null || nonHexVersion === void 0 ? void 0 : nonHexVersion.title) || depVersionSpec }; } transitivesQueue.push({ dep, parentNodeId, scope, labels }); } while (transitivesQueue.length > 0) { const { dep, parentNodeId, scope, labels } = transitivesQueue.shift(); const nodeId = addNode(dep.name, dep.version, scope, labels); builder.connectDep(parentNodeId, nodeId); if (!dep.dependencies) continue; for (const [childName, , childOptions] of dep.dependencies) { const lockDep = lockDepMap[childName]; if (!lockDep && childOptions && !childOptions.optional) throw new out_of_sync_error_1.OutOfSyncError(childName); else if (!lockDep) continue; transitivesQueue.push({ parentNodeId: nodeId, dep: lockDep, scope }); } } return builder.build(); function addNode(name, version, scope, labels) { const nodeInfo = { labels: { scope, ...(labels || {}), }, }; const nodeId = `${name}@${version || ''}`; builder.addPkgNode({ name, version }, nodeId, nodeInfo); return nodeId; } } function getRootPkg(prefix, manifest) { const name = getManifestName(manifest); return { name: `${prefix}${name}`, version: manifest.version || '0.0.0' }; } function getManifestName(manifest) { var _a; return (manifest.app || ((_a = manifest.module_name) === null || _a === void 0 ? void 0 : _a.replace(/\.Mix\w{4,}$/, '').toLowerCase()) || 'no_name'); } function getTopLevelDeps(manifest) { return Array.isArray(manifest.deps) ? manifest.deps : Object.entries(manifest.deps).map(([key, value]) => Array.isArray(value) ? [key, ...value] : [key, value]); } //# sourceMappingURL=build-dep-graphs.js.map /***/ }), /***/ 3749: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getNonHexVersion = void 0; const PATH_OPTION_PROPS = ['path', 'in_umbrella']; const GIT_OPTION_PROPS = [ 'git', 'github', 'ref', 'branch', 'tag', 'submodules', 'sparse', ]; function getNonHexVersion(options) { if (hasPathOptionProps(options)) return generatePathDepVersion(options); else if (hasGitOptionProps(options)) return generateGitDepVersion(options); } exports.getNonHexVersion = getNonHexVersion; function hasPathOptionProps(options) { return PATH_OPTION_PROPS.some((key) => options === null || options === void 0 ? void 0 : options[key]); } function generatePathDepVersion(options) { if (options.in_umbrella) return { title: 'in_umbrella', labels: {} }; else if (options.path) return { title: 'path', labels: { path: options.path } }; } function hasGitOptionProps(options) { return GIT_OPTION_PROPS.some((key) => options === null || options === void 0 ? void 0 : options[key]); } function generateGitDepVersion(options) { const gitAddress = options.github ? `https://github.com/${options.github}.git` : options.git; const ref = options.branch || options.tag || options.ref || 'HEAD'; const title = `${gitAddress}@${ref}`; const labels = {}; for (const prop of GIT_OPTION_PROPS) { if (!options[prop]) continue; labels[prop] = options[prop]; } return { title, labels }; } //# sourceMappingURL=get-non-hex-version.js.map /***/ }), /***/ 72559: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); var build_dep_graphs_1 = __webpack_require__(59468); Object.defineProperty(exports, "buildDepGraphs", ({ enumerable: true, get: function () { return build_dep_graphs_1.buildDepGraphs; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 92700: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isDevDependency = void 0; /* * A dependency can be a limited to more than one environment (i.e. :dev and :test) * The logic to decide the scope (dev/prod): * If the dependency is not whitelisted, or if :prod is in the `only` whitelist, we consider it as a prod dependency * Otherwise it's a dev dependency. * */ function isDevDependency(options) { if (!options || !options.only) return false; const envs = Array.isArray(options.only) ? options.only : [options.only]; return envs.every((env) => env !== 'prod'); } exports.isDevDependency = isDevDependency; //# sourceMappingURL=is-dev-dependency.js.map /***/ }), /***/ 71757: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.OutOfSyncError = void 0; class OutOfSyncError extends Error { constructor(dependencyName) { super(`Dependency ${dependencyName} was not found in ` + `mix.lock. Your mix.exs and ` + `mix.lock are probably out of sync. Please run ` + `"mix deps.get" and try again.`); this.name = 'OutOfSyncError'; this.dependencyName = dependencyName; Error.captureStackTrace(this, OutOfSyncError); } } exports.OutOfSyncError = OutOfSyncError; //# sourceMappingURL=out-of-sync-error.js.map /***/ }), /***/ 77697: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DepGraphBuilder = void 0; const graphlib = __webpack_require__(76830); const dep_graph_1 = __webpack_require__(82519); class DepGraphBuilder { constructor(pkgManager, rootPkg) { this._pkgs = {}; this._pkgNodes = {}; const graph = new graphlib.Graph({ directed: true, multigraph: false, compound: false, }); if (!rootPkg) { rootPkg = { name: '_root', version: '0.0.0', }; } this._rootNodeId = 'root-node'; this._rootPkgId = DepGraphBuilder._getPkgId(rootPkg); this._pkgs[this._rootPkgId] = rootPkg; graph.setNode(this._rootNodeId, { pkgId: this._rootPkgId }); this._pkgNodes[this._rootPkgId] = new Set([this._rootNodeId]); this._graph = graph; this._pkgManager = pkgManager; } get rootNodeId() { return this._rootNodeId; } static _getPkgId(pkg) { return `${pkg.name}@${pkg.version || ''}`; } getPkgs() { return Object.values(this._pkgs); } // TODO: this can create disconnected nodes addPkgNode(pkgInfo, nodeId, nodeInfo) { if (nodeId === this._rootNodeId) { throw new Error('DepGraphBuilder.addPkgNode() cant override root node'); } const pkgId = DepGraphBuilder._getPkgId(pkgInfo); this._pkgs[pkgId] = pkgInfo; this._pkgNodes[pkgId] = this._pkgNodes[pkgId] || new Set(); this._pkgNodes[pkgId].add(nodeId); this._graph.setNode(nodeId, { pkgId, info: nodeInfo }); return this; } // TODO: this can create cycles connectDep(parentNodeId, depNodeId) { if (!this._graph.hasNode(parentNodeId)) { throw new Error('parentNodeId does not exist'); } if (!this._graph.hasNode(depNodeId)) { throw new Error('depNodeId does not exist'); } this._graph.setEdge(parentNodeId, depNodeId); return this; } build() { return new dep_graph_1.DepGraphImpl(this._graph, this._rootNodeId, this._pkgs, this._pkgNodes, this._pkgManager); } } exports.DepGraphBuilder = DepGraphBuilder; //# sourceMappingURL=builder.js.map /***/ }), /***/ 5506: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createFromJSON = exports.SUPPORTED_SCHEMA_RANGE = void 0; const semver = __webpack_require__(8095); const graphlib = __webpack_require__(76830); const errors_1 = __webpack_require__(27477); const validate_graph_1 = __webpack_require__(42302); const dep_graph_1 = __webpack_require__(82519); exports.SUPPORTED_SCHEMA_RANGE = '^1.0.0'; /** * Create a DepGraph instance from a JSON representation of a dep graph. This * is typically used after passing the graph over the wire as `DepGraphData`. */ function createFromJSON(depGraphData) { validateDepGraphData(depGraphData); const graph = new graphlib.Graph({ directed: true, multigraph: false, compound: false, }); const pkgs = {}; const pkgNodes = {}; for (const { id, info } of depGraphData.pkgs) { pkgs[id] = info.version ? info : Object.assign(Object.assign({}, info), { version: undefined }); } for (const node of depGraphData.graph.nodes) { const pkgId = node.pkgId; if (!pkgNodes[pkgId]) { pkgNodes[pkgId] = new Set(); } pkgNodes[pkgId].add(node.nodeId); graph.setNode(node.nodeId, { pkgId, info: node.info }); } for (const node of depGraphData.graph.nodes) { for (const depNodeId of node.deps) { graph.setEdge(node.nodeId, depNodeId.nodeId); } } validate_graph_1.validateGraph(graph, depGraphData.graph.rootNodeId, pkgs, pkgNodes); return new dep_graph_1.DepGraphImpl(graph, depGraphData.graph.rootNodeId, pkgs, pkgNodes, depGraphData.pkgManager); } exports.createFromJSON = createFromJSON; function assert(condition, msg) { if (!condition) { throw new errors_1.ValidationError(msg); } } function validateDepGraphData(depGraphData) { assert(!!semver.valid(depGraphData.schemaVersion) && semver.satisfies(depGraphData.schemaVersion, exports.SUPPORTED_SCHEMA_RANGE), `dep-graph schemaVersion not in "${exports.SUPPORTED_SCHEMA_RANGE}"`); assert(depGraphData.pkgManager && !!depGraphData.pkgManager.name, '.pkgManager.name is missing'); const pkgsMap = depGraphData.pkgs.reduce((acc, cur) => { assert(!(cur.id in acc), 'more than one pkg with same id'); assert(!!cur.info, '.pkgs item missing .info'); acc[cur.id] = cur.info; return acc; }, {}); const nodesMap = depGraphData.graph.nodes.reduce((acc, cur) => { assert(!(cur.nodeId in acc), 'more than on node with same id'); acc[cur.nodeId] = cur; return acc; }, {}); const rootNodeId = depGraphData.graph.rootNodeId; const rootNode = nodesMap[rootNodeId]; assert(rootNodeId in nodesMap, `.${rootNodeId} root graph node is missing`); const rootPkgId = rootNode.pkgId; assert(rootPkgId in pkgsMap, `.${rootPkgId} root pkg missing`); assert(nodesMap[rootNodeId].pkgId === rootPkgId, `the root node .pkgId should be "${rootPkgId}"`); const pkgIds = Object.keys(pkgsMap); // NOTE: this name@version check is very strict, // we can relax it later, it just makes things easier now assert(pkgIds.filter((pkgId) => pkgId !== dep_graph_1.DepGraphImpl.getPkgId(pkgsMap[pkgId])) .length === 0, 'pkgs ids should be name@version'); assert(Object.values(nodesMap).filter((node) => !(node.pkgId in pkgsMap)) .length === 0, 'some instance nodes belong to non-existing pkgIds'); assert(Object.values(pkgsMap).filter((pkg) => !pkg.name) .length === 0, 'some .pkgs elements have no .name field'); } //# sourceMappingURL=create-from-json.js.map /***/ }), /***/ 82519: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DepGraphImpl = void 0; const _isEqual = __webpack_require__(72307); const graphlib = __webpack_require__(76830); const create_from_json_1 = __webpack_require__(5506); class DepGraphImpl { constructor(_graph, _rootNodeId, _pkgs, _pkgNodes, _pkgManager) { this._graph = _graph; this._rootNodeId = _rootNodeId; this._pkgs = _pkgs; this._pkgNodes = _pkgNodes; this._pkgManager = _pkgManager; this._countNodePathsToRootCache = new Map(); this._rootPkgId = _graph.node(_rootNodeId).pkgId; this._pkgList = Object.values(_pkgs); this._depPkgsList = this._pkgList.filter((pkg) => pkg !== this.rootPkg); } static getPkgId(pkg) { return `${pkg.name}@${pkg.version || ''}`; } get pkgManager() { return this._pkgManager; } get rootPkg() { return this._pkgs[this._rootPkgId]; } get rootNodeId() { return this._rootNodeId; } /** * Get all unique packages in the graph (including the root package) */ getPkgs() { return this._pkgList; } /** * Get all unique packages in the graph (excluding the root package) */ getDepPkgs() { return this._depPkgsList; } getPkgNodes(pkg) { const pkgId = DepGraphImpl.getPkgId(pkg); const nodes = []; for (const nodeId of Array.from(this._pkgNodes[pkgId])) { const graphNode = this.getGraphNode(nodeId); nodes.push({ info: graphNode.info || {}, }); } return nodes; } getNode(nodeId) { return this.getGraphNode(nodeId).info || {}; } getNodePkg(nodeId) { return this._pkgs[this.getGraphNode(nodeId).pkgId]; } getPkgNodeIds(pkg) { const pkgId = DepGraphImpl.getPkgId(pkg); if (!this._pkgs[pkgId]) { throw new Error(`no such pkg: ${pkgId}`); } return Array.from(this._pkgNodes[pkgId]); } getNodeDepsNodeIds(nodeId) { const deps = this._graph.successors(nodeId); if (!deps) { throw new Error(`no such node: ${nodeId}`); } return deps; } getNodeParentsNodeIds(nodeId) { const parents = this._graph.predecessors(nodeId); if (!parents) { throw new Error(`no such node: ${nodeId}`); } return parents; } hasCycles() { // `isAcyclic` is expensive, so memoize if (this._hasCycles === undefined) { this._hasCycles = !graphlib.alg.isAcyclic(this._graph); } return this._hasCycles; } pkgPathsToRoot(pkg, opts) { const pathsToRoot = []; const limit = opts === null || opts === void 0 ? void 0 : opts.limit; for (const nodeId of this.getPkgNodeIds(pkg)) { const pathsFromNodeToRoot = this.pathsFromNodeToRoot(nodeId, [], { limit, }); for (const path of pathsFromNodeToRoot) { pathsToRoot.push(path); } if (limit && pathsToRoot.length >= limit) { break; } } // note: sorting to get shorter paths first - // it's nicer - and better resembles older behaviour return pathsToRoot.sort((a, b) => a.length - b.length); } countPathsToRoot(pkg) { let count = 0; for (const nodeId of this.getPkgNodeIds(pkg)) { count += this.countNodePathsToRoot(nodeId); } return count; } equals(other, { compareRoot = true } = {}) { let otherDepGraph; if (other instanceof DepGraphImpl) { otherDepGraph = other; } else { // At runtime theoretically we can have multiple versions of // @snyk/dep-graph. If "other" is not an instance of the same class it is // safer to rebuild it from JSON. otherDepGraph = create_from_json_1.createFromJSON(other.toJSON()); } // In theory, for the graphs created by standard means, `_.isEquals(this._data, otherDepGraph._data)` // should suffice, since node IDs will be generated in a predictable way. // However, there might be different versions of graph and inconsistencies // in the ordering of the arrays, so we perform a deep comparison. return this.nodeEquals(this, this.rootNodeId, otherDepGraph, otherDepGraph.rootNodeId, compareRoot); } directDepsLeadingTo(pkg) { const pkgNodes = this.getPkgNodeIds(pkg); const directDeps = this.getNodeDepsNodeIds(this.rootNodeId); const nodes = directDeps.filter((directDep) => { const reachableNodes = graphlib.alg.postorder(this._graph, [directDep]); return reachableNodes.filter((node) => pkgNodes.includes(node)).length; }); return nodes.map((node) => this.getNodePkg(node)); } /** * Create a JSON representation of a dep graph. This is typically used to * send the dep graph over the wire */ toJSON() { const nodeIds = this._graph.nodes(); const nodes = nodeIds.reduce((acc, nodeId) => { const deps = (this._graph.successors(nodeId) || []).map((depNodeId) => ({ nodeId: depNodeId, })); const node = this._graph.node(nodeId); const elem = { nodeId, pkgId: node.pkgId, deps, }; if (node.info && Object.keys(node.info).length > 0) { elem.info = node.info; } acc.push(elem); return acc; }, []); const pkgs = Object.keys(this._pkgs).map((pkgId) => ({ id: pkgId, info: this._pkgs[pkgId], })); return { schemaVersion: DepGraphImpl.SCHEMA_VERSION, pkgManager: this._pkgManager, pkgs, graph: { rootNodeId: this._rootNodeId, nodes, }, }; } nodeEquals(graphA, nodeIdA, graphB, nodeIdB, compareRoot, traversedPairs = new Set()) { // Skip root nodes comparision if needed. if (compareRoot || (nodeIdA !== graphA.rootNodeId && nodeIdB !== graphB.rootNodeId)) { const pkgA = graphA.getNodePkg(nodeIdA); const pkgB = graphB.getNodePkg(nodeIdB); // Compare PkgInfo (name and version). if (!_isEqual(pkgA, pkgB)) { return false; } const infoA = graphA.getNode(nodeIdA); const infoB = graphB.getNode(nodeIdB); // Compare NodeInfo (VersionProvenance and labels). if (!_isEqual(infoA, infoB)) { return false; } } let depsA = graphA.getNodeDepsNodeIds(nodeIdA); let depsB = graphB.getNodeDepsNodeIds(nodeIdB); // Number of dependencies should be the same. if (depsA.length !== depsB.length) { return false; } // Sort dependencies by name@version string. const sortFn = (graph) => (idA, idB) => { const pkgA = graph.getNodePkg(idA); const pkgB = graph.getNodePkg(idB); return DepGraphImpl.getPkgId(pkgA).localeCompare(DepGraphImpl.getPkgId(pkgB)); }; depsA = depsA.sort(sortFn(graphA)); depsB = depsB.sort(sortFn(graphB)); // Compare Each dependency recursively. for (let i = 0; i < depsA.length; i++) { const pairKey = `${depsA[i]}_${depsB[i]}`; // Prevent cycles. if (traversedPairs.has(pairKey)) { continue; } traversedPairs.add(pairKey); if (!this.nodeEquals(graphA, depsA[i], graphB, depsB[i], compareRoot, traversedPairs)) { return false; } } return true; } getGraphNode(nodeId) { const node = this._graph.node(nodeId); if (!node) { throw new Error(`no such node: ${nodeId}`); } return node; } pathsFromNodeToRoot(nodeId, ancestors = [], opts) { const parentNodesIds = this.getNodeParentsNodeIds(nodeId); const pkgInfo = this.getNodePkg(nodeId); if (parentNodesIds.length === 0) { return [[pkgInfo]]; } const allPaths = []; ancestors = ancestors.concat(nodeId); const limit = opts.limit; for (const id of parentNodesIds) { if (ancestors.includes(id)) continue; const pathsFromNodeToRoot = this.pathsFromNodeToRoot(id, ancestors, opts); pathsFromNodeToRoot.forEach((path) => allPaths.push([pkgInfo].concat(path))); if (limit && allPaths.length >= limit) { break; } } return allPaths; } countNodePathsToRoot(nodeId, ancestors = []) { if (ancestors.includes(nodeId)) { return 0; } if (this._countNodePathsToRootCache.has(nodeId)) { return this._countNodePathsToRootCache.get(nodeId) || 0; } const parentNodesIds = this.getNodeParentsNodeIds(nodeId); if (parentNodesIds.length === 0) { this._countNodePathsToRootCache.set(nodeId, 1); return 1; } ancestors = ancestors.concat(nodeId); const count = parentNodesIds.reduce((acc, parentNodeId) => { return acc + this.countNodePathsToRoot(parentNodeId, ancestors); }, 0); this._countNodePathsToRootCache.set(nodeId, count); return count; } } exports.DepGraphImpl = DepGraphImpl; DepGraphImpl.SCHEMA_VERSION = '1.2.0'; //# sourceMappingURL=dep-graph.js.map /***/ }), /***/ 83229: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CustomError = void 0; class CustomError extends Error { constructor(message) { super(message); Object.setPrototypeOf(this, CustomError.prototype); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; } } exports.CustomError = CustomError; //# sourceMappingURL=custom-error.js.map /***/ }), /***/ 27477: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ValidationError = void 0; const validation_error_1 = __webpack_require__(93866); Object.defineProperty(exports, "ValidationError", ({ enumerable: true, get: function () { return validation_error_1.ValidationError; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 93866: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ValidationError = void 0; const custom_error_1 = __webpack_require__(83229); class ValidationError extends custom_error_1.CustomError { constructor(message) { super(message); Object.setPrototypeOf(this, ValidationError.prototype); } } exports.ValidationError = ValidationError; //# sourceMappingURL=validation-error.js.map /***/ }), /***/ 42302: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.validateGraph = void 0; const graphlib = __webpack_require__(76830); const errors_1 = __webpack_require__(27477); function assert(condition, msg) { if (!condition) { throw new errors_1.ValidationError(msg); } } function validateGraph(graph, rootNodeId, pkgs, pkgNodes) { assert((graph.predecessors(rootNodeId) || []).length === 0, `"${rootNodeId}" is not really the root`); const reachableFromRoot = graphlib.alg.postorder(graph, [rootNodeId]); const nodeIds = graph.nodes(); assert(JSON.stringify(nodeIds.sort()) === JSON.stringify(reachableFromRoot.sort()), 'not all graph nodes are reachable from root'); const pkgIds = Object.keys(pkgs); const pkgsWithoutInstances = pkgIds.filter((pkgId) => !pkgNodes[pkgId] || pkgNodes[pkgId].size === 0); assert(pkgsWithoutInstances.length === 0, 'not all pkgs have instance nodes'); } exports.validateGraph = validateGraph; //# sourceMappingURL=validate-graph.js.map /***/ }), /***/ 8045: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.dfs = void 0; const each = __webpack_require__(43590); /* * A helper that preforms a pre- or post-order traversal on the input graph * and returns the nodes in the order they were visited. If the graph is * undirected then this algorithm will navigate using neighbors. If the graph * is directed then this algorithm will navigate using successors. * * Order must be one of "pre" or "post". */ function dfs(g, vs, order) { if (!Array.isArray(vs)) { vs = [vs]; } const navigation = (g.isDirected() ? g.successors : g.neighbors).bind(g); const acc = []; const visited = {}; each(vs, (v) => { if (!g.hasNode(v)) { throw new Error('Graph does not have node: ' + v); } doDfs(g, v, order === 'post', visited, navigation, acc); }); return acc; } exports.dfs = dfs; function doDfs(g, v, postorder, visited, navigation, acc) { if (!(v in visited)) { visited[v] = true; if (!postorder) { acc.push(v); } each(navigation(v), function (w) { doDfs(g, w, postorder, visited, navigation, acc); }); if (postorder) { acc.push(v); } } } //# sourceMappingURL=dfs.js.map /***/ }), /***/ 46548: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isAcyclic = void 0; const topsort_1 = __webpack_require__(49881); function isAcyclic(g) { try { topsort_1.topsort(g); } catch (e) { if (e instanceof topsort_1.CycleException) { return false; } throw e; } return true; } exports.isAcyclic = isAcyclic; //# sourceMappingURL=is-acyclic.js.map /***/ }), /***/ 28740: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.postorder = void 0; const dfs_1 = __webpack_require__(8045); function postorder(g, vs) { return dfs_1.dfs(g, vs, 'post'); } exports.postorder = postorder; //# sourceMappingURL=postorder.js.map /***/ }), /***/ 49881: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CycleException = exports.topsort = void 0; const each = __webpack_require__(43590); const size = __webpack_require__(27946); function topsort(g) { const visited = {}; const stack = {}; const results = []; function visit(node) { if (node in stack) { throw new CycleException(); } if (!(node in visited)) { stack[node] = true; visited[node] = true; each(g.predecessors(node), visit); delete stack[node]; results.push(node); } } each(g.sinks(), visit); if (size(visited) !== g.nodeCount()) { throw new CycleException(); } return results; } exports.topsort = topsort; class CycleException extends Error { } exports.CycleException = CycleException; //# sourceMappingURL=topsort.js.map /***/ }), /***/ 62556: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Graph = void 0; /* eslint-disable prefer-rest-params */ /* eslint-disable @typescript-eslint/no-this-alias */ const constant = __webpack_require__(4254); const each = __webpack_require__(43590); const _filter = __webpack_require__(43590); const isEmpty = __webpack_require__(99245); const isFunction = __webpack_require__(98423); const isUndefined = __webpack_require__(28801); const keys = __webpack_require__(44799); const reduce = __webpack_require__(34766); const union = __webpack_require__(96744); const values = __webpack_require__(17720); const DEFAULT_EDGE_NAME = '\x00'; const GRAPH_NODE = '\x00'; const EDGE_KEY_DELIM = '\x01'; // Implementation notes: // // * Node id query functions should return string ids for the nodes // * Edge id query functions should return an "edgeObj", edge object, that is // composed of enough information to uniquely identify an edge: {v, w, name}. // * Internally we use an "edgeId", a stringified form of the edgeObj, to // reference edges. This is because we need a performant way to look these // edges up and, object properties, which have string keys, are the closest // we're going to get to a performant hashtable in JavaScript. class Graph { constructor(opts) { var _a, _b, _c; /* Number of nodes in the graph. Should only be changed by the implementation. */ this._nodeCount = 0; /* Number of edges in the graph. Should only be changed by the implementation. */ this._edgeCount = 0; this._isDirected = (_a = opts === null || opts === void 0 ? void 0 : opts.directed) !== null && _a !== void 0 ? _a : true; this._isMultigraph = (_b = opts === null || opts === void 0 ? void 0 : opts.multigraph) !== null && _b !== void 0 ? _b : false; this._isCompound = (_c = opts === null || opts === void 0 ? void 0 : opts.compound) !== null && _c !== void 0 ? _c : false; // Label for the graph itself this._label = undefined; // Defaults to be set when creating a new node this._defaultNodeLabelFn = constant(undefined); // Defaults to be set when creating a new edge this._defaultEdgeLabelFn = constant(undefined); // v -> label this._nodes = {}; if (this._isCompound) { // v -> parent this._parent = {}; // v -> children this._children = {}; this._children[GRAPH_NODE] = {}; } // v -> edgeObj this._in = {}; // u -> v -> Number this._preds = {}; // v -> edgeObj this._out = {}; // v -> w -> Number this._sucs = {}; // e -> edgeObj this._edgeObjs = {}; // e -> label this._edgeLabels = {}; } /* === Graph functions ========= */ isDirected() { return this._isDirected; } isMultigraph() { return this._isMultigraph; } isCompound() { return this._isCompound; } setGraph(label) { this._label = label; return this; } graph() { return this._label; } /* === Node functions ========== */ setDefaultNodeLabel(newDefault) { if (!isFunction(newDefault)) { newDefault = constant(newDefault); } this._defaultNodeLabelFn = newDefault; return this; } nodeCount() { return this._nodeCount; } nodes() { return keys(this._nodes); } sources() { const self = this; return _filter(this.nodes(), function (v) { return isEmpty(self._in[v]); }); } sinks() { const self = this; return _filter(this.nodes(), function (v) { return isEmpty(self._out[v]); }); } setNodes(vs, value) { const args = arguments; const self = this; each(vs, function (v) { if (args.length > 1) { self.setNode(v, value); } else { self.setNode(v); } }); return this; } setNode(v, value) { if (v in this._nodes) { if (arguments.length > 1) { this._nodes[v] = value; } return this; } this._nodes[v] = arguments.length > 1 ? value : this._defaultNodeLabelFn(v); if (this._isCompound) { this._parent[v] = GRAPH_NODE; this._children[v] = {}; this._children[GRAPH_NODE][v] = true; } this._in[v] = {}; this._preds[v] = {}; this._out[v] = {}; this._sucs[v] = {}; ++this._nodeCount; return this; } node(v) { return this._nodes[v]; } hasNode(v) { return v in this._nodes; } removeNode(v) { const self = this; if (v in this._nodes) { const removeEdge = function (e) { self.removeEdge(self._edgeObjs[e]); }; delete this._nodes[v]; if (this._isCompound) { this._removeFromParentsChildList(v); delete this._parent[v]; each(this.children(v), function (child) { self.setParent(child); }); delete this._children[v]; } each(keys(this._in[v]), removeEdge); delete this._in[v]; delete this._preds[v]; each(keys(this._out[v]), removeEdge); delete this._out[v]; delete this._sucs[v]; --this._nodeCount; } return this; } setParent(v, parent) { if (!this._isCompound) { throw new Error('Cannot set parent in a non-compound graph'); } if (isUndefined(parent)) { parent = GRAPH_NODE; } else { // Coerce parent to string parent += ''; for (let ancestor = parent; !isUndefined(ancestor); ancestor = this.parent(ancestor)) { if (ancestor === v) { throw new Error('Setting ' + parent + ' as parent of ' + v + ' would create a cycle'); } } this.setNode(parent); } this.setNode(v); this._removeFromParentsChildList(v); this._parent[v] = parent; this._children[parent][v] = true; return this; } _removeFromParentsChildList(v) { delete this._children[this._parent[v]][v]; } parent(v) { if (this._isCompound) { const parent = this._parent[v]; if (parent !== GRAPH_NODE) { return parent; } } } children(v) { if (isUndefined(v)) { v = GRAPH_NODE; } if (this._isCompound) { const children = this._children[v]; if (children) { return keys(children); } } else if (v === GRAPH_NODE) { return this.nodes(); } else if (this.hasNode(v)) { return []; } } predecessors(v) { const predsV = this._preds[v]; if (predsV) { return keys(predsV); } } successors(v) { const sucsV = this._sucs[v]; if (sucsV) { return keys(sucsV); } } neighbors(v) { const preds = this.predecessors(v); if (preds) { return union(preds, this.successors(v)); } } isLeaf(v) { let neighbors; if (this.isDirected()) { neighbors = this.successors(v); } else { neighbors = this.neighbors(v); } return neighbors.length === 0; } filterNodes(filter) { const copy = new Graph({ directed: this._isDirected, multigraph: this._isMultigraph, compound: this._isCompound, }); copy.setGraph(this.graph()); const self = this; each(this._nodes, function (value, v) { if (filter(v)) { copy.setNode(v, value); } }); each(this._edgeObjs, function (e) { if (copy.hasNode(e.v) && copy.hasNode(e.w)) { copy.setEdge(e, self.edge(e)); } }); const parents = {}; function findParent(v) { const parent = self.parent(v); if (parent === undefined || copy.hasNode(parent)) { parents[v] = parent; return parent; } else if (parent in parents) { return parents[parent]; } else { return findParent(parent); } } if (this._isCompound) { each(copy.nodes(), function (v) { copy.setParent(v, findParent(v)); }); } return copy; } /* === Edge functions ========== */ setDefaultEdgeLabel(newDefault) { if (!isFunction(newDefault)) { newDefault = constant(newDefault); } this._defaultEdgeLabelFn = newDefault; return this; } edgeCount() { return this._edgeCount; } edges() { return values(this._edgeObjs); } setPath(vs, value) { const self = this; const args = arguments; reduce(vs, function (v, w) { if (args.length > 1) { self.setEdge(v, w, value); } else { self.setEdge(v, w); } return w; }); return this; } // eslint-disable-next-line @typescript-eslint/no-unused-vars setEdge(...args) { let v, w, name, value; let valueSpecified = false; const arg0 = arguments[0]; if (typeof arg0 === 'object' && arg0 !== null && 'v' in arg0) { v = arg0.v; w = arg0.w; name = arg0.name; if (arguments.length === 2) { value = arguments[1]; valueSpecified = true; } } else { v = arg0; w = arguments[1]; name = arguments[3]; if (arguments.length > 2) { value = arguments[2]; valueSpecified = true; } } v = '' + v; w = '' + w; if (!isUndefined(name)) { name = '' + name; } const e = edgeArgsToId(this._isDirected, v, w, name); if (e in this._edgeLabels) { if (valueSpecified) { this._edgeLabels[e] = value; } return this; } if (!isUndefined(name) && !this._isMultigraph) { throw new Error('Cannot set a named edge when isMultigraph = false'); } // It didn't exist, so we need to create it. // First ensure the nodes exist. this.setNode(v); this.setNode(w); this._edgeLabels[e] = valueSpecified ? value : this._defaultEdgeLabelFn(v, w, name); const edgeObj = edgeArgsToObj(this._isDirected, v, w, name); // Ensure we add undirected edges in a consistent way. v = edgeObj.v; w = edgeObj.w; Object.freeze(edgeObj); this._edgeObjs[e] = edgeObj; incrementOrInitEntry(this._preds[w], v); incrementOrInitEntry(this._sucs[v], w); this._in[w][e] = edgeObj; this._out[v][e] = edgeObj; this._edgeCount++; return this; } edge(v, w, name) { const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); return this._edgeLabels[e]; } hasEdge(v, w, name) { const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); return e in this._edgeLabels; } removeEdge(v, w, name) { const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); const edge = this._edgeObjs[e]; if (edge) { v = edge.v; w = edge.w; delete this._edgeLabels[e]; delete this._edgeObjs[e]; decrementOrRemoveEntry(this._preds[w], v); decrementOrRemoveEntry(this._sucs[v], w); delete this._in[w][e]; delete this._out[v][e]; this._edgeCount--; } return this; } inEdges(v, u) { const inV = this._in[v]; if (inV) { const edges = values(inV); if (!u) { return edges; } return _filter(edges, function (edge) { return edge.v === u; }); } } outEdges(v, w) { const outV = this._out[v]; if (outV) { const edges = values(outV); if (!w) { return edges; } return _filter(edges, function (edge) { return edge.w === w; }); } } nodeEdges(v, w) { const inEdges = this.inEdges(v, w); if (inEdges) { return inEdges.concat(this.outEdges(v, w)); } } } exports.Graph = Graph; function incrementOrInitEntry(map, k) { if (map[k]) { map[k]++; } else { map[k] = 1; } } function decrementOrRemoveEntry(map, k) { if (!--map[k]) { delete map[k]; } } function edgeArgsToId(isDirected, v_, w_, name) { let v = '' + v_; let w = '' + w_; if (!isDirected && v > w) { const tmp = v; v = w; w = tmp; } return (v + EDGE_KEY_DELIM + w + EDGE_KEY_DELIM + (isUndefined(name) ? DEFAULT_EDGE_NAME : name)); } function edgeArgsToObj(isDirected, v_, w_, name) { let v = '' + v_; let w = '' + w_; if (!isDirected && v > w) { const tmp = v; v = w; w = tmp; } const edgeObj = { v: v, w: w }; if (name) { edgeObj.name = name; } return edgeObj; } function edgeObjToId(isDirected, edgeObj) { return edgeArgsToId(isDirected, edgeObj.v, edgeObj.w, edgeObj.name); } //# sourceMappingURL=graph.js.map /***/ }), /***/ 76830: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.alg = exports.Graph = void 0; var graph_1 = __webpack_require__(62556); Object.defineProperty(exports, "Graph", ({ enumerable: true, get: function () { return graph_1.Graph; } })); const is_acyclic_1 = __webpack_require__(46548); const postorder_1 = __webpack_require__(28740); exports.alg = { isAcyclic: is_acyclic_1.isAcyclic, postorder: postorder_1.postorder, }; //# sourceMappingURL=index.js.map /***/ }), /***/ 74565: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.legacy = exports.Errors = exports.DepGraphBuilder = exports.createFromJSON = void 0; var create_from_json_1 = __webpack_require__(5506); Object.defineProperty(exports, "createFromJSON", ({ enumerable: true, get: function () { return create_from_json_1.createFromJSON; } })); var builder_1 = __webpack_require__(77697); Object.defineProperty(exports, "DepGraphBuilder", ({ enumerable: true, get: function () { return builder_1.DepGraphBuilder; } })); const Errors = __webpack_require__(27477); exports.Errors = Errors; const legacy = __webpack_require__(1547); exports.legacy = legacy; //# sourceMappingURL=index.js.map /***/ }), /***/ 18411: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.partitionCycles = exports.getCycle = void 0; function getCycle(ancestors, nodeId) { if (!ancestors.includes(nodeId)) { return null; } // first item is where the cycle starts and ends. return ancestors.slice(ancestors.indexOf(nodeId)); } exports.getCycle = getCycle; function partitionCycles(nodeId, allCyclesTheNodeIsPartOf) { const cyclesStartWithThisNode = []; const cyclesWithThisNode = []; for (const cycle of allCyclesTheNodeIsPartOf) { const nodeStartsCycle = cycle[0] === nodeId; if (nodeStartsCycle) { cyclesStartWithThisNode.push(cycle); } else { cyclesWithThisNode.push(cycle); } } return { cyclesStartWithThisNode, cyclesWithThisNode }; } exports.partitionCycles = partitionCycles; //# sourceMappingURL=cycles.js.map /***/ }), /***/ 1547: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.graphToDepTree = exports.depTreeToGraph = void 0; const crypto = __webpack_require__(6113); const event_loop_spinner_1 = __webpack_require__(77158); const builder_1 = __webpack_require__(77697); const objectHash = __webpack_require__(86422); const cycles_1 = __webpack_require__(18411); const memiozation_1 = __webpack_require__(75107); function addLabel(dep, key, value) { if (!dep.labels) { dep.labels = {}; } dep.labels[key] = value; } /** * @deprecated Don't use dep trees as an intermediate step, because they are * large structures, resulting in high memory usage and high CPU costs from * serializing / deserializing. Instead, create a graph directly with * {@link DepGraphBuilder} */ async function depTreeToGraph(depTree, pkgManagerName) { const rootPkg = { name: depTree.name, version: depTree.version || undefined, }; const pkgManagerInfo = { name: pkgManagerName, }; const targetOS = depTree.targetOS; if (targetOS) { pkgManagerInfo.repositories = [ { alias: `${targetOS.name}:${targetOS.version}`, }, ]; } const builder = new builder_1.DepGraphBuilder(pkgManagerInfo, rootPkg); await buildGraph(builder, depTree, depTree.name, true); const depGraph = await builder.build(); return shortenNodeIds(depGraph); } exports.depTreeToGraph = depTreeToGraph; async function buildGraph(builder, depTree, pkgName, isRoot = false, memoizationMap = new Map()) { if (memoizationMap.has(depTree)) { return memoizationMap.get(depTree); } const getNodeId = (name, version, hashId) => `${name}@${version || ''}|${hashId}`; const depNodesIds = []; const hash = crypto.createHash('sha1'); if (depTree.versionProvenance) { hash.update(objectHash(depTree.versionProvenance)); } if (depTree.labels) { hash.update(objectHash(depTree.labels)); } const deps = depTree.dependencies || {}; // filter-out invalid null deps (shouldn't happen - but did...) const depNames = Object.keys(deps).filter((d) => !!deps[d]); for (const depName of depNames.sort()) { const dep = deps[depName]; const subtreeHash = await buildGraph(builder, dep, depName, false, memoizationMap); const depPkg = { name: depName, version: dep.version, }; const depNodeId = getNodeId(depPkg.name, depPkg.version, subtreeHash); depNodesIds.push(depNodeId); const nodeInfo = {}; if (dep.versionProvenance) { nodeInfo.versionProvenance = dep.versionProvenance; } if (dep.labels) { nodeInfo.labels = dep.labels; } builder.addPkgNode(depPkg, depNodeId, nodeInfo); hash.update(depNodeId); } const treeHash = hash.digest('hex'); let pkgNodeId; if (isRoot) { pkgNodeId = builder.rootNodeId; } else { // we don't assume depTree has a .name to support output of `npm list --json` const pkg = { name: pkgName, version: depTree.version, }; pkgNodeId = getNodeId(pkg.name, pkg.version, treeHash); const nodeInfo = {}; if (depTree.versionProvenance) { nodeInfo.versionProvenance = depTree.versionProvenance; } if (depTree.labels) { nodeInfo.labels = depTree.labels; } builder.addPkgNode(pkg, pkgNodeId, nodeInfo); } for (const depNodeId of depNodesIds) { builder.connectDep(pkgNodeId, depNodeId); } if (depNodesIds.length > 0 && event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } memoizationMap.set(depTree, treeHash); return treeHash; } async function shortenNodeIds(depGraph) { const builder = new builder_1.DepGraphBuilder(depGraph.pkgManager, depGraph.rootPkg); const nodesMap = {}; // create nodes with shorter ids for (const pkg of depGraph.getPkgs()) { const nodeIds = depGraph.getPkgNodeIds(pkg); for (let i = 0; i < nodeIds.length; i++) { const nodeId = nodeIds[i]; if (nodeId === depGraph.rootNodeId) { continue; } const nodeInfo = depGraph.getNode(nodeId); let newNodeId; if (nodeIds.length === 1) { newNodeId = `${trimAfterLastSep(nodeId, '|')}`; } else { newNodeId = `${trimAfterLastSep(nodeId, '|')}|${i + 1}`; } nodesMap[nodeId] = newNodeId; builder.addPkgNode(pkg, newNodeId, nodeInfo); } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } // connect nodes for (const pkg of depGraph.getPkgs()) { for (const nodeId of depGraph.getPkgNodeIds(pkg)) { for (const depNodeId of depGraph.getNodeDepsNodeIds(nodeId)) { const parentNode = nodesMap[nodeId] || nodeId; const childNode = nodesMap[depNodeId] || depNodeId; builder.connectDep(parentNode, childNode); } } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } return builder.build(); } /** * @deprecated Don't use dep trees. You should adapt your code to use graphs, * and enhance the dep-graph library if there is missing functionality from * the graph structure */ async function graphToDepTree(depGraphInterface, pkgType, opts = { deduplicateWithinTopLevelDeps: false }) { const depGraph = depGraphInterface; const [depTree] = await buildSubtree(depGraph, depGraph.rootNodeId, opts.deduplicateWithinTopLevelDeps ? null : false); depTree.type = depGraph.pkgManager.name; depTree.packageFormatVersion = constructPackageFormatVersion(pkgType); const targetOS = constructTargetOS(depGraph); if (targetOS) { depTree.targetOS = targetOS; } return depTree; } exports.graphToDepTree = graphToDepTree; function constructPackageFormatVersion(pkgType) { if (pkgType === 'maven') { pkgType = 'mvn'; } return `${pkgType}:0.0.1`; } function constructTargetOS(depGraph) { if (['apk', 'apt', 'deb', 'rpm', 'linux'].indexOf(depGraph.pkgManager.name) === -1) { // .targetOS is undefined unless its a linux pkgManager return; } if (!depGraph.pkgManager.repositories || !depGraph.pkgManager.repositories.length || !depGraph.pkgManager.repositories[0].alias) { throw new Error('Incomplete .pkgManager, could not create .targetOS'); } const [name, version] = depGraph.pkgManager.repositories[0].alias.split(':'); return { name, version }; } async function buildSubtree(depGraph, nodeId, maybeDeduplicationSet = false, // false = disabled; null = not in deduplication scope yet ancestors = [], memoizationMap = new Map()) { if (!maybeDeduplicationSet) { const memoizedDepTree = memiozation_1.getMemoizedDepTree(nodeId, ancestors, memoizationMap); if (memoizedDepTree) { return [memoizedDepTree, undefined]; } } const isRoot = nodeId === depGraph.rootNodeId; const nodePkg = depGraph.getNodePkg(nodeId); const nodeInfo = depGraph.getNode(nodeId); const depTree = {}; depTree.name = nodePkg.name; depTree.version = nodePkg.version; if (nodeInfo.versionProvenance) { depTree.versionProvenance = nodeInfo.versionProvenance; } if (nodeInfo.labels) { depTree.labels = Object.assign({}, nodeInfo.labels); } const depInstanceIds = depGraph.getNodeDepsNodeIds(nodeId); if (!depInstanceIds || depInstanceIds.length === 0) { memoizationMap.set(nodeId, { depTree }); return [depTree, undefined]; } const cycle = cycles_1.getCycle(ancestors, nodeId); if (cycle) { // This node starts a cycle and now it's the second visit. addLabel(depTree, 'pruned', 'cyclic'); return [depTree, [cycle]]; } if (maybeDeduplicationSet) { if (maybeDeduplicationSet.has(nodeId)) { if (depInstanceIds.length > 0) { addLabel(depTree, 'pruned', 'true'); } return [depTree, undefined]; } maybeDeduplicationSet.add(nodeId); } const cycles = []; for (const depInstId of depInstanceIds) { // Deduplication of nodes occurs only within a scope of a top-level dependency. // Therefore, every top-level dep gets an independent set to track duplicates. if (isRoot && maybeDeduplicationSet !== false) { maybeDeduplicationSet = new Set(); } const [subtree, subtreeCycles] = await buildSubtree(depGraph, depInstId, maybeDeduplicationSet, ancestors.concat(nodeId), memoizationMap); if (subtreeCycles) { for (const cycle of subtreeCycles) { cycles.push(cycle); } } if (!subtree) { continue; } if (!depTree.dependencies) { depTree.dependencies = {}; } depTree.dependencies[subtree.name] = subtree; } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } const partitionedCycles = cycles_1.partitionCycles(nodeId, cycles); memiozation_1.memoize(nodeId, memoizationMap, depTree, partitionedCycles); return [depTree, partitionedCycles.cyclesWithThisNode]; } function trimAfterLastSep(str, sep) { return str.slice(0, str.lastIndexOf(sep)); } //# sourceMappingURL=index.js.map /***/ }), /***/ 75107: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getMemoizedDepTree = exports.memoize = void 0; function memoize(nodeId, memoizationMap, depTree, partitionedCycles) { const { cyclesStartWithThisNode, cyclesWithThisNode } = partitionedCycles; if (cyclesStartWithThisNode.length > 0) { const cycleNodeIds = new Set(...cyclesStartWithThisNode); memoizationMap.set(nodeId, { depTree, cycleNodeIds }); } else if (cyclesWithThisNode.length === 0) { memoizationMap.set(nodeId, { depTree }); } // Don't memoize nodes in cycles (cyclesWithThisNode.length > 0) } exports.memoize = memoize; function getMemoizedDepTree(nodeId, ancestors, memoizationMap) { if (!memoizationMap.has(nodeId)) return null; const { depTree, cycleNodeIds } = memoizationMap.get(nodeId); if (!cycleNodeIds) return depTree; const ancestorsArePartOfTheCycle = ancestors.some((nodeId) => cycleNodeIds.has(nodeId)); return ancestorsArePartOfTheCycle ? null : depTree; } exports.getMemoizedDepTree = getMemoizedDepTree; //# sourceMappingURL=memiozation.js.map /***/ }), /***/ 78061: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // A linked list to keep track of recently-used-ness const Yallist = __webpack_require__(21800) const MAX = Symbol('max') const LENGTH = Symbol('length') const LENGTH_CALCULATOR = Symbol('lengthCalculator') const ALLOW_STALE = Symbol('allowStale') const MAX_AGE = Symbol('maxAge') const DISPOSE = Symbol('dispose') const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') const LRU_LIST = Symbol('lruList') const CACHE = Symbol('cache') const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') const naiveLength = () => 1 // lruList is a yallist where the head is the youngest // item, and the tail is the oldest. the list contains the Hit // objects as the entries. // Each Hit object has a reference to its Yallist.Node. This // never changes. // // cache is a Map (or PseudoMap) that matches the keys to // the Yallist.Node object. class LRUCache { constructor (options) { if (typeof options === 'number') options = { max: options } if (!options) options = {} if (options.max && (typeof options.max !== 'number' || options.max < 0)) throw new TypeError('max must be a non-negative number') // Kind of weird to have a default max of Infinity, but oh well. const max = this[MAX] = options.max || Infinity const lc = options.length || naiveLength this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc this[ALLOW_STALE] = options.stale || false if (options.maxAge && typeof options.maxAge !== 'number') throw new TypeError('maxAge must be a number') this[MAX_AGE] = options.maxAge || 0 this[DISPOSE] = options.dispose this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false this.reset() } // resize the cache when the max changes. set max (mL) { if (typeof mL !== 'number' || mL < 0) throw new TypeError('max must be a non-negative number') this[MAX] = mL || Infinity trim(this) } get max () { return this[MAX] } set allowStale (allowStale) { this[ALLOW_STALE] = !!allowStale } get allowStale () { return this[ALLOW_STALE] } set maxAge (mA) { if (typeof mA !== 'number') throw new TypeError('maxAge must be a non-negative number') this[MAX_AGE] = mA trim(this) } get maxAge () { return this[MAX_AGE] } // resize the cache when the lengthCalculator changes. set lengthCalculator (lC) { if (typeof lC !== 'function') lC = naiveLength if (lC !== this[LENGTH_CALCULATOR]) { this[LENGTH_CALCULATOR] = lC this[LENGTH] = 0 this[LRU_LIST].forEach(hit => { hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) this[LENGTH] += hit.length }) } trim(this) } get lengthCalculator () { return this[LENGTH_CALCULATOR] } get length () { return this[LENGTH] } get itemCount () { return this[LRU_LIST].length } rforEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].tail; walker !== null;) { const prev = walker.prev forEachStep(this, fn, walker, thisp) walker = prev } } forEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].head; walker !== null;) { const next = walker.next forEachStep(this, fn, walker, thisp) walker = next } } keys () { return this[LRU_LIST].toArray().map(k => k.key) } values () { return this[LRU_LIST].toArray().map(k => k.value) } reset () { if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) { this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) } this[CACHE] = new Map() // hash of items by key this[LRU_LIST] = new Yallist() // list of items in order of use recency this[LENGTH] = 0 // length of items in the list } dump () { return this[LRU_LIST].map(hit => isStale(this, hit) ? false : { k: hit.key, v: hit.value, e: hit.now + (hit.maxAge || 0) }).toArray().filter(h => h) } dumpLru () { return this[LRU_LIST] } set (key, value, maxAge) { maxAge = maxAge || this[MAX_AGE] if (maxAge && typeof maxAge !== 'number') throw new TypeError('maxAge must be a number') const now = maxAge ? Date.now() : 0 const len = this[LENGTH_CALCULATOR](value, key) if (this[CACHE].has(key)) { if (len > this[MAX]) { del(this, this[CACHE].get(key)) return false } const node = this[CACHE].get(key) const item = node.value // dispose of the old one before overwriting // split out into 2 ifs for better coverage tracking if (this[DISPOSE]) { if (!this[NO_DISPOSE_ON_SET]) this[DISPOSE](key, item.value) } item.now = now item.maxAge = maxAge item.value = value this[LENGTH] += len - item.length item.length = len this.get(key) trim(this) return true } const hit = new Entry(key, value, len, now, maxAge) // oversized objects fall out of cache automatically. if (hit.length > this[MAX]) { if (this[DISPOSE]) this[DISPOSE](key, value) return false } this[LENGTH] += hit.length this[LRU_LIST].unshift(hit) this[CACHE].set(key, this[LRU_LIST].head) trim(this) return true } has (key) { if (!this[CACHE].has(key)) return false const hit = this[CACHE].get(key).value return !isStale(this, hit) } get (key) { return get(this, key, true) } peek (key) { return get(this, key, false) } pop () { const node = this[LRU_LIST].tail if (!node) return null del(this, node) return node.value } del (key) { del(this, this[CACHE].get(key)) } load (arr) { // reset the cache this.reset() const now = Date.now() // A previous serialized cache has the most recent items first for (let l = arr.length - 1; l >= 0; l--) { const hit = arr[l] const expiresAt = hit.e || 0 if (expiresAt === 0) // the item was created without expiration in a non aged cache this.set(hit.k, hit.v) else { const maxAge = expiresAt - now // dont add already expired items if (maxAge > 0) { this.set(hit.k, hit.v, maxAge) } } } } prune () { this[CACHE].forEach((value, key) => get(this, key, false)) } } const get = (self, key, doUse) => { const node = self[CACHE].get(key) if (node) { const hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) return undefined } else { if (doUse) { if (self[UPDATE_AGE_ON_GET]) node.value.now = Date.now() self[LRU_LIST].unshiftNode(node) } } return hit.value } } const isStale = (self, hit) => { if (!hit || (!hit.maxAge && !self[MAX_AGE])) return false const diff = Date.now() - hit.now return hit.maxAge ? diff > hit.maxAge : self[MAX_AGE] && (diff > self[MAX_AGE]) } const trim = self => { if (self[LENGTH] > self[MAX]) { for (let walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) { // We know that we're about to delete this one, and also // what the next least recently used key will be, so just // go ahead and set it now. const prev = walker.prev del(self, walker) walker = prev } } } const del = (self, node) => { if (node) { const hit = node.value if (self[DISPOSE]) self[DISPOSE](hit.key, hit.value) self[LENGTH] -= hit.length self[CACHE].delete(hit.key) self[LRU_LIST].removeNode(node) } } class Entry { constructor (key, value, length, now, maxAge) { this.key = key this.value = value this.length = length this.now = now this.maxAge = maxAge || 0 } } const forEachStep = (self, fn, node, thisp) => { let hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) hit = undefined } if (hit) fn.call(thisp, hit.value, hit.key, self) } module.exports = LRUCache /***/ }), /***/ 86422: /***/ ((module, exports, __webpack_require__) => { "use strict"; var crypto = __webpack_require__(6113); /** * Exported function * * Options: * * - `algorithm` hash algo to be used by this instance: *'sha1', 'md5' * - `excludeValues` {true|*false} hash object keys, values ignored * - `encoding` hash encoding, supports 'buffer', '*hex', 'binary', 'base64' * - `ignoreUnknown` {true|*false} ignore unknown object types * - `replacer` optional function that replaces values before hashing * - `respectFunctionProperties` {*true|false} consider function properties when hashing * - `respectFunctionNames` {*true|false} consider 'name' property of functions for hashing * - `respectType` {*true|false} Respect special properties (prototype, constructor) * when hashing to distinguish between types * - `unorderedArrays` {true|*false} Sort all arrays before hashing * - `unorderedSets` {*true|false} Sort `Set` and `Map` instances before hashing * * = default * * @param {object} object value to hash * @param {object} options hashing options * @return {string} hash value * @api public */ exports = module.exports = objectHash; function objectHash(object, options){ options = applyDefaults(object, options); return hash(object, options); } /** * Exported sugar methods * * @param {object} object value to hash * @return {string} hash value * @api public */ exports.sha1 = function(object){ return objectHash(object); }; exports.keys = function(object){ return objectHash(object, {excludeValues: true, algorithm: 'sha1', encoding: 'hex'}); }; exports.MD5 = function(object){ return objectHash(object, {algorithm: 'md5', encoding: 'hex'}); }; exports.keysMD5 = function(object){ return objectHash(object, {algorithm: 'md5', encoding: 'hex', excludeValues: true}); }; // Internals var hashes = crypto.getHashes ? crypto.getHashes().slice() : ['sha1', 'md5']; hashes.push('passthrough'); var encodings = ['buffer', 'hex', 'binary', 'base64']; function applyDefaults(object, sourceOptions){ sourceOptions = sourceOptions || {}; // create a copy rather than mutating var options = {}; options.algorithm = sourceOptions.algorithm || 'sha1'; options.encoding = sourceOptions.encoding || 'hex'; options.excludeValues = sourceOptions.excludeValues ? true : false; options.algorithm = options.algorithm.toLowerCase(); options.encoding = options.encoding.toLowerCase(); options.ignoreUnknown = sourceOptions.ignoreUnknown !== true ? false : true; // default to false options.respectType = sourceOptions.respectType === false ? false : true; // default to true options.respectFunctionNames = sourceOptions.respectFunctionNames === false ? false : true; options.respectFunctionProperties = sourceOptions.respectFunctionProperties === false ? false : true; options.unorderedArrays = sourceOptions.unorderedArrays !== true ? false : true; // default to false options.unorderedSets = sourceOptions.unorderedSets === false ? false : true; // default to false options.unorderedObjects = sourceOptions.unorderedObjects === false ? false : true; // default to true options.replacer = sourceOptions.replacer || undefined; options.excludeKeys = sourceOptions.excludeKeys || undefined; if(typeof object === 'undefined') { throw new Error('Object argument required.'); } // if there is a case-insensitive match in the hashes list, accept it // (i.e. SHA256 for sha256) for (var i = 0; i < hashes.length; ++i) { if (hashes[i].toLowerCase() === options.algorithm.toLowerCase()) { options.algorithm = hashes[i]; } } if(hashes.indexOf(options.algorithm) === -1){ throw new Error('Algorithm "' + options.algorithm + '" not supported. ' + 'supported values: ' + hashes.join(', ')); } if(encodings.indexOf(options.encoding) === -1 && options.algorithm !== 'passthrough'){ throw new Error('Encoding "' + options.encoding + '" not supported. ' + 'supported values: ' + encodings.join(', ')); } return options; } /** Check if the given function is a native function */ function isNativeFunction(f) { if ((typeof f) !== 'function') { return false; } var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i; return exp.exec(Function.prototype.toString.call(f)) != null; } function hash(object, options) { var hashingStream; if (options.algorithm !== 'passthrough') { hashingStream = crypto.createHash(options.algorithm); } else { hashingStream = new PassThrough(); } if (typeof hashingStream.write === 'undefined') { hashingStream.write = hashingStream.update; hashingStream.end = hashingStream.update; } var hasher = typeHasher(options, hashingStream); hasher.dispatch(object); if (!hashingStream.update) { hashingStream.end(''); } if (hashingStream.digest) { return hashingStream.digest(options.encoding === 'buffer' ? undefined : options.encoding); } var buf = hashingStream.read(); if (options.encoding === 'buffer') { return buf; } return buf.toString(options.encoding); } /** * Expose streaming API * * @param {object} object Value to serialize * @param {object} options Options, as for hash() * @param {object} stream A stream to write the serializiation to * @api public */ exports.writeToStream = function(object, options, stream) { if (typeof stream === 'undefined') { stream = options; options = {}; } options = applyDefaults(object, options); return typeHasher(options, stream).dispatch(object); }; function typeHasher(options, writeTo, context){ context = context || []; var write = function(str) { if (writeTo.update) { return writeTo.update(str, 'utf8'); } else { return writeTo.write(str, 'utf8'); } }; return { dispatch: function(value){ if (options.replacer) { value = options.replacer(value); } var type = typeof value; if (value === null) { type = 'null'; } //console.log("[DEBUG] Dispatch: ", value, "->", type, " -> ", "_" + type); return this['_' + type](value); }, _object: function(object) { var pattern = (/\[object (.*)\]/i); var objString = Object.prototype.toString.call(object); var objType = pattern.exec(objString); if (!objType) { // object type did not match [object ...] objType = 'unknown:[' + objString + ']'; } else { objType = objType[1]; // take only the class name } objType = objType.toLowerCase(); var objectNumber = null; if ((objectNumber = context.indexOf(object)) >= 0) { return this.dispatch('[CIRCULAR:' + objectNumber + ']'); } else { context.push(object); } if (typeof Buffer !== 'undefined' && Buffer.isBuffer && Buffer.isBuffer(object)) { write('buffer:'); return write(object); } if(objType !== 'object' && objType !== 'function' && objType !== 'asyncfunction') { if(this['_' + objType]) { this['_' + objType](object); } else if (options.ignoreUnknown) { return write('[' + objType + ']'); } else { throw new Error('Unknown object type "' + objType + '"'); } }else{ var keys = Object.keys(object); if (options.unorderedObjects) { keys = keys.sort(); } // Make sure to incorporate special properties, so // Types with different prototypes will produce // a different hash and objects derived from // different functions (`new Foo`, `new Bar`) will // produce different hashes. // We never do this for native functions since some // seem to break because of that. if (options.respectType !== false && !isNativeFunction(object)) { keys.splice(0, 0, 'prototype', '__proto__', 'constructor'); } if (options.excludeKeys) { keys = keys.filter(function(key) { return !options.excludeKeys(key); }); } write('object:' + keys.length + ':'); var self = this; return keys.forEach(function(key){ self.dispatch(key); write(':'); if(!options.excludeValues) { self.dispatch(object[key]); } write(','); }); } }, _array: function(arr, unordered){ unordered = typeof unordered !== 'undefined' ? unordered : options.unorderedArrays !== false; // default to options.unorderedArrays var self = this; write('array:' + arr.length + ':'); if (!unordered || arr.length <= 1) { return arr.forEach(function(entry) { return self.dispatch(entry); }); } // the unordered case is a little more complicated: // since there is no canonical ordering on objects, // i.e. {a:1} < {a:2} and {a:1} > {a:2} are both false, // we first serialize each entry using a PassThrough stream // before sorting. // also: we can’t use the same context array for all entries // since the order of hashing should *not* matter. instead, // we keep track of the additions to a copy of the context array // and add all of them to the global context array when we’re done var contextAdditions = []; var entries = arr.map(function(entry) { var strm = new PassThrough(); var localContext = context.slice(); // make copy var hasher = typeHasher(options, strm, localContext); hasher.dispatch(entry); // take only what was added to localContext and append it to contextAdditions contextAdditions = contextAdditions.concat(localContext.slice(context.length)); return strm.read().toString(); }); context = context.concat(contextAdditions); entries.sort(); return this._array(entries, false); }, _date: function(date){ return write('date:' + date.toJSON()); }, _symbol: function(sym){ return write('symbol:' + sym.toString()); }, _error: function(err){ return write('error:' + err.toString()); }, _boolean: function(bool){ return write('bool:' + bool.toString()); }, _string: function(string){ write('string:' + string.length + ':'); write(string.toString()); }, _function: function(fn){ write('fn:'); if (isNativeFunction(fn)) { this.dispatch('[native]'); } else { this.dispatch(fn.toString()); } if (options.respectFunctionNames !== false) { // Make sure we can still distinguish native functions // by their name, otherwise String and Function will // have the same hash this.dispatch("function-name:" + String(fn.name)); } if (options.respectFunctionProperties) { this._object(fn); } }, _number: function(number){ return write('number:' + number.toString()); }, _xml: function(xml){ return write('xml:' + xml.toString()); }, _null: function() { return write('Null'); }, _undefined: function() { return write('Undefined'); }, _regexp: function(regex){ return write('regex:' + regex.toString()); }, _uint8array: function(arr){ write('uint8array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _uint8clampedarray: function(arr){ write('uint8clampedarray:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _int8array: function(arr){ write('uint8array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _uint16array: function(arr){ write('uint16array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _int16array: function(arr){ write('uint16array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _uint32array: function(arr){ write('uint32array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _int32array: function(arr){ write('uint32array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _float32array: function(arr){ write('float32array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _float64array: function(arr){ write('float64array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _arraybuffer: function(arr){ write('arraybuffer:'); return this.dispatch(new Uint8Array(arr)); }, _url: function(url) { return write('url:' + url.toString(), 'utf8'); }, _map: function(map) { write('map:'); var arr = Array.from(map); return this._array(arr, options.unorderedSets !== false); }, _set: function(set) { write('set:'); var arr = Array.from(set); return this._array(arr, options.unorderedSets !== false); }, _file: function(file) { write('file:'); return this.dispatch([file.name, file.size, file.type, file.lastModfied]); }, _blob: function() { if (options.ignoreUnknown) { return write('[blob]'); } throw Error('Hashing Blob objects is currently not supported\n' + '(see https://github.com/puleos/object-hash/issues/26)\n' + 'Use "options.replacer" or "options.ignoreUnknown"\n'); }, _domwindow: function() { return write('domwindow'); }, _bigint: function(number){ return write('bigint:' + number.toString()); }, /* Node.js standard native objects */ _process: function() { return write('process'); }, _timer: function() { return write('timer'); }, _pipe: function() { return write('pipe'); }, _tcp: function() { return write('tcp'); }, _udp: function() { return write('udp'); }, _tty: function() { return write('tty'); }, _statwatcher: function() { return write('statwatcher'); }, _securecontext: function() { return write('securecontext'); }, _connection: function() { return write('connection'); }, _zlib: function() { return write('zlib'); }, _context: function() { return write('context'); }, _nodescript: function() { return write('nodescript'); }, _httpparser: function() { return write('httpparser'); }, _dataview: function() { return write('dataview'); }, _signal: function() { return write('signal'); }, _fsevent: function() { return write('fsevent'); }, _tlswrap: function() { return write('tlswrap'); }, }; } // Mini-implementation of stream.PassThrough // We are far from having need for the full implementation, and we can // make assumptions like "many writes, then only one final read" // and we can ignore encoding specifics function PassThrough() { return { buf: '', write: function(b) { this.buf += b; }, end: function(b) { this.buf += b; }, read: function() { return this.buf; } }; } /***/ }), /***/ 82226: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const ANY = Symbol('SemVer ANY') // hoisted class for cyclic dependency class Comparator { static get ANY () { return ANY } constructor (comp, options) { options = parseOptions(options) if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } comp = comp.trim().split(/\s+/).join(' ') debug('comparator', comp, options) this.options = options this.loose = !!options.loose this.parse(comp) if (this.semver === ANY) { this.value = '' } else { this.value = this.operator + this.semver.version } debug('comp', this) } parse (comp) { const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] const m = comp.match(r) if (!m) { throw new TypeError(`Invalid comparator: ${comp}`) } this.operator = m[1] !== undefined ? m[1] : '' if (this.operator === '=') { this.operator = '' } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY } else { this.semver = new SemVer(m[2], this.options.loose) } } toString () { return this.value } test (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY || version === ANY) { return true } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } return cmp(version, this.operator, this.semver, this.options) } intersects (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (this.operator === '') { if (this.value === '') { return true } return new Range(comp.value, options).test(this.value) } else if (comp.operator === '') { if (comp.value === '') { return true } return new Range(this.value, options).test(comp.semver) } options = parseOptions(options) // Special cases where nothing can possibly be lower if (options.includePrerelease && (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { return false } if (!options.includePrerelease && (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { return false } // Same direction increasing (> or >=) if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { return true } // Same direction decreasing (< or <=) if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { return true } // same SemVer and both sides are inclusive (<= or >=) if ( (this.semver.version === comp.semver.version) && this.operator.includes('=') && comp.operator.includes('=')) { return true } // opposite directions less than if (cmp(this.semver, '<', comp.semver, options) && this.operator.startsWith('>') && comp.operator.startsWith('<')) { return true } // opposite directions greater than if (cmp(this.semver, '>', comp.semver, options) && this.operator.startsWith('<') && comp.operator.startsWith('>')) { return true } return false } } module.exports = Comparator const parseOptions = __webpack_require__(12985) const { safeRe: re, t } = __webpack_require__(2078) const cmp = __webpack_require__(83875) const debug = __webpack_require__(23914) const SemVer = __webpack_require__(63161) const Range = __webpack_require__(40308) /***/ }), /***/ 40308: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // hoisted class for cyclic dependency class Range { constructor (range, options) { options = parseOptions(options) if (range instanceof Range) { if ( range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease ) { return range } else { return new Range(range.raw, options) } } if (range instanceof Comparator) { // just put it in the set and return this.raw = range.value this.set = [[range]] this.format() return this } this.options = options this.loose = !!options.loose this.includePrerelease = !!options.includePrerelease // First reduce all whitespace as much as possible so we do not have to rely // on potentially slow regexes like \s*. This is then stored and used for // future error messages as well. this.raw = range .trim() .split(/\s+/) .join(' ') // First, split on || this.set = this.raw .split('||') // map the range to a 2d array of comparators .map(r => this.parseRange(r.trim())) // throw out any comparator lists that are empty // this generally means that it was not a valid range, which is allowed // in loose mode, but will still throw if the WHOLE range is invalid. .filter(c => c.length) if (!this.set.length) { throw new TypeError(`Invalid SemVer Range: ${this.raw}`) } // if we have any that are not the null set, throw out null sets. if (this.set.length > 1) { // keep the first one, in case they're all null sets const first = this.set[0] this.set = this.set.filter(c => !isNullSet(c[0])) if (this.set.length === 0) { this.set = [first] } else if (this.set.length > 1) { // if we have any that are *, then the range is just * for (const c of this.set) { if (c.length === 1 && isAny(c[0])) { this.set = [c] break } } } } this.format() } format () { this.range = this.set .map((comps) => comps.join(' ').trim()) .join('||') .trim() return this.range } toString () { return this.range } parseRange (range) { // memoize range parsing for performance. // this is a very hot path, and fully deterministic. const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE) const memoKey = memoOpts + ':' + range const cached = cache.get(memoKey) if (cached) { return cached } const loose = this.options.loose // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range) // `~ 1.2.3` => `~1.2.3` range = range.replace(re[t.TILDETRIM], tildeTrimReplace) debug('tilde trim', range) // `^ 1.2.3` => `^1.2.3` range = range.replace(re[t.CARETTRIM], caretTrimReplace) debug('caret trim', range) // At this point, the range is completely trimmed and // ready to be split into comparators. let rangeList = range .split(' ') .map(comp => parseComparator(comp, this.options)) .join(' ') .split(/\s+/) // >=0.0.0 is equivalent to * .map(comp => replaceGTE0(comp, this.options)) if (loose) { // in loose mode, throw out any that are not valid comparators rangeList = rangeList.filter(comp => { debug('loose invalid filter', comp, this.options) return !!comp.match(re[t.COMPARATORLOOSE]) }) } debug('range list', rangeList) // if any comparators are the null set, then replace with JUST null set // if more than one comparator, remove any * comparators // also, don't include the same comparator more than once const rangeMap = new Map() const comparators = rangeList.map(comp => new Comparator(comp, this.options)) for (const comp of comparators) { if (isNullSet(comp)) { return [comp] } rangeMap.set(comp.value, comp) } if (rangeMap.size > 1 && rangeMap.has('')) { rangeMap.delete('') } const result = [...rangeMap.values()] cache.set(memoKey, result) return result } intersects (range, options) { if (!(range instanceof Range)) { throw new TypeError('a Range is required') } return this.set.some((thisComparators) => { return ( isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => { return ( isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { return rangeComparators.every((rangeComparator) => { return thisComparator.intersects(rangeComparator, options) }) }) ) }) ) }) } // if ANY of the sets match ALL of its comparators, then pass test (version) { if (!version) { return false } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } for (let i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true } } return false } } module.exports = Range const LRU = __webpack_require__(78061) const cache = new LRU({ max: 1000 }) const parseOptions = __webpack_require__(12985) const Comparator = __webpack_require__(82226) const debug = __webpack_require__(23914) const SemVer = __webpack_require__(63161) const { safeRe: re, t, comparatorTrimReplace, tildeTrimReplace, caretTrimReplace, } = __webpack_require__(2078) const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __webpack_require__(97348) const isNullSet = c => c.value === '<0.0.0-0' const isAny = c => c.value === '' // take a set of comparators and determine whether there // exists a version which can satisfy it const isSatisfiable = (comparators, options) => { let result = true const remainingComparators = comparators.slice() let testComparator = remainingComparators.pop() while (result && remainingComparators.length) { result = remainingComparators.every((otherComparator) => { return testComparator.intersects(otherComparator, options) }) testComparator = remainingComparators.pop() } return result } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. const parseComparator = (comp, options) => { debug('comp', comp, options) comp = replaceCarets(comp, options) debug('caret', comp) comp = replaceTildes(comp, options) debug('tildes', comp) comp = replaceXRanges(comp, options) debug('xrange', comp) comp = replaceStars(comp, options) debug('stars', comp) return comp } const isX = id => !id || id.toLowerCase() === 'x' || id === '*' // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 // ~0.0.1 --> >=0.0.1 <0.1.0-0 const replaceTildes = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceTilde(c, options)) .join(' ') } const replaceTilde = (comp, options) => { const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] return comp.replace(r, (_, M, m, p, pr) => { debug('tilde', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0 <${+M + 1}.0.0-0` } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0-0 ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` } else if (pr) { debug('replaceTilde pr', pr) ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } else { // ~1.2.3 == >=1.2.3 <1.3.0-0 ret = `>=${M}.${m}.${p } <${M}.${+m + 1}.0-0` } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 // ^1.2.3 --> >=1.2.3 <2.0.0-0 // ^1.2.0 --> >=1.2.0 <2.0.0-0 // ^0.0.1 --> >=0.0.1 <0.0.2-0 // ^0.1.0 --> >=0.1.0 <0.2.0-0 const replaceCarets = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceCaret(c, options)) .join(' ') } const replaceCaret = (comp, options) => { debug('caret', comp, options) const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] const z = options.includePrerelease ? '-0' : '' return comp.replace(r, (_, M, m, p, pr) => { debug('caret', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` } else if (isX(p)) { if (M === '0') { ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` } else { ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p}-${pr } <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p}-${pr } <${+M + 1}.0.0-0` } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p }${z} <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p }${z} <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p } <${+M + 1}.0.0-0` } } debug('caret return', ret) return ret }) } const replaceXRanges = (comp, options) => { debug('replaceXRanges', comp, options) return comp .split(/\s+/) .map((c) => replaceXRange(c, options)) .join(' ') } const replaceXRange = (comp, options) => { comp = comp.trim() const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] return comp.replace(r, (ret, gtlt, M, m, p, pr) => { debug('xRange', comp, ret, gtlt, M, m, p, pr) const xM = isX(M) const xm = xM || isX(m) const xp = xm || isX(p) const anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } // if we're including prereleases in the match, then we need // to fix this to -0, the lowest possible prerelease value pr = options.includePrerelease ? '-0' : '' if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0-0' } else { // nothing is forbidden ret = '*' } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0 } p = 0 if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 gtlt = '>=' if (xm) { M = +M + 1 m = 0 p = 0 } else { m = +m + 1 p = 0 } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<' if (xm) { M = +M + 1 } else { m = +m + 1 } } if (gtlt === '<') { pr = '-0' } ret = `${gtlt + M}.${m}.${p}${pr}` } else if (xm) { ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` } else if (xp) { ret = `>=${M}.${m}.0${pr } <${M}.${+m + 1}.0-0` } debug('xRange return', ret) return ret }) } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. const replaceStars = (comp, options) => { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp .trim() .replace(re[t.STAR], '') } const replaceGTE0 = (comp, options) => { debug('replaceGTE0', comp, options) return comp .trim() .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') } // This function is passed to string.replace(re[t.HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 const hyphenReplace = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) => { if (isX(fM)) { from = '' } else if (isX(fm)) { from = `>=${fM}.0.0${incPr ? '-0' : ''}` } else if (isX(fp)) { from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` } else if (fpr) { from = `>=${from}` } else { from = `>=${from}${incPr ? '-0' : ''}` } if (isX(tM)) { to = '' } else if (isX(tm)) { to = `<${+tM + 1}.0.0-0` } else if (isX(tp)) { to = `<${tM}.${+tm + 1}.0-0` } else if (tpr) { to = `<=${tM}.${tm}.${tp}-${tpr}` } else if (incPr) { to = `<${tM}.${tm}.${+tp + 1}-0` } else { to = `<=${to}` } return `${from} ${to}`.trim() } const testSet = (set, version, options) => { for (let i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (let i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === Comparator.ANY) { continue } if (set[i].semver.prerelease.length > 0) { const allowed = set[i].semver if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } /***/ }), /***/ 63161: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const debug = __webpack_require__(23914) const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(97348) const { safeRe: re, t } = __webpack_require__(2078) const parseOptions = __webpack_require__(12985) const { compareIdentifiers } = __webpack_require__(85508) class SemVer { constructor (version, options) { options = parseOptions(options) if (version instanceof SemVer) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) } if (version.length > MAX_LENGTH) { throw new TypeError( `version is longer than ${MAX_LENGTH} characters` ) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose // this isn't actually relevant for versions, but keep it so that we // don't run into trouble passing this.options around. this.includePrerelease = !!options.includePrerelease const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) if (!m) { throw new TypeError(`Invalid Version: ${version}`) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map((id) => { if (/^[0-9]+$/.test(id)) { const num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } format () { this.version = `${this.major}.${this.minor}.${this.patch}` if (this.prerelease.length) { this.version += `-${this.prerelease.join('.')}` } return this.version } toString () { return this.version } compare (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { if (typeof other === 'string' && other === this.version) { return 0 } other = new SemVer(other, this.options) } if (other.version === this.version) { return 0 } return this.compareMain(other) || this.comparePre(other) } compareMain (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return ( compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) ) } comparePre (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } let i = 0 do { const a = this.prerelease[i] const b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } compareBuild (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } let i = 0 do { const a = this.build[i] const b = other.build[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc (release, identifier, identifierBase) { switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier, identifierBase) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier, identifierBase) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier, identifierBase) this.inc('pre', identifier, identifierBase) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier, identifierBase) } this.inc('pre', identifier, identifierBase) break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if ( this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0 ) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. case 'pre': { const base = Number(identifierBase) ? 1 : 0 if (!identifier && identifierBase === false) { throw new Error('invalid increment argument: identifier is empty') } if (this.prerelease.length === 0) { this.prerelease = [base] } else { let i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything if (identifier === this.prerelease.join('.') && identifierBase === false) { throw new Error('invalid increment argument: identifier already exists') } this.prerelease.push(base) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 let prerelease = [identifier, base] if (identifierBase === false) { prerelease = [identifier] } if (compareIdentifiers(this.prerelease[0], identifier) === 0) { if (isNaN(this.prerelease[1])) { this.prerelease = prerelease } } else { this.prerelease = prerelease } } break } default: throw new Error(`invalid increment argument: ${release}`) } this.raw = this.format() if (this.build.length) { this.raw += `+${this.build.join('.')}` } return this } } module.exports = SemVer /***/ }), /***/ 82572: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(80670) const clean = (version, options) => { const s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } module.exports = clean /***/ }), /***/ 83875: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const eq = __webpack_require__(3210) const neq = __webpack_require__(15919) const gt = __webpack_require__(22507) const gte = __webpack_require__(3326) const lt = __webpack_require__(30898) const lte = __webpack_require__(6064) const cmp = (a, op, b, loose) => { switch (op) { case '===': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a === b case '!==': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError(`Invalid operator: ${op}`) } } module.exports = cmp /***/ }), /***/ 55063: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(63161) const parse = __webpack_require__(80670) const { safeRe: re, t } = __webpack_require__(2078) const coerce = (version, options) => { if (version instanceof SemVer) { return version } if (typeof version === 'number') { version = String(version) } if (typeof version !== 'string') { return null } options = options || {} let match = null if (!options.rtl) { match = version.match(re[t.COERCE]) } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' // // Walk through the string checking with a /g regexp // Manually set the index so as to pick up overlapping matches. // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. let next while ((next = re[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next } re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length } // leave it in a clean state re[t.COERCERTL].lastIndex = -1 } if (match === null) { return null } return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) } module.exports = coerce /***/ }), /***/ 55424: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(63161) const compareBuild = (a, b, loose) => { const versionA = new SemVer(a, loose) const versionB = new SemVer(b, loose) return versionA.compare(versionB) || versionA.compareBuild(versionB) } module.exports = compareBuild /***/ }), /***/ 13028: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(98945) const compareLoose = (a, b) => compare(a, b, true) module.exports = compareLoose /***/ }), /***/ 98945: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(63161) const compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)) module.exports = compare /***/ }), /***/ 77094: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(80670) const diff = (version1, version2) => { const v1 = parse(version1, null, true) const v2 = parse(version2, null, true) const comparison = v1.compare(v2) if (comparison === 0) { return null } const v1Higher = comparison > 0 const highVersion = v1Higher ? v1 : v2 const lowVersion = v1Higher ? v2 : v1 const highHasPre = !!highVersion.prerelease.length const lowHasPre = !!lowVersion.prerelease.length if (lowHasPre && !highHasPre) { // Going from prerelease -> no prerelease requires some special casing // If the low version has only a major, then it will always be a major // Some examples: // 1.0.0-1 -> 1.0.0 // 1.0.0-1 -> 1.1.1 // 1.0.0-1 -> 2.0.0 if (!lowVersion.patch && !lowVersion.minor) { return 'major' } // Otherwise it can be determined by checking the high version if (highVersion.patch) { // anything higher than a patch bump would result in the wrong version return 'patch' } if (highVersion.minor) { // anything higher than a minor bump would result in the wrong version return 'minor' } // bumping major/minor/patch all have same result return 'major' } // add the `pre` prefix if we are going to a prerelease version const prefix = highHasPre ? 'pre' : '' if (v1.major !== v2.major) { return prefix + 'major' } if (v1.minor !== v2.minor) { return prefix + 'minor' } if (v1.patch !== v2.patch) { return prefix + 'patch' } // high and low are preleases return 'prerelease' } module.exports = diff /***/ }), /***/ 3210: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(98945) const eq = (a, b, loose) => compare(a, b, loose) === 0 module.exports = eq /***/ }), /***/ 22507: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(98945) const gt = (a, b, loose) => compare(a, b, loose) > 0 module.exports = gt /***/ }), /***/ 3326: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(98945) const gte = (a, b, loose) => compare(a, b, loose) >= 0 module.exports = gte /***/ }), /***/ 9257: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(63161) const inc = (version, release, options, identifier, identifierBase) => { if (typeof (options) === 'string') { identifierBase = identifier identifier = options options = undefined } try { return new SemVer( version instanceof SemVer ? version.version : version, options ).inc(release, identifier, identifierBase).version } catch (er) { return null } } module.exports = inc /***/ }), /***/ 30898: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(98945) const lt = (a, b, loose) => compare(a, b, loose) < 0 module.exports = lt /***/ }), /***/ 6064: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(98945) const lte = (a, b, loose) => compare(a, b, loose) <= 0 module.exports = lte /***/ }), /***/ 12879: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(63161) const major = (a, loose) => new SemVer(a, loose).major module.exports = major /***/ }), /***/ 91362: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(63161) const minor = (a, loose) => new SemVer(a, loose).minor module.exports = minor /***/ }), /***/ 15919: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(98945) const neq = (a, b, loose) => compare(a, b, loose) !== 0 module.exports = neq /***/ }), /***/ 80670: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(63161) const parse = (version, options, throwErrors = false) => { if (version instanceof SemVer) { return version } try { return new SemVer(version, options) } catch (er) { if (!throwErrors) { return null } throw er } } module.exports = parse /***/ }), /***/ 41067: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(63161) const patch = (a, loose) => new SemVer(a, loose).patch module.exports = patch /***/ }), /***/ 7020: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(80670) const prerelease = (version, options) => { const parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } module.exports = prerelease /***/ }), /***/ 16046: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(98945) const rcompare = (a, b, loose) => compare(b, a, loose) module.exports = rcompare /***/ }), /***/ 37026: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(55424) const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) module.exports = rsort /***/ }), /***/ 26233: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(40308) const satisfies = (version, range, options) => { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } module.exports = satisfies /***/ }), /***/ 3424: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(55424) const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) module.exports = sort /***/ }), /***/ 8691: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(80670) const valid = (version, options) => { const v = parse(version, options) return v ? v.version : null } module.exports = valid /***/ }), /***/ 8095: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // just pre-load all the stuff that index.js lazily exports const internalRe = __webpack_require__(2078) const constants = __webpack_require__(97348) const SemVer = __webpack_require__(63161) const identifiers = __webpack_require__(85508) const parse = __webpack_require__(80670) const valid = __webpack_require__(8691) const clean = __webpack_require__(82572) const inc = __webpack_require__(9257) const diff = __webpack_require__(77094) const major = __webpack_require__(12879) const minor = __webpack_require__(91362) const patch = __webpack_require__(41067) const prerelease = __webpack_require__(7020) const compare = __webpack_require__(98945) const rcompare = __webpack_require__(16046) const compareLoose = __webpack_require__(13028) const compareBuild = __webpack_require__(55424) const sort = __webpack_require__(3424) const rsort = __webpack_require__(37026) const gt = __webpack_require__(22507) const lt = __webpack_require__(30898) const eq = __webpack_require__(3210) const neq = __webpack_require__(15919) const gte = __webpack_require__(3326) const lte = __webpack_require__(6064) const cmp = __webpack_require__(83875) const coerce = __webpack_require__(55063) const Comparator = __webpack_require__(82226) const Range = __webpack_require__(40308) const satisfies = __webpack_require__(26233) const toComparators = __webpack_require__(52756) const maxSatisfying = __webpack_require__(39417) const minSatisfying = __webpack_require__(18889) const minVersion = __webpack_require__(76478) const validRange = __webpack_require__(76159) const outside = __webpack_require__(58560) const gtr = __webpack_require__(32784) const ltr = __webpack_require__(13312) const intersects = __webpack_require__(47086) const simplifyRange = __webpack_require__(40950) const subset = __webpack_require__(53508) module.exports = { parse, valid, clean, inc, diff, major, minor, patch, prerelease, compare, rcompare, compareLoose, compareBuild, sort, rsort, gt, lt, eq, neq, gte, lte, cmp, coerce, Comparator, Range, satisfies, toComparators, maxSatisfying, minSatisfying, minVersion, validRange, outside, gtr, ltr, intersects, simplifyRange, subset, SemVer, re: internalRe.re, src: internalRe.src, tokens: internalRe.t, SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, RELEASE_TYPES: constants.RELEASE_TYPES, compareIdentifiers: identifiers.compareIdentifiers, rcompareIdentifiers: identifiers.rcompareIdentifiers, } /***/ }), /***/ 97348: /***/ ((module) => { // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. const SEMVER_SPEC_VERSION = '2.0.0' const MAX_LENGTH = 256 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. const MAX_SAFE_COMPONENT_LENGTH = 16 // Max safe length for a build identifier. The max length minus 6 characters for // the shortest version with a build 0.0.0+BUILD. const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 const RELEASE_TYPES = [ 'major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease', ] module.exports = { MAX_LENGTH, MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_SAFE_INTEGER, RELEASE_TYPES, SEMVER_SPEC_VERSION, FLAG_INCLUDE_PRERELEASE: 0b001, FLAG_LOOSE: 0b010, } /***/ }), /***/ 23914: /***/ ((module) => { const debug = ( typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ) ? (...args) => console.error('SEMVER', ...args) : () => {} module.exports = debug /***/ }), /***/ 85508: /***/ ((module) => { const numeric = /^[0-9]+$/ const compareIdentifiers = (a, b) => { const anum = numeric.test(a) const bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) module.exports = { compareIdentifiers, rcompareIdentifiers, } /***/ }), /***/ 12985: /***/ ((module) => { // parse out just the options we care about const looseOption = Object.freeze({ loose: true }) const emptyOpts = Object.freeze({ }) const parseOptions = options => { if (!options) { return emptyOpts } if (typeof options !== 'object') { return looseOption } return options } module.exports = parseOptions /***/ }), /***/ 2078: /***/ ((module, exports, __webpack_require__) => { const { MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_LENGTH, } = __webpack_require__(97348) const debug = __webpack_require__(23914) exports = module.exports = {} // The actual regexps go on exports.re const re = exports.re = [] const safeRe = exports.safeRe = [] const src = exports.src = [] const t = exports.t = {} let R = 0 const LETTERDASHNUMBER = '[a-zA-Z0-9-]' // Replace some greedy regex tokens to prevent regex dos issues. These regex are // used internally via the safeRe object since all inputs in this library get // normalized first to trim and collapse all extra whitespace. The original // regexes are exported for userland consumption and lower level usage. A // future breaking change could export the safer regex only with a note that // all input should have extra whitespace removed. const safeRegexReplacements = [ ['\\s', 1], ['\\d', MAX_LENGTH], [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], ] const makeSafeRegex = (value) => { for (const [token, max] of safeRegexReplacements) { value = value .split(`${token}*`).join(`${token}{0,${max}}`) .split(`${token}+`).join(`${token}{1,${max}}`) } return value } const createToken = (name, value, isGlobal) => { const safe = makeSafeRegex(value) const index = R++ debug(name, index, value) t[name] = index src[index] = value re[index] = new RegExp(value, isGlobal ? 'g' : undefined) safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) } // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') createToken('NUMERICIDENTIFIERLOOSE', '\\d+') // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) // ## Main Version // Three dot-separated numeric identifiers. createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`) createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] }|${src[t.NONNUMERICIDENTIFIER]})`) createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] }|${src[t.NONNUMERICIDENTIFIER]})`) // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] }(?:\\.${src[t.BUILDIDENTIFIER]})*))`) // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. createToken('FULLPLAIN', `v?${src[t.MAINVERSION] }${src[t.PRERELEASE]}?${ src[t.BUILD]}?`) createToken('FULL', `^${src[t.FULLPLAIN]}$`) // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] }${src[t.PRERELEASELOOSE]}?${ src[t.BUILD]}?`) createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) createToken('GTLT', '((?:<|>)?=?)') // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) // Coercion. // Extract anything that could conceivably be a part of a valid semver createToken('COERCE', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:$|[^\\d])`) createToken('COERCERTL', src[t.COERCE], true) // Tilde ranges. // Meaning is "reasonably at or greater than" createToken('LONETILDE', '(?:~>?)') createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) exports.tildeTrimReplace = '$1~' createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) // Caret ranges. // Meaning is "at least and backwards compatible with" createToken('LONECARET', '(?:\\^)') createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) exports.caretTrimReplace = '$1^' createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) // A simple gt/lt/eq thing, or just "" to indicate "any version" createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) exports.comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`) createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`) // Star ranges basically just allow anything at all. createToken('STAR', '(<|>)?=?\\s*\\*') // >=0.0.0 is like a star createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') /***/ }), /***/ 32784: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Determine if version is greater than all the versions possible in the range. const outside = __webpack_require__(58560) const gtr = (version, range, options) => outside(version, range, '>', options) module.exports = gtr /***/ }), /***/ 47086: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(40308) const intersects = (r1, r2, options) => { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2, options) } module.exports = intersects /***/ }), /***/ 13312: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const outside = __webpack_require__(58560) // Determine if version is less than all the versions possible in the range const ltr = (version, range, options) => outside(version, range, '<', options) module.exports = ltr /***/ }), /***/ 39417: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(63161) const Range = __webpack_require__(40308) const maxSatisfying = (versions, range, options) => { let max = null let maxSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } module.exports = maxSatisfying /***/ }), /***/ 18889: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(63161) const Range = __webpack_require__(40308) const minSatisfying = (versions, range, options) => { let min = null let minSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } module.exports = minSatisfying /***/ }), /***/ 76478: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(63161) const Range = __webpack_require__(40308) const gt = __webpack_require__(22507) const minVersion = (range, loose) => { range = new Range(range, loose) let minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let setMin = null comparators.forEach((comparator) => { // Clone to avoid manipulating the comparator's semver object. const compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!setMin || gt(compver, setMin)) { setMin = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error(`Unexpected operation: ${comparator.operator}`) } }) if (setMin && (!minver || gt(minver, setMin))) { minver = setMin } } if (minver && range.test(minver)) { return minver } return null } module.exports = minVersion /***/ }), /***/ 58560: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(63161) const Comparator = __webpack_require__(82226) const { ANY } = Comparator const Range = __webpack_require__(40308) const satisfies = __webpack_require__(26233) const gt = __webpack_require__(22507) const lt = __webpack_require__(30898) const lte = __webpack_require__(6064) const gte = __webpack_require__(3326) const outside = (version, range, hilo, options) => { version = new SemVer(version, options) range = new Range(range, options) let gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisfies the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let high = null let low = null comparators.forEach((comparator) => { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } module.exports = outside /***/ }), /***/ 40950: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // given a set of versions and a range, create a "simplified" range // that includes the same versions that the original range does // If the original range is shorter than the simplified one, return that. const satisfies = __webpack_require__(26233) const compare = __webpack_require__(98945) module.exports = (versions, range, options) => { const set = [] let first = null let prev = null const v = versions.sort((a, b) => compare(a, b, options)) for (const version of v) { const included = satisfies(version, range, options) if (included) { prev = version if (!first) { first = version } } else { if (prev) { set.push([first, prev]) } prev = null first = null } } if (first) { set.push([first, null]) } const ranges = [] for (const [min, max] of set) { if (min === max) { ranges.push(min) } else if (!max && min === v[0]) { ranges.push('*') } else if (!max) { ranges.push(`>=${min}`) } else if (min === v[0]) { ranges.push(`<=${max}`) } else { ranges.push(`${min} - ${max}`) } } const simplified = ranges.join(' || ') const original = typeof range.raw === 'string' ? range.raw : String(range) return simplified.length < original.length ? simplified : range } /***/ }), /***/ 53508: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(40308) const Comparator = __webpack_require__(82226) const { ANY } = Comparator const satisfies = __webpack_require__(26233) const compare = __webpack_require__(98945) // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: // - Every simple range `r1, r2, ...` is a null set, OR // - Every simple range `r1, r2, ...` which is not a null set is a subset of // some `R1, R2, ...` // // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: // - If c is only the ANY comparator // - If C is only the ANY comparator, return true // - Else if in prerelease mode, return false // - else replace c with `[>=0.0.0]` // - If C is only the ANY comparator // - if in prerelease mode, return true // - else replace C with `[>=0.0.0]` // - Let EQ be the set of = comparators in c // - If EQ is more than one, return true (null set) // - Let GT be the highest > or >= comparator in c // - Let LT be the lowest < or <= comparator in c // - If GT and LT, and GT.semver > LT.semver, return true (null set) // - If any C is a = range, and GT or LT are set, return false // - If EQ // - If GT, and EQ does not satisfy GT, return true (null set) // - If LT, and EQ does not satisfy LT, return true (null set) // - If EQ satisfies every C, return true // - Else return false // - If GT // - If GT.semver is lower than any > or >= comp in C, return false // - If GT is >=, and GT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the GT.semver tuple, return false // - If LT // - If LT.semver is greater than any < or <= comp in C, return false // - If LT is <=, and LT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the LT.semver tuple, return false // - Else return true const subset = (sub, dom, options = {}) => { if (sub === dom) { return true } sub = new Range(sub, options) dom = new Range(dom, options) let sawNonNull = false OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { const isSub = simpleSubset(simpleSub, simpleDom, options) sawNonNull = sawNonNull || isSub !== null if (isSub) { continue OUTER } } // the null set is a subset of everything, but null simple ranges in // a complex range should be ignored. so if we saw a non-null range, // then we know this isn't a subset, but if EVERY simple range was null, // then it is a subset. if (sawNonNull) { return false } } return true } const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] const minimumVersion = [new Comparator('>=0.0.0')] const simpleSubset = (sub, dom, options) => { if (sub === dom) { return true } if (sub.length === 1 && sub[0].semver === ANY) { if (dom.length === 1 && dom[0].semver === ANY) { return true } else if (options.includePrerelease) { sub = minimumVersionWithPreRelease } else { sub = minimumVersion } } if (dom.length === 1 && dom[0].semver === ANY) { if (options.includePrerelease) { return true } else { dom = minimumVersion } } const eqSet = new Set() let gt, lt for (const c of sub) { if (c.operator === '>' || c.operator === '>=') { gt = higherGT(gt, c, options) } else if (c.operator === '<' || c.operator === '<=') { lt = lowerLT(lt, c, options) } else { eqSet.add(c.semver) } } if (eqSet.size > 1) { return null } let gtltComp if (gt && lt) { gtltComp = compare(gt.semver, lt.semver, options) if (gtltComp > 0) { return null } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { return null } } // will iterate one or zero times for (const eq of eqSet) { if (gt && !satisfies(eq, String(gt), options)) { return null } if (lt && !satisfies(eq, String(lt), options)) { return null } for (const c of dom) { if (!satisfies(eq, String(c), options)) { return false } } return true } let higher, lower let hasDomLT, hasDomGT // if the subset has a prerelease, we need a comparator in the superset // with the same tuple and a prerelease, or it's not a subset let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false // exception: <1.2.3-0 is the same as <1.2.3 if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { needDomLTPre = false } for (const c of dom) { hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' if (gt) { if (needDomGTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { needDomGTPre = false } } if (c.operator === '>' || c.operator === '>=') { higher = higherGT(gt, c, options) if (higher === c && higher !== gt) { return false } } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { return false } } if (lt) { if (needDomLTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { needDomLTPre = false } } if (c.operator === '<' || c.operator === '<=') { lower = lowerLT(lt, c, options) if (lower === c && lower !== lt) { return false } } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { return false } } if (!c.operator && (lt || gt) && gtltComp !== 0) { return false } } // if there was a < or >, and nothing in the dom, then must be false // UNLESS it was limited by another range in the other direction. // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 if (gt && hasDomLT && !lt && gtltComp !== 0) { return false } if (lt && hasDomGT && !gt && gtltComp !== 0) { return false } // we needed a prerelease range in a specific tuple, but didn't get one // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, // because it includes prereleases in the 1.2.3 tuple if (needDomGTPre || needDomLTPre) { return false } return true } // >=1.2.3 is lower than >1.2.3 const higherGT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp > 0 ? a : comp < 0 ? b : b.operator === '>' && a.operator === '>=' ? b : a } // <=1.2.3 is higher than <1.2.3 const lowerLT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp < 0 ? a : comp > 0 ? b : b.operator === '<' && a.operator === '<=' ? b : a } module.exports = subset /***/ }), /***/ 52756: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(40308) // Mostly just for testing and legacy API reasons const toComparators = (range, options) => new Range(range, options).set .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) module.exports = toComparators /***/ }), /***/ 76159: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(40308) const validRange = (range, options) => { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } module.exports = validRange /***/ }), /***/ 83556: /***/ ((module) => { "use strict"; module.exports = function (Yallist) { Yallist.prototype[Symbol.iterator] = function* () { for (let walker = this.head; walker; walker = walker.next) { yield walker.value } } } /***/ }), /***/ 21800: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = Yallist Yallist.Node = Node Yallist.create = Yallist function Yallist (list) { var self = this if (!(self instanceof Yallist)) { self = new Yallist() } self.tail = null self.head = null self.length = 0 if (list && typeof list.forEach === 'function') { list.forEach(function (item) { self.push(item) }) } else if (arguments.length > 0) { for (var i = 0, l = arguments.length; i < l; i++) { self.push(arguments[i]) } } return self } Yallist.prototype.removeNode = function (node) { if (node.list !== this) { throw new Error('removing node which does not belong to this list') } var next = node.next var prev = node.prev if (next) { next.prev = prev } if (prev) { prev.next = next } if (node === this.head) { this.head = next } if (node === this.tail) { this.tail = prev } node.list.length-- node.next = null node.prev = null node.list = null return next } Yallist.prototype.unshiftNode = function (node) { if (node === this.head) { return } if (node.list) { node.list.removeNode(node) } var head = this.head node.list = this node.next = head if (head) { head.prev = node } this.head = node if (!this.tail) { this.tail = node } this.length++ } Yallist.prototype.pushNode = function (node) { if (node === this.tail) { return } if (node.list) { node.list.removeNode(node) } var tail = this.tail node.list = this node.prev = tail if (tail) { tail.next = node } this.tail = node if (!this.head) { this.head = node } this.length++ } Yallist.prototype.push = function () { for (var i = 0, l = arguments.length; i < l; i++) { push(this, arguments[i]) } return this.length } Yallist.prototype.unshift = function () { for (var i = 0, l = arguments.length; i < l; i++) { unshift(this, arguments[i]) } return this.length } Yallist.prototype.pop = function () { if (!this.tail) { return undefined } var res = this.tail.value this.tail = this.tail.prev if (this.tail) { this.tail.next = null } else { this.head = null } this.length-- return res } Yallist.prototype.shift = function () { if (!this.head) { return undefined } var res = this.head.value this.head = this.head.next if (this.head) { this.head.prev = null } else { this.tail = null } this.length-- return res } Yallist.prototype.forEach = function (fn, thisp) { thisp = thisp || this for (var walker = this.head, i = 0; walker !== null; i++) { fn.call(thisp, walker.value, i, this) walker = walker.next } } Yallist.prototype.forEachReverse = function (fn, thisp) { thisp = thisp || this for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { fn.call(thisp, walker.value, i, this) walker = walker.prev } } Yallist.prototype.get = function (n) { for (var i = 0, walker = this.head; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.next } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.getReverse = function (n) { for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.prev } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.map = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.head; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.next } return res } Yallist.prototype.mapReverse = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.tail; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.prev } return res } Yallist.prototype.reduce = function (fn, initial) { var acc var walker = this.head if (arguments.length > 1) { acc = initial } else if (this.head) { walker = this.head.next acc = this.head.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = 0; walker !== null; i++) { acc = fn(acc, walker.value, i) walker = walker.next } return acc } Yallist.prototype.reduceReverse = function (fn, initial) { var acc var walker = this.tail if (arguments.length > 1) { acc = initial } else if (this.tail) { walker = this.tail.prev acc = this.tail.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = this.length - 1; walker !== null; i--) { acc = fn(acc, walker.value, i) walker = walker.prev } return acc } Yallist.prototype.toArray = function () { var arr = new Array(this.length) for (var i = 0, walker = this.head; walker !== null; i++) { arr[i] = walker.value walker = walker.next } return arr } Yallist.prototype.toArrayReverse = function () { var arr = new Array(this.length) for (var i = 0, walker = this.tail; walker !== null; i++) { arr[i] = walker.value walker = walker.prev } return arr } Yallist.prototype.slice = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = 0, walker = this.head; walker !== null && i < from; i++) { walker = walker.next } for (; walker !== null && i < to; i++, walker = walker.next) { ret.push(walker.value) } return ret } Yallist.prototype.sliceReverse = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { walker = walker.prev } for (; walker !== null && i > from; i--, walker = walker.prev) { ret.push(walker.value) } return ret } Yallist.prototype.splice = function (start, deleteCount, ...nodes) { if (start > this.length) { start = this.length - 1 } if (start < 0) { start = this.length + start; } for (var i = 0, walker = this.head; walker !== null && i < start; i++) { walker = walker.next } var ret = [] for (var i = 0; walker && i < deleteCount; i++) { ret.push(walker.value) walker = this.removeNode(walker) } if (walker === null) { walker = this.tail } if (walker !== this.head && walker !== this.tail) { walker = walker.prev } for (var i = 0; i < nodes.length; i++) { walker = insert(this, walker, nodes[i]) } return ret; } Yallist.prototype.reverse = function () { var head = this.head var tail = this.tail for (var walker = head; walker !== null; walker = walker.prev) { var p = walker.prev walker.prev = walker.next walker.next = p } this.head = tail this.tail = head return this } function insert (self, node, value) { var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self) if (inserted.next === null) { self.tail = inserted } if (inserted.prev === null) { self.head = inserted } self.length++ return inserted } function push (self, item) { self.tail = new Node(item, self.tail, null, self) if (!self.head) { self.head = self.tail } self.length++ } function unshift (self, item) { self.head = new Node(item, null, self.head, self) if (!self.tail) { self.tail = self.head } self.length++ } function Node (value, prev, next, list) { if (!(this instanceof Node)) { return new Node(value, prev, next, list) } this.list = list this.value = value if (prev) { prev.next = this this.prev = prev } else { this.prev = null } if (next) { next.prev = this this.next = next } else { this.next = null } } try { // add if support for Symbol.iterator is present __webpack_require__(83556)(Yallist) } catch (er) {} /***/ }), /***/ 78217: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const types_1 = __webpack_require__(45776); const types_2 = __webpack_require__(98590); /** * Extract the values from a hash index, which is stored in a Hash DB page. * The hash index contains key/value pairs. The key is usually some number * which is not relevant to the application. This function returns only the * values stored in the index. * @param data A database page. * @param entries How many entries are stored in the index. */ function bufferToHashIndexValues(page, entries) { // Hash table entries are always stored in pairs of 2. if (entries % 2 !== 0) { const pageNumber = page.readUInt32LE(8); throw new types_2.ParserError('The number of entries must be a multiple of 2', { entries, pageNumber, }); } // Every entry is a 2-byte offset that points somewhere in the current database page. const hashIndexSize = entries * types_1.HASH_INDEX_ENTRY_SIZE; const hashIndex = page.slice(types_1.DATABASE_PAGE_HEADER_SIZE, types_1.DATABASE_PAGE_HEADER_SIZE + hashIndexSize); // We only want the values, not the keys. Data is stored in key/value pairs. // The following skips over all keys and stores only the values. An entry is 2 bytes long. const keyValuePairSize = 2 * types_1.HASH_INDEX_ENTRY_SIZE; const hashIndexValues = hashIndex.reduce((values, _, byteOffset) => { // Is the current byte the start of a value? if ((byteOffset - types_1.HASH_INDEX_ENTRY_SIZE) % keyValuePairSize === 0) { const value = hashIndex.readInt16LE(byteOffset); values.push(value); } return values; }, new Array()); return hashIndexValues; } exports.bufferToHashIndexValues = bufferToHashIndexValues; //# sourceMappingURL=database-pages.js.map /***/ }), /***/ 85959: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const types_1 = __webpack_require__(45776); const types_2 = __webpack_require__(98590); /** * Traverse the data (overflow) pages and extract the data. * The data may be spread over multiple pages, so for every page we need to: * 1. Strip the page header of every page. * 2. Collate with data collected so far. * 3. Make sure to read the right data offset if we reach the last page. * The pages are not in order, so we may have to jump all across the BerkeleyDB file. * This is why we also need a Buffer to the database contents. * @param berkeleydb The contents of the database. * @param page Which page to start looking from. This should be an Overflow page. * @param pageStartOffset Which byte in the BerkeleyDB points to the start of the page. * @param pageSizeBytes How big is every page (typically it would be 4096 bytes). */ function bufferToHashValueContent(berkeleydb, page, pageStartOffset, pageSizeBytes) { // The byte offset that describes the page type is the same regardless of the page type. // Note there may be 5 different page types of varying length, but we are interested only one. const pageType = page.readUInt8(pageStartOffset); if (pageType !== types_1.HashPageType.H_OFFPAGE) { throw new types_2.ParserError('Unsupported page type', { pageType }); } const startPageNumber = page.readUInt32LE(pageStartOffset + 4); const dataLengthBytes = page.readUInt32LE(pageStartOffset + 8); const result = Buffer.alloc(dataLengthBytes); let bytesWritten = 0; // Traverse the pages, using "nextPageNumber" in the page metadata to see if we've reached the end. for (let currentPageNumber = startPageNumber; currentPageNumber !== 0;) { const pageStart = pageSizeBytes * currentPageNumber; const pageEnd = pageStart + pageSizeBytes; const currentPage = berkeleydb.slice(pageStart, pageEnd); const nextPageNumber = currentPage.readUInt32LE(16); const freeAreaOffset = currentPage.readUInt16LE(22); const isLastPage = nextPageNumber === 0; const bytesToWrite = isLastPage ? // The last page points to where the data ends. currentPage.slice(types_1.DATABASE_PAGE_HEADER_SIZE, freeAreaOffset) : // Otherwise the whole page is filled with content. currentPage.slice(types_1.DATABASE_PAGE_HEADER_SIZE, currentPage.length); const byteOffset = bytesWritten; result.set(bytesToWrite, byteOffset); bytesWritten += bytesToWrite.length; currentPageNumber = nextPageNumber; } return result; } exports.bufferToHashValueContent = bufferToHashValueContent; //# sourceMappingURL=hash-pages.js.map /***/ }), /***/ 40218: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const event_loop_spinner_1 = __webpack_require__(77158); const database_pages_1 = __webpack_require__(78217); exports.bufferToHashIndexValues = database_pages_1.bufferToHashIndexValues; const hash_pages_1 = __webpack_require__(85959); exports.bufferToHashValueContent = hash_pages_1.bufferToHashValueContent; const types_1 = __webpack_require__(45776); const types_2 = __webpack_require__(98590); const validPageSizes = [ 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, ]; /** * Extract the RPM package contents from a BerkeleyDB. Note that the contents * are returned as a Buffer of data for every package and that they need to be further * processed to extract meaningful package information. * * This implementation is interested in finding only data blobs of type Hash DB. * * The BerkeleyDB that we are interested in contains only the following pages: * - A metadata page -- the first page (index 0) of the database. * - A Hash DB page -- this page basically tells us where to find the data in the BerkeleyDB. * - An Overflow page -- this page contains the data. The data may span multiple pages (hence "overflow" pages). * @param data The contents of a BerkeleyDB database. */ async function bufferToHashDbValues(data) { validateBerkeleyDbMetadata(data); const pageSize = data.readUInt32LE(20); validatePageSize(pageSize); const lastPageNumber = data.readUInt32LE(32); const result = new Array(); // The 0th index page is the database metadata page, so start from the 1st index page. for (let pageNumber = 1; pageNumber < lastPageNumber; pageNumber++) { const pageStart = pageNumber * pageSize; const pageEnd = pageStart + pageSize; const pageType = data[pageStart + 25]; // Look only for HASH pages, we will traverse their content in subsequent steps. if (pageType !== types_1.DatabasePageType.P_HASH) { continue; } const page = data.slice(pageStart, pageEnd); const entries = page.readUInt16LE(20); // Hash DB entries come in key/value pairs. We are only interested in the values. const hashIndex = database_pages_1.bufferToHashIndexValues(page, entries); for (const hashPage of hashIndex) { const valuePageType = page[hashPage]; // Only Overflow pages contain package data, skip anything else. if (valuePageType !== types_1.HashPageType.H_OFFPAGE) { continue; } // Traverse the page to concatenate the data that may span multiple pages. const valueContent = hash_pages_1.bufferToHashValueContent(data, page, hashPage, pageSize); result.push(valueContent); } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } return result; } exports.bufferToHashDbValues = bufferToHashDbValues; /** * Exported for testing */ function validateBerkeleyDbMetadata(data) { // We are only interested in Hash DB. Other types are B-Tree, Queue, Heap, etc. const magicNumber = data.readUInt32LE(12); if (magicNumber !== types_1.MagicNumber.DB_HASH) { throw new types_2.ParserError('Unexpected database magic number', { magicNumber }); } // The first page of the database must be a Hash DB metadata page. const pageType = data.readUInt8(25); if (pageType !== types_1.DatabasePageType.P_HASHMETA) { throw new types_2.ParserError('Unexpected page type', { pageType }); } const encryptionAlgorithm = data.readUInt8(24); if (encryptionAlgorithm !== 0) { throw new types_2.ParserError('Encrypted databases are not supported', { encryptionAlgorithm, }); } // We will be pre-allocating some memory for the entries in the database. // Choose a very high, possibly unrealistic number, for the number of installed // packages on the system. We don't want to allocate too much memory. const entriesCount = data.readUInt32LE(88); if (entriesCount < 0 || entriesCount > 50000) { throw new types_2.ParserError('Invalid number of entries in the database', { entriesCount, }); } } exports.validateBerkeleyDbMetadata = validateBerkeleyDbMetadata; /** * Exported for testing */ function validatePageSize(pageSize) { if (!validPageSizes.includes(pageSize)) { throw new types_2.ParserError('Invalid page size', { pageSize }); } } exports.validatePageSize = validatePageSize; //# sourceMappingURL=index.js.map /***/ }), /***/ 45776: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /** * Every entry in the index is a 2-byte offset that points somewhere in the current database page. */ exports.HASH_INDEX_ENTRY_SIZE = 2; /** * Every DB page has a 26 bytes header at the start of the page. */ exports.DATABASE_PAGE_HEADER_SIZE = 26; /** * Every BerkeleyDB will contain a magic number that additionally proves that * the file is of a particular type. */ var MagicNumber; (function (MagicNumber) { MagicNumber[MagicNumber["DB_HASH"] = 398689] = "DB_HASH"; })(MagicNumber = exports.MagicNumber || (exports.MagicNumber = {})); /** * Every page in the database has a particular type. * These are the only types we need for fully reading the list of packages. */ var DatabasePageType; (function (DatabasePageType) { DatabasePageType[DatabasePageType["P_OVERFLOW"] = 7] = "P_OVERFLOW"; DatabasePageType[DatabasePageType["P_HASHMETA"] = 8] = "P_HASHMETA"; DatabasePageType[DatabasePageType["P_HASH"] = 13] = "P_HASH"; })(DatabasePageType = exports.DatabasePageType || (exports.DatabasePageType = {})); /** * We are only interested in Hash pages of type Overflow since they are the only ones containing data. */ var HashPageType; (function (HashPageType) { HashPageType[HashPageType["H_OFFPAGE"] = 3] = "H_OFFPAGE"; })(HashPageType = exports.HashPageType || (exports.HashPageType = {})); //# sourceMappingURL=types.js.map /***/ }), /***/ 76713: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const berkeleydb_1 = __webpack_require__(40218); const rpm_1 = __webpack_require__(22604); const sql_js_1 = __webpack_require__(26657); /** * Get a list of packages given a Buffer that contains an RPM database in BerkeleyDB format. * The database is inspected as best-effort, returning all valid/readable entries. * @param data An RPM database in BerkeleyDB format. */ async function getPackages(data) { try { const berkeleyDbValues = await berkeleydb_1.bufferToHashDbValues(data); let packagesSkipped = 0; let packagesProcessed = 0; const rpmPackageInfos = new Array(); for (const entry of berkeleyDbValues) { try { const packageInfo = await rpm_1.bufferToPackageInfo(entry); if (packageInfo !== undefined) { rpmPackageInfos.push(packageInfo); packagesProcessed += 1; } else { packagesSkipped += 1; } } catch (error) { packagesSkipped += 1; } } return { response: rpmPackageInfos, rpmMetadata: { packagesProcessed, packagesSkipped, }, }; } catch (error) { return { response: [], error: error, }; } } exports.getPackages = getPackages; function formatRpmPackageVersion(packageInfo) { if (packageInfo.epoch === undefined || packageInfo.epoch === 0) { return `${packageInfo.version}-${packageInfo.release}`; } return `${packageInfo.epoch}:${packageInfo.version}-${packageInfo.release}`; } exports.formatRpmPackageVersion = formatRpmPackageVersion; /** * Get a list of packages given a file path to an Sqlite RPM packages DB. * The database is inspected as best-effort, returning all valid/readable entries. * @param sqliteFilePath A path to an RPM sqlite Packages DB. */ async function getPackagesSqlite(sqliteDbBuffer) { try { const packageInfoBlobs = await getBlobsFromPackagesTableSqliteDb(sqliteDbBuffer); const packages = await Promise.all(packageInfoBlobs.map((data) => rpm_1.bufferToPackageInfo(data))); return { response: packages }; } catch (error) { return { response: [], error: error }; } } exports.getPackagesSqlite = getPackagesSqlite; // TODO: revisit when new version of sql.js is available // OR we're able to use sqlite3 (Snyk CLI limitation with native modules) async function getBlobsFromPackagesTableSqliteDb(sqliteDbBuffer) { const SQL = await sql_js_1.default(); const db = new SQL.Database(sqliteDbBuffer); const dbContent = db.exec('SELECT blob FROM Packages'); const packagesInfoBlobs = dbContent[0].values; db.close(); return packagesInfoBlobs.map((data) => Buffer.from(data[0])); } //# sourceMappingURL=index.js.map /***/ }), /***/ 34808: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const event_loop_spinner_1 = __webpack_require__(77158); const types_1 = __webpack_require__(61668); const types_2 = __webpack_require__(98590); /** * Iterate through RPM metadata entries to build the full package data. * @param entries Entries that were previously extracted from a BerkeleyDB blob. */ async function getPackageInfo(entries) { const packageInfo = {}; for (const entry of entries) { switch (entry.info.tag) { case types_1.RpmTag.NAME: if (entry.info.type !== types_1.RpmType.STRING) { throw new types_2.ParserError('Unexpected type for name tag', { type: entry.info.type, }); } packageInfo.name = extractString(entry.data); break; case types_1.RpmTag.RELEASE: if (entry.info.type !== types_1.RpmType.STRING) { throw new types_2.ParserError('Unexpected type for release tag', { type: entry.info.type, }); } packageInfo.release = extractString(entry.data); break; case types_1.RpmTag.ARCH: if (entry.info.type !== types_1.RpmType.STRING) { throw new types_2.ParserError('Unexpected type for arch tag', { type: entry.info.type, }); } packageInfo.arch = extractString(entry.data); break; case types_1.RpmTag.EPOCH: if (entry.info.type !== types_1.RpmType.INT32) { throw new types_2.ParserError('Unexpected type for epoch tag', { type: entry.info.type, }); } packageInfo.epoch = entry.data.readInt32BE(0); break; case types_1.RpmTag.SIZE: if (entry.info.type !== types_1.RpmType.INT32) { throw new types_2.ParserError('Unexpected type for size tag', { type: entry.info.type, }); } packageInfo.size = entry.data.readInt32BE(0); break; case types_1.RpmTag.VERSION: if (entry.info.type !== types_1.RpmType.STRING) { throw new types_2.ParserError('Unexpected type for version tag', { type: entry.info.type, }); } packageInfo.version = extractString(entry.data); break; case types_1.RpmTag.MODULARITYLABEL: if (entry.info.type !== types_1.RpmType.STRING) { throw new types_2.ParserError('Unexpected type for module tag', { type: entry.info.type, }); } packageInfo.module = extractString(entry.data); break; default: break; } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } return isPackageInfo(packageInfo) ? packageInfo : undefined; } exports.getPackageInfo = getPackageInfo; /** * The content may be padded with zeros so we can't directly convert it to string. * Find the first 0 byte which indicates where the string ends. */ function extractString(data) { const contentEnd = data.indexOf(0); return data.slice(0, contentEnd).toString('utf-8'); } /** * Type checks to assert we are dealing with the expected type. */ function isPackageInfo(packageInfo) { return (packageInfo.name !== undefined && packageInfo.version !== undefined && packageInfo.release !== undefined && packageInfo.size !== undefined); } //# sourceMappingURL=extensions.js.map /***/ }), /***/ 65224: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const event_loop_spinner_1 = __webpack_require__(77158); const types_1 = __webpack_require__(61668); const types_2 = __webpack_require__(98590); /** * Transform a blob of metadadata into addressable RPM package entries. * The entries need to be further processed to extract package information. * @param data A blob of RPM metadata, as stored inside BerkeleyDB. */ async function headerImport(data) { const indexLength = data.readInt32BE(0); const dataLength = data.readInt32BE(4); if (indexLength <= 0 || indexLength > 50000) { // Ensure we don't allocate something crazy... throw new types_2.ParserError('Invalid index length', { indexLength }); } const entryInfos = new Array(); // Skip the first 2 items (index and data lengths) const dataStart = 8 + indexLength * types_1.ENTRY_INFO_SIZE; const index = data.slice(8, indexLength * types_1.ENTRY_INFO_SIZE); for (let i = 0; i < indexLength; i++) { const entry = index.slice(i * types_1.ENTRY_INFO_SIZE, i * types_1.ENTRY_INFO_SIZE + types_1.ENTRY_INFO_SIZE); if (entry.length < types_1.ENTRY_INFO_SIZE) { continue; } const entryInfo = { tag: entry.readInt32BE(0), type: entry.readUInt32BE(4), offset: entry.readInt32BE(8), count: entry.readUInt32BE(12), }; if (types_1.PRIVATE_RPM_TAGS.includes(entryInfo.tag)) { continue; } entryInfos.push(entryInfo); if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } return regionSwab(data, entryInfos, dataStart, dataLength); } exports.headerImport = headerImport; async function regionSwab(data, entryInfos, dataStart, dataLength) { const indexEntries = new Array(entryInfos.length); for (let i = 0; i < entryInfos.length; i++) { const entryInfo = entryInfos[i]; const entryLength = i < entryInfos.length - 1 ? entryInfos[i + 1].offset - entryInfo.offset : dataLength - entryInfo.offset; const entryStart = dataStart + entryInfo.offset; const entryEnd = entryStart + entryLength; const indexEntry = { info: entryInfo, data: data.slice(entryStart, entryEnd), length: entryLength, }; indexEntries[i] = indexEntry; if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } return indexEntries; } //# sourceMappingURL=header.js.map /***/ }), /***/ 22604: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const header_1 = __webpack_require__(65224); const extensions_1 = __webpack_require__(34808); /** * Extracts as much package information as available from a blob of RPM metadata. * Returns undefined if the package cannot be constructed due to missing or corrupt data. * @param data A blob of RPM metadata, as stored inside BerkeleyDB. */ async function bufferToPackageInfo(data) { const entries = await header_1.headerImport(data); const packageInfo = await extensions_1.getPackageInfo(entries); return packageInfo; } exports.bufferToPackageInfo = bufferToPackageInfo; //# sourceMappingURL=index.js.map /***/ }), /***/ 61668: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /** * Size of an RPM metadata entry in bytes. */ exports.ENTRY_INFO_SIZE = 16; /** https://github.com/rpm-software-management/rpm/blob/ad1cad7e6a5def8b6036b90f2634297eda79dc7d/lib/rpmtag.h#L16-L25 */ exports.PRIVATE_RPM_TAGS = [ 61, 62, 63, 64, 100, 256, ]; var RpmTag; (function (RpmTag) { RpmTag[RpmTag["NAME"] = 1000] = "NAME"; RpmTag[RpmTag["VERSION"] = 1001] = "VERSION"; RpmTag[RpmTag["RELEASE"] = 1002] = "RELEASE"; RpmTag[RpmTag["EPOCH"] = 1003] = "EPOCH"; RpmTag[RpmTag["SIZE"] = 1009] = "SIZE"; RpmTag[RpmTag["ARCH"] = 1022] = "ARCH"; RpmTag[RpmTag["MODULARITYLABEL"] = 5096] = "MODULARITYLABEL"; })(RpmTag = exports.RpmTag || (exports.RpmTag = {})); var RpmType; (function (RpmType) { RpmType[RpmType["NULL"] = 0] = "NULL"; RpmType[RpmType["CHAR"] = 1] = "CHAR"; RpmType[RpmType["INT8"] = 2] = "INT8"; RpmType[RpmType["INT16"] = 3] = "INT16"; RpmType[RpmType["INT32"] = 4] = "INT32"; RpmType[RpmType["INT64"] = 5] = "INT64"; RpmType[RpmType["STRING"] = 6] = "STRING"; RpmType[RpmType["BIN"] = 7] = "BIN"; RpmType[RpmType["STRING_ARRAY"] = 8] = "STRING_ARRAY"; RpmType[RpmType["I18NSTRING"] = 9] = "I18NSTRING"; })(RpmType = exports.RpmType || (exports.RpmType = {})); //# sourceMappingURL=types.js.map /***/ }), /***/ 98590: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); class ParserError extends Error { constructor(message, context) { super(message); Error.captureStackTrace(this, this.constructor); this.context = context; } } exports.ParserError = ParserError; //# sourceMappingURL=types.js.map /***/ }), /***/ 49556: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.OutOfSyncError = exports.inspect = void 0; const tslib_1 = __webpack_require__(58432); const fs = __webpack_require__(57147); const path = __webpack_require__(71017); const crypto = __webpack_require__(6113); const subProcess = __webpack_require__(85468); const cocoapods_lockfile_parser_1 = __webpack_require__(84537); const legacy_1 = __webpack_require__(3042); // Compile-time check that we are implementing the plugin API properly // eslint-disable-next-line @typescript-eslint/no-unused-vars const _ = { pluginName() { return "snyk-cocoapods-plugin"; }, inspect, }; const MANIFEST_FILE_NAMES = [ "CocoaPods.podfile.yaml", "CocoaPods.podfile", "Podfile", "Podfile.rb", ]; const LOCKFILE_NAME = "Podfile.lock"; function inspect(root, targetFile, options) { return tslib_1.__awaiter(this, void 0, void 0, function* () { if (!options) { options = { dev: false }; } if (!("strictOutOfSync" in options)) { options.strictOutOfSync = false; } if (options.subProject) { throw new Error("The CocoaPods plugin doesn't support specifying a subProject!"); } let lockfilePath; function expectToFindLockfile(dir = '.') { return tslib_1.__awaiter(this, void 0, void 0, function* () { const discoveredLockfilePath = yield findLockfile(root, dir); if (!discoveredLockfilePath) { throw new Error("Could not find lockfile \"Podfile.lock\"! This might be resolved by running `pod install`."); } return discoveredLockfilePath; }); } let manifestFilePath; if (targetFile) { const { base, dir } = path.parse(targetFile); if (base === LOCKFILE_NAME) { lockfilePath = targetFile; manifestFilePath = yield findManifestFile(root, dir); } else if (MANIFEST_FILE_NAMES.indexOf(base) !== -1) { const absTargetFilePath = path.join(root, targetFile); if (!(yield fsExists(absTargetFilePath))) { throw new Error(`Given target file ("${targetFile}") doesn't exist!`); } manifestFilePath = targetFile; lockfilePath = yield expectToFindLockfile(dir); } else { throw new Error("Unexpected name for target file!"); } } else { manifestFilePath = yield findManifestFile(root); lockfilePath = yield expectToFindLockfile(); } const absLockfilePath = path.join(root, lockfilePath); if (options.strictOutOfSync) { if (!manifestFilePath) { throw new Error("Option `--strict-out-of-sync=true` given, but no manifest file could be found!"); } const absManifestFilePath = path.join(root, manifestFilePath); const result = yield verifyChecksum(absManifestFilePath, absLockfilePath); if (result === ChecksumVerificationResult.NoChecksumInLockfile) { throw new Error("Option `--strict-out-of-sync=true` given, but lockfile doesn't encode checksum of Podfile! " + "Try to update the CocoaPods integration via \"pod install\" or omit the option."); } if (result === ChecksumVerificationResult.Invalid) { throw new OutOfSyncError(manifestFilePath, lockfilePath); } } const plugin = { meta: {}, name: 'cocoapods', runtime: yield cocoapodsVersion(root), targetFile: manifestFilePath || lockfilePath, }; const depTree = yield getAllDeps(absLockfilePath); return { package: depTree, plugin, }; }); } exports.inspect = inspect; function fsExists(pathToTest) { return tslib_1.__awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => { try { fs.exists(pathToTest, (exists) => resolve(exists)); } catch (error) { reject(error); } }); }); } function fsReadFile(filename) { return tslib_1.__awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => { fs.readFile(filename, 'utf8', (err, data) => { if (err) { reject(err); return; } resolve(data); }); }); }); } function findManifestFile(root, dir = '.') { return tslib_1.__awaiter(this, void 0, void 0, function* () { for (const manifestFileName of MANIFEST_FILE_NAMES) { const targetFilePath = path.join(root, dir, manifestFileName); if (yield fsExists(targetFilePath)) { return path.join(dir, manifestFileName); } } }); } function findLockfile(root, dir = '.') { return tslib_1.__awaiter(this, void 0, void 0, function* () { const lockfilePath = path.join(root, dir, LOCKFILE_NAME); if (yield fsExists(lockfilePath)) { return path.join(dir, LOCKFILE_NAME); } }); } var ChecksumVerificationResult; (function (ChecksumVerificationResult) { ChecksumVerificationResult[ChecksumVerificationResult["Valid"] = 0] = "Valid"; ChecksumVerificationResult[ChecksumVerificationResult["Invalid"] = 1] = "Invalid"; ChecksumVerificationResult[ChecksumVerificationResult["NoChecksumInLockfile"] = 2] = "NoChecksumInLockfile"; })(ChecksumVerificationResult || (ChecksumVerificationResult = {})); function verifyChecksum(manifestFilePath, lockfilePath) { return tslib_1.__awaiter(this, void 0, void 0, function* () { const manifestFileContents = yield fsReadFile(manifestFilePath); const checksum = crypto.createHash('sha1').update(manifestFileContents).digest('hex'); const parser = yield cocoapods_lockfile_parser_1.LockfileParser.readFile(lockfilePath); if (parser.podfileChecksum === undefined) { return ChecksumVerificationResult.NoChecksumInLockfile; } else if (parser.podfileChecksum === checksum) { return ChecksumVerificationResult.Valid; } else { return ChecksumVerificationResult.Invalid; } }); } function getAllDeps(lockfilePath) { return tslib_1.__awaiter(this, void 0, void 0, function* () { let parser; try { parser = yield cocoapods_lockfile_parser_1.LockfileParser.readFile(lockfilePath); } catch (error) { throw new Error(`Error while parsing ${LOCKFILE_NAME}:\n${error.message}`); } const graph = parser.toDepGraph(); return (0, legacy_1.graphToDepTree)(graph, "cocoapods"); }); } function cocoapodsVersion(root) { return tslib_1.__awaiter(this, void 0, void 0, function* () { let podVersionOutput = ''; try { // 1st: try to run CocoaPods via bundler podVersionOutput = yield subProcess.execute('bundle exec pod', ['--version'], { cwd: root }); } catch (_a) { try { // 2nd: try to run CocoaPods directly podVersionOutput = yield subProcess.execute('pod', ['--version'], { cwd: root }); } catch (_b) { // intentionally empty } } return podVersionOutput.trim(); }); } class OutOfSyncError extends Error { constructor(manifestFileName, lockfileName) { super(`Your Podfile ("${manifestFileName}") is not in sync ` + `with your lockfile ("${lockfileName}"). ` + `Please run "pod install" and try again.`); this.code = 422; this.name = 'OutOfSyncError'; Error.captureStackTrace(this, OutOfSyncError); } } exports.OutOfSyncError = OutOfSyncError; //# sourceMappingURL=index.js.map /***/ }), /***/ 85468: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.execute = void 0; const childProcess = __webpack_require__(32081); const shescape_1 = __webpack_require__(79114); function execute(command, args = [], options) { const spawnOptions = { shell: true }; if (options && options.cwd) { spawnOptions.cwd = options.cwd; } args = (0, shescape_1.quoteAll)(args, spawnOptions); return new Promise((resolve, reject) => { let stdout = ''; let stderr = ''; const proc = childProcess.spawn(command, args, spawnOptions); proc.stdout.on('data', (data) => { stdout = stdout + data; }); proc.stderr.on('data', (data) => { stderr = stderr + data; }); proc.on('close', (code) => { if (code !== 0) { return reject(new Error(stdout || stderr)); } resolve(stdout || stderr); }); }); } exports.execute = execute; //# sourceMappingURL=sub-process.js.map /***/ }), /***/ 50437: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DepGraphBuilder = void 0; const graphlib = __webpack_require__(54105); const dep_graph_1 = __webpack_require__(56509); class DepGraphBuilder { constructor(pkgManager, rootPkg) { this._pkgs = {}; this._pkgNodes = {}; const graph = new graphlib.Graph({ directed: true, multigraph: false, compound: false, }); if (!rootPkg) { rootPkg = { name: '_root', version: '0.0.0', }; } this._rootNodeId = 'root-node'; this._rootPkgId = DepGraphBuilder._getPkgId(rootPkg); this._pkgs[this._rootPkgId] = rootPkg; graph.setNode(this._rootNodeId, { pkgId: this._rootPkgId }); this._pkgNodes[this._rootPkgId] = new Set([this._rootNodeId]); this._graph = graph; this._pkgManager = pkgManager; } get rootNodeId() { return this._rootNodeId; } static _getPkgId(pkg) { return `${pkg.name}@${pkg.version || ''}`; } getPkgs() { return Object.values(this._pkgs); } // TODO: this can create disconnected nodes addPkgNode(pkgInfo, nodeId, nodeInfo) { if (nodeId === this._rootNodeId) { throw new Error('DepGraphBuilder.addPkgNode() cant override root node'); } const pkgId = DepGraphBuilder._getPkgId(pkgInfo); this._pkgs[pkgId] = pkgInfo; this._pkgNodes[pkgId] = this._pkgNodes[pkgId] || new Set(); this._pkgNodes[pkgId].add(nodeId); this._graph.setNode(nodeId, { pkgId, info: nodeInfo }); return this; } // TODO: this can create cycles connectDep(parentNodeId, depNodeId) { if (!this._graph.hasNode(parentNodeId)) { throw new Error('parentNodeId does not exist'); } if (!this._graph.hasNode(depNodeId)) { throw new Error('depNodeId does not exist'); } this._graph.setEdge(parentNodeId, depNodeId); return this; } build() { return new dep_graph_1.DepGraphImpl(this._graph, this._rootNodeId, this._pkgs, this._pkgNodes, this._pkgManager); } } exports.DepGraphBuilder = DepGraphBuilder; //# sourceMappingURL=builder.js.map /***/ }), /***/ 98491: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createFromJSON = exports.SUPPORTED_SCHEMA_RANGE = void 0; const semver = __webpack_require__(78502); const graphlib = __webpack_require__(54105); const errors_1 = __webpack_require__(24167); const validate_graph_1 = __webpack_require__(41825); const dep_graph_1 = __webpack_require__(56509); exports.SUPPORTED_SCHEMA_RANGE = '^1.0.0'; /** * Create a DepGraph instance from a JSON representation of a dep graph. This * is typically used after passing the graph over the wire as `DepGraphData`. */ function createFromJSON(depGraphData) { validateDepGraphData(depGraphData); const graph = new graphlib.Graph({ directed: true, multigraph: false, compound: false, }); const pkgs = {}; const pkgNodes = {}; for (const { id, info } of depGraphData.pkgs) { pkgs[id] = info.version ? info : Object.assign(Object.assign({}, info), { version: undefined }); } for (const node of depGraphData.graph.nodes) { const pkgId = node.pkgId; if (!pkgNodes[pkgId]) { pkgNodes[pkgId] = new Set(); } pkgNodes[pkgId].add(node.nodeId); graph.setNode(node.nodeId, { pkgId, info: node.info }); } for (const node of depGraphData.graph.nodes) { for (const depNodeId of node.deps) { graph.setEdge(node.nodeId, depNodeId.nodeId); } } validate_graph_1.validateGraph(graph, depGraphData.graph.rootNodeId, pkgs, pkgNodes); return new dep_graph_1.DepGraphImpl(graph, depGraphData.graph.rootNodeId, pkgs, pkgNodes, depGraphData.pkgManager); } exports.createFromJSON = createFromJSON; function assert(condition, msg) { if (!condition) { throw new errors_1.ValidationError(msg); } } function validateDepGraphData(depGraphData) { assert(!!semver.valid(depGraphData.schemaVersion) && semver.satisfies(depGraphData.schemaVersion, exports.SUPPORTED_SCHEMA_RANGE), `dep-graph schemaVersion not in "${exports.SUPPORTED_SCHEMA_RANGE}"`); assert(depGraphData.pkgManager && !!depGraphData.pkgManager.name, '.pkgManager.name is missing'); const pkgsMap = depGraphData.pkgs.reduce((acc, cur) => { assert(!(cur.id in acc), 'more than one pkg with same id'); assert(!!cur.info, '.pkgs item missing .info'); acc[cur.id] = cur.info; return acc; }, {}); const nodesMap = depGraphData.graph.nodes.reduce((acc, cur) => { assert(!(cur.nodeId in acc), 'more than on node with same id'); acc[cur.nodeId] = cur; return acc; }, {}); const rootNodeId = depGraphData.graph.rootNodeId; const rootNode = nodesMap[rootNodeId]; assert(rootNodeId in nodesMap, `.${rootNodeId} root graph node is missing`); const rootPkgId = rootNode.pkgId; assert(rootPkgId in pkgsMap, `.${rootPkgId} root pkg missing`); assert(nodesMap[rootNodeId].pkgId === rootPkgId, `the root node .pkgId should be "${rootPkgId}"`); const pkgIds = Object.keys(pkgsMap); // NOTE: this name@version check is very strict, // we can relax it later, it just makes things easier now assert(pkgIds.filter((pkgId) => pkgId !== dep_graph_1.DepGraphImpl.getPkgId(pkgsMap[pkgId])) .length === 0, 'pkgs ids should be name@version'); assert(Object.values(nodesMap).filter((node) => !(node.pkgId in pkgsMap)) .length === 0, 'some instance nodes belong to non-existing pkgIds'); assert(Object.values(pkgsMap).filter((pkg) => !pkg.name) .length === 0, 'some .pkgs elements have no .name field'); } //# sourceMappingURL=create-from-json.js.map /***/ }), /***/ 56509: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DepGraphImpl = void 0; const _isEqual = __webpack_require__(72307); const graphlib = __webpack_require__(54105); const create_from_json_1 = __webpack_require__(98491); class DepGraphImpl { constructor(_graph, _rootNodeId, _pkgs, _pkgNodes, _pkgManager) { this._graph = _graph; this._rootNodeId = _rootNodeId; this._pkgs = _pkgs; this._pkgNodes = _pkgNodes; this._pkgManager = _pkgManager; this._countNodePathsToRootCache = new Map(); this._rootPkgId = _graph.node(_rootNodeId).pkgId; this._pkgList = Object.values(_pkgs); this._depPkgsList = this._pkgList.filter((pkg) => pkg !== this.rootPkg); } static getPkgId(pkg) { return `${pkg.name}@${pkg.version || ''}`; } get pkgManager() { return this._pkgManager; } get rootPkg() { return this._pkgs[this._rootPkgId]; } get rootNodeId() { return this._rootNodeId; } /** * Get all unique packages in the graph (including the root package) */ getPkgs() { return this._pkgList; } /** * Get all unique packages in the graph (excluding the root package) */ getDepPkgs() { return this._depPkgsList; } getPkgNodes(pkg) { const pkgId = DepGraphImpl.getPkgId(pkg); const nodes = []; for (const nodeId of Array.from(this._pkgNodes[pkgId])) { const graphNode = this.getGraphNode(nodeId); nodes.push({ info: graphNode.info || {}, }); } return nodes; } getNode(nodeId) { return this.getGraphNode(nodeId).info || {}; } getNodePkg(nodeId) { return this._pkgs[this.getGraphNode(nodeId).pkgId]; } getPkgNodeIds(pkg) { const pkgId = DepGraphImpl.getPkgId(pkg); if (!this._pkgs[pkgId]) { throw new Error(`no such pkg: ${pkgId}`); } return Array.from(this._pkgNodes[pkgId]); } getNodeDepsNodeIds(nodeId) { const deps = this._graph.successors(nodeId); if (!deps) { throw new Error(`no such node: ${nodeId}`); } return deps; } getNodeParentsNodeIds(nodeId) { const parents = this._graph.predecessors(nodeId); if (!parents) { throw new Error(`no such node: ${nodeId}`); } return parents; } hasCycles() { // `isAcyclic` is expensive, so memoize if (this._hasCycles === undefined) { this._hasCycles = !graphlib.alg.isAcyclic(this._graph); } return this._hasCycles; } pkgPathsToRoot(pkg, opts) { const pathsToRoot = []; const limit = opts === null || opts === void 0 ? void 0 : opts.limit; for (const nodeId of this.getPkgNodeIds(pkg)) { const pathsFromNodeToRoot = this.pathsFromNodeToRoot(nodeId, [], { limit, }); for (const path of pathsFromNodeToRoot) { pathsToRoot.push(path); } if (limit && pathsToRoot.length >= limit) { break; } } // note: sorting to get shorter paths first - // it's nicer - and better resembles older behaviour return pathsToRoot.sort((a, b) => a.length - b.length); } countPathsToRoot(pkg) { let count = 0; for (const nodeId of this.getPkgNodeIds(pkg)) { count += this.countNodePathsToRoot(nodeId); } return count; } equals(other, { compareRoot = true } = {}) { let otherDepGraph; if (other instanceof DepGraphImpl) { otherDepGraph = other; } else { // At runtime theoretically we can have multiple versions of // @snyk/dep-graph. If "other" is not an instance of the same class it is // safer to rebuild it from JSON. otherDepGraph = create_from_json_1.createFromJSON(other.toJSON()); } // In theory, for the graphs created by standard means, `_.isEquals(this._data, otherDepGraph._data)` // should suffice, since node IDs will be generated in a predictable way. // However, there might be different versions of graph and inconsistencies // in the ordering of the arrays, so we perform a deep comparison. return this.nodeEquals(this, this.rootNodeId, otherDepGraph, otherDepGraph.rootNodeId, compareRoot); } directDepsLeadingTo(pkg) { const pkgNodes = this.getPkgNodeIds(pkg); const directDeps = this.getNodeDepsNodeIds(this.rootNodeId); const nodes = directDeps.filter((directDep) => { const reachableNodes = graphlib.alg.postorder(this._graph, [directDep]); return reachableNodes.filter((node) => pkgNodes.includes(node)).length; }); return nodes.map((node) => this.getNodePkg(node)); } /** * Create a JSON representation of a dep graph. This is typically used to * send the dep graph over the wire */ toJSON() { const nodeIds = this._graph.nodes(); const nodes = nodeIds.reduce((acc, nodeId) => { const deps = (this._graph.successors(nodeId) || []).map((depNodeId) => ({ nodeId: depNodeId, })); const node = this._graph.node(nodeId); const elem = { nodeId, pkgId: node.pkgId, deps, }; if (node.info && Object.keys(node.info).length > 0) { elem.info = node.info; } acc.push(elem); return acc; }, []); const pkgs = Object.keys(this._pkgs).map((pkgId) => ({ id: pkgId, info: this._pkgs[pkgId], })); return { schemaVersion: DepGraphImpl.SCHEMA_VERSION, pkgManager: this._pkgManager, pkgs, graph: { rootNodeId: this._rootNodeId, nodes, }, }; } nodeEquals(graphA, nodeIdA, graphB, nodeIdB, compareRoot, traversedPairs = new Set()) { // Skip root nodes comparision if needed. if (compareRoot || (nodeIdA !== graphA.rootNodeId && nodeIdB !== graphB.rootNodeId)) { const pkgA = graphA.getNodePkg(nodeIdA); const pkgB = graphB.getNodePkg(nodeIdB); // Compare PkgInfo (name and version). if (!_isEqual(pkgA, pkgB)) { return false; } const infoA = graphA.getNode(nodeIdA); const infoB = graphB.getNode(nodeIdB); // Compare NodeInfo (VersionProvenance and labels). if (!_isEqual(infoA, infoB)) { return false; } } let depsA = graphA.getNodeDepsNodeIds(nodeIdA); let depsB = graphB.getNodeDepsNodeIds(nodeIdB); // Number of dependencies should be the same. if (depsA.length !== depsB.length) { return false; } // Sort dependencies by name@version string. const sortFn = (graph) => (idA, idB) => { const pkgA = graph.getNodePkg(idA); const pkgB = graph.getNodePkg(idB); return DepGraphImpl.getPkgId(pkgA).localeCompare(DepGraphImpl.getPkgId(pkgB)); }; depsA = depsA.sort(sortFn(graphA)); depsB = depsB.sort(sortFn(graphB)); // Compare Each dependency recursively. for (let i = 0; i < depsA.length; i++) { const pairKey = `${depsA[i]}_${depsB[i]}`; // Prevent cycles. if (traversedPairs.has(pairKey)) { continue; } traversedPairs.add(pairKey); if (!this.nodeEquals(graphA, depsA[i], graphB, depsB[i], compareRoot, traversedPairs)) { return false; } } return true; } getGraphNode(nodeId) { const node = this._graph.node(nodeId); if (!node) { throw new Error(`no such node: ${nodeId}`); } return node; } pathsFromNodeToRoot(nodeId, ancestors = [], opts) { const parentNodesIds = this.getNodeParentsNodeIds(nodeId); const pkgInfo = this.getNodePkg(nodeId); if (parentNodesIds.length === 0) { return [[pkgInfo]]; } const allPaths = []; ancestors = ancestors.concat(nodeId); const limit = opts.limit; for (const id of parentNodesIds) { if (ancestors.includes(id)) continue; const pathsFromNodeToRoot = this.pathsFromNodeToRoot(id, ancestors, opts); pathsFromNodeToRoot.forEach((path) => allPaths.push([pkgInfo].concat(path))); if (limit && allPaths.length >= limit) { break; } } return allPaths; } countNodePathsToRoot(nodeId, ancestors = []) { if (ancestors.includes(nodeId)) { return 0; } if (this._countNodePathsToRootCache.has(nodeId)) { return this._countNodePathsToRootCache.get(nodeId) || 0; } const parentNodesIds = this.getNodeParentsNodeIds(nodeId); if (parentNodesIds.length === 0) { this._countNodePathsToRootCache.set(nodeId, 1); return 1; } ancestors = ancestors.concat(nodeId); const count = parentNodesIds.reduce((acc, parentNodeId) => { return acc + this.countNodePathsToRoot(parentNodeId, ancestors); }, 0); this._countNodePathsToRootCache.set(nodeId, count); return count; } } exports.DepGraphImpl = DepGraphImpl; DepGraphImpl.SCHEMA_VERSION = '1.2.0'; //# sourceMappingURL=dep-graph.js.map /***/ }), /***/ 36305: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CustomError = void 0; class CustomError extends Error { constructor(message) { super(message); Object.setPrototypeOf(this, CustomError.prototype); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; } } exports.CustomError = CustomError; //# sourceMappingURL=custom-error.js.map /***/ }), /***/ 24167: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ValidationError = void 0; const validation_error_1 = __webpack_require__(47216); Object.defineProperty(exports, "ValidationError", ({ enumerable: true, get: function () { return validation_error_1.ValidationError; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 47216: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ValidationError = void 0; const custom_error_1 = __webpack_require__(36305); class ValidationError extends custom_error_1.CustomError { constructor(message) { super(message); Object.setPrototypeOf(this, ValidationError.prototype); } } exports.ValidationError = ValidationError; //# sourceMappingURL=validation-error.js.map /***/ }), /***/ 41825: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.validateGraph = void 0; const graphlib = __webpack_require__(54105); const errors_1 = __webpack_require__(24167); function assert(condition, msg) { if (!condition) { throw new errors_1.ValidationError(msg); } } function validateGraph(graph, rootNodeId, pkgs, pkgNodes) { assert((graph.predecessors(rootNodeId) || []).length === 0, `"${rootNodeId}" is not really the root`); const reachableFromRoot = graphlib.alg.postorder(graph, [rootNodeId]); const nodeIds = graph.nodes(); assert(JSON.stringify(nodeIds.sort()) === JSON.stringify(reachableFromRoot.sort()), 'not all graph nodes are reachable from root'); const pkgIds = Object.keys(pkgs); const pkgsWithoutInstances = pkgIds.filter((pkgId) => !pkgNodes[pkgId] || pkgNodes[pkgId].size === 0); assert(pkgsWithoutInstances.length === 0, 'not all pkgs have instance nodes'); } exports.validateGraph = validateGraph; //# sourceMappingURL=validate-graph.js.map /***/ }), /***/ 69785: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.dfs = void 0; const each = __webpack_require__(43590); /* * A helper that preforms a pre- or post-order traversal on the input graph * and returns the nodes in the order they were visited. If the graph is * undirected then this algorithm will navigate using neighbors. If the graph * is directed then this algorithm will navigate using successors. * * Order must be one of "pre" or "post". */ function dfs(g, vs, order) { if (!Array.isArray(vs)) { vs = [vs]; } const navigation = (g.isDirected() ? g.successors : g.neighbors).bind(g); const acc = []; const visited = {}; each(vs, (v) => { if (!g.hasNode(v)) { throw new Error('Graph does not have node: ' + v); } doDfs(g, v, order === 'post', visited, navigation, acc); }); return acc; } exports.dfs = dfs; function doDfs(g, v, postorder, visited, navigation, acc) { if (!(v in visited)) { visited[v] = true; if (!postorder) { acc.push(v); } each(navigation(v), function (w) { doDfs(g, w, postorder, visited, navigation, acc); }); if (postorder) { acc.push(v); } } } //# sourceMappingURL=dfs.js.map /***/ }), /***/ 91528: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isAcyclic = void 0; const topsort_1 = __webpack_require__(75081); function isAcyclic(g) { try { topsort_1.topsort(g); } catch (e) { if (e instanceof topsort_1.CycleException) { return false; } throw e; } return true; } exports.isAcyclic = isAcyclic; //# sourceMappingURL=is-acyclic.js.map /***/ }), /***/ 49582: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.postorder = void 0; const dfs_1 = __webpack_require__(69785); function postorder(g, vs) { return dfs_1.dfs(g, vs, 'post'); } exports.postorder = postorder; //# sourceMappingURL=postorder.js.map /***/ }), /***/ 75081: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CycleException = exports.topsort = void 0; const each = __webpack_require__(43590); const size = __webpack_require__(27946); function topsort(g) { const visited = {}; const stack = {}; const results = []; function visit(node) { if (node in stack) { throw new CycleException(); } if (!(node in visited)) { stack[node] = true; visited[node] = true; each(g.predecessors(node), visit); delete stack[node]; results.push(node); } } each(g.sinks(), visit); if (size(visited) !== g.nodeCount()) { throw new CycleException(); } return results; } exports.topsort = topsort; class CycleException extends Error { } exports.CycleException = CycleException; //# sourceMappingURL=topsort.js.map /***/ }), /***/ 55561: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Graph = void 0; /* eslint-disable prefer-rest-params */ /* eslint-disable @typescript-eslint/no-this-alias */ const constant = __webpack_require__(4254); const each = __webpack_require__(43590); const _filter = __webpack_require__(43590); const isEmpty = __webpack_require__(99245); const isFunction = __webpack_require__(98423); const isUndefined = __webpack_require__(28801); const keys = __webpack_require__(44799); const reduce = __webpack_require__(34766); const union = __webpack_require__(96744); const values = __webpack_require__(17720); const DEFAULT_EDGE_NAME = '\x00'; const GRAPH_NODE = '\x00'; const EDGE_KEY_DELIM = '\x01'; // Implementation notes: // // * Node id query functions should return string ids for the nodes // * Edge id query functions should return an "edgeObj", edge object, that is // composed of enough information to uniquely identify an edge: {v, w, name}. // * Internally we use an "edgeId", a stringified form of the edgeObj, to // reference edges. This is because we need a performant way to look these // edges up and, object properties, which have string keys, are the closest // we're going to get to a performant hashtable in JavaScript. class Graph { constructor(opts) { var _a, _b, _c; /* Number of nodes in the graph. Should only be changed by the implementation. */ this._nodeCount = 0; /* Number of edges in the graph. Should only be changed by the implementation. */ this._edgeCount = 0; this._isDirected = (_a = opts === null || opts === void 0 ? void 0 : opts.directed) !== null && _a !== void 0 ? _a : true; this._isMultigraph = (_b = opts === null || opts === void 0 ? void 0 : opts.multigraph) !== null && _b !== void 0 ? _b : false; this._isCompound = (_c = opts === null || opts === void 0 ? void 0 : opts.compound) !== null && _c !== void 0 ? _c : false; // Label for the graph itself this._label = undefined; // Defaults to be set when creating a new node this._defaultNodeLabelFn = constant(undefined); // Defaults to be set when creating a new edge this._defaultEdgeLabelFn = constant(undefined); // v -> label this._nodes = {}; if (this._isCompound) { // v -> parent this._parent = {}; // v -> children this._children = {}; this._children[GRAPH_NODE] = {}; } // v -> edgeObj this._in = {}; // u -> v -> Number this._preds = {}; // v -> edgeObj this._out = {}; // v -> w -> Number this._sucs = {}; // e -> edgeObj this._edgeObjs = {}; // e -> label this._edgeLabels = {}; } /* === Graph functions ========= */ isDirected() { return this._isDirected; } isMultigraph() { return this._isMultigraph; } isCompound() { return this._isCompound; } setGraph(label) { this._label = label; return this; } graph() { return this._label; } /* === Node functions ========== */ setDefaultNodeLabel(newDefault) { if (!isFunction(newDefault)) { newDefault = constant(newDefault); } this._defaultNodeLabelFn = newDefault; return this; } nodeCount() { return this._nodeCount; } nodes() { return keys(this._nodes); } sources() { const self = this; return _filter(this.nodes(), function (v) { return isEmpty(self._in[v]); }); } sinks() { const self = this; return _filter(this.nodes(), function (v) { return isEmpty(self._out[v]); }); } setNodes(vs, value) { const args = arguments; const self = this; each(vs, function (v) { if (args.length > 1) { self.setNode(v, value); } else { self.setNode(v); } }); return this; } setNode(v, value) { if (v in this._nodes) { if (arguments.length > 1) { this._nodes[v] = value; } return this; } this._nodes[v] = arguments.length > 1 ? value : this._defaultNodeLabelFn(v); if (this._isCompound) { this._parent[v] = GRAPH_NODE; this._children[v] = {}; this._children[GRAPH_NODE][v] = true; } this._in[v] = {}; this._preds[v] = {}; this._out[v] = {}; this._sucs[v] = {}; ++this._nodeCount; return this; } node(v) { return this._nodes[v]; } hasNode(v) { return v in this._nodes; } removeNode(v) { const self = this; if (v in this._nodes) { const removeEdge = function (e) { self.removeEdge(self._edgeObjs[e]); }; delete this._nodes[v]; if (this._isCompound) { this._removeFromParentsChildList(v); delete this._parent[v]; each(this.children(v), function (child) { self.setParent(child); }); delete this._children[v]; } each(keys(this._in[v]), removeEdge); delete this._in[v]; delete this._preds[v]; each(keys(this._out[v]), removeEdge); delete this._out[v]; delete this._sucs[v]; --this._nodeCount; } return this; } setParent(v, parent) { if (!this._isCompound) { throw new Error('Cannot set parent in a non-compound graph'); } if (isUndefined(parent)) { parent = GRAPH_NODE; } else { // Coerce parent to string parent += ''; for (let ancestor = parent; !isUndefined(ancestor); ancestor = this.parent(ancestor)) { if (ancestor === v) { throw new Error('Setting ' + parent + ' as parent of ' + v + ' would create a cycle'); } } this.setNode(parent); } this.setNode(v); this._removeFromParentsChildList(v); this._parent[v] = parent; this._children[parent][v] = true; return this; } _removeFromParentsChildList(v) { delete this._children[this._parent[v]][v]; } parent(v) { if (this._isCompound) { const parent = this._parent[v]; if (parent !== GRAPH_NODE) { return parent; } } } children(v) { if (isUndefined(v)) { v = GRAPH_NODE; } if (this._isCompound) { const children = this._children[v]; if (children) { return keys(children); } } else if (v === GRAPH_NODE) { return this.nodes(); } else if (this.hasNode(v)) { return []; } } predecessors(v) { const predsV = this._preds[v]; if (predsV) { return keys(predsV); } } successors(v) { const sucsV = this._sucs[v]; if (sucsV) { return keys(sucsV); } } neighbors(v) { const preds = this.predecessors(v); if (preds) { return union(preds, this.successors(v)); } } isLeaf(v) { let neighbors; if (this.isDirected()) { neighbors = this.successors(v); } else { neighbors = this.neighbors(v); } return neighbors.length === 0; } filterNodes(filter) { const copy = new Graph({ directed: this._isDirected, multigraph: this._isMultigraph, compound: this._isCompound, }); copy.setGraph(this.graph()); const self = this; each(this._nodes, function (value, v) { if (filter(v)) { copy.setNode(v, value); } }); each(this._edgeObjs, function (e) { if (copy.hasNode(e.v) && copy.hasNode(e.w)) { copy.setEdge(e, self.edge(e)); } }); const parents = {}; function findParent(v) { const parent = self.parent(v); if (parent === undefined || copy.hasNode(parent)) { parents[v] = parent; return parent; } else if (parent in parents) { return parents[parent]; } else { return findParent(parent); } } if (this._isCompound) { each(copy.nodes(), function (v) { copy.setParent(v, findParent(v)); }); } return copy; } /* === Edge functions ========== */ setDefaultEdgeLabel(newDefault) { if (!isFunction(newDefault)) { newDefault = constant(newDefault); } this._defaultEdgeLabelFn = newDefault; return this; } edgeCount() { return this._edgeCount; } edges() { return values(this._edgeObjs); } setPath(vs, value) { const self = this; const args = arguments; reduce(vs, function (v, w) { if (args.length > 1) { self.setEdge(v, w, value); } else { self.setEdge(v, w); } return w; }); return this; } // eslint-disable-next-line @typescript-eslint/no-unused-vars setEdge(...args) { let v, w, name, value; let valueSpecified = false; const arg0 = arguments[0]; if (typeof arg0 === 'object' && arg0 !== null && 'v' in arg0) { v = arg0.v; w = arg0.w; name = arg0.name; if (arguments.length === 2) { value = arguments[1]; valueSpecified = true; } } else { v = arg0; w = arguments[1]; name = arguments[3]; if (arguments.length > 2) { value = arguments[2]; valueSpecified = true; } } v = '' + v; w = '' + w; if (!isUndefined(name)) { name = '' + name; } const e = edgeArgsToId(this._isDirected, v, w, name); if (e in this._edgeLabels) { if (valueSpecified) { this._edgeLabels[e] = value; } return this; } if (!isUndefined(name) && !this._isMultigraph) { throw new Error('Cannot set a named edge when isMultigraph = false'); } // It didn't exist, so we need to create it. // First ensure the nodes exist. this.setNode(v); this.setNode(w); this._edgeLabels[e] = valueSpecified ? value : this._defaultEdgeLabelFn(v, w, name); const edgeObj = edgeArgsToObj(this._isDirected, v, w, name); // Ensure we add undirected edges in a consistent way. v = edgeObj.v; w = edgeObj.w; Object.freeze(edgeObj); this._edgeObjs[e] = edgeObj; incrementOrInitEntry(this._preds[w], v); incrementOrInitEntry(this._sucs[v], w); this._in[w][e] = edgeObj; this._out[v][e] = edgeObj; this._edgeCount++; return this; } edge(v, w, name) { const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); return this._edgeLabels[e]; } hasEdge(v, w, name) { const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); return e in this._edgeLabels; } removeEdge(v, w, name) { const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); const edge = this._edgeObjs[e]; if (edge) { v = edge.v; w = edge.w; delete this._edgeLabels[e]; delete this._edgeObjs[e]; decrementOrRemoveEntry(this._preds[w], v); decrementOrRemoveEntry(this._sucs[v], w); delete this._in[w][e]; delete this._out[v][e]; this._edgeCount--; } return this; } inEdges(v, u) { const inV = this._in[v]; if (inV) { const edges = values(inV); if (!u) { return edges; } return _filter(edges, function (edge) { return edge.v === u; }); } } outEdges(v, w) { const outV = this._out[v]; if (outV) { const edges = values(outV); if (!w) { return edges; } return _filter(edges, function (edge) { return edge.w === w; }); } } nodeEdges(v, w) { const inEdges = this.inEdges(v, w); if (inEdges) { return inEdges.concat(this.outEdges(v, w)); } } } exports.Graph = Graph; function incrementOrInitEntry(map, k) { if (map[k]) { map[k]++; } else { map[k] = 1; } } function decrementOrRemoveEntry(map, k) { if (!--map[k]) { delete map[k]; } } function edgeArgsToId(isDirected, v_, w_, name) { let v = '' + v_; let w = '' + w_; if (!isDirected && v > w) { const tmp = v; v = w; w = tmp; } return (v + EDGE_KEY_DELIM + w + EDGE_KEY_DELIM + (isUndefined(name) ? DEFAULT_EDGE_NAME : name)); } function edgeArgsToObj(isDirected, v_, w_, name) { let v = '' + v_; let w = '' + w_; if (!isDirected && v > w) { const tmp = v; v = w; w = tmp; } const edgeObj = { v: v, w: w }; if (name) { edgeObj.name = name; } return edgeObj; } function edgeObjToId(isDirected, edgeObj) { return edgeArgsToId(isDirected, edgeObj.v, edgeObj.w, edgeObj.name); } //# sourceMappingURL=graph.js.map /***/ }), /***/ 54105: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.alg = exports.Graph = void 0; var graph_1 = __webpack_require__(55561); Object.defineProperty(exports, "Graph", ({ enumerable: true, get: function () { return graph_1.Graph; } })); const is_acyclic_1 = __webpack_require__(91528); const postorder_1 = __webpack_require__(49582); exports.alg = { isAcyclic: is_acyclic_1.isAcyclic, postorder: postorder_1.postorder, }; //# sourceMappingURL=index.js.map /***/ }), /***/ 4570: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.partitionCycles = exports.getCycle = void 0; function getCycle(ancestors, nodeId) { if (!ancestors.includes(nodeId)) { return null; } // first item is where the cycle starts and ends. return ancestors.slice(ancestors.indexOf(nodeId)); } exports.getCycle = getCycle; function partitionCycles(nodeId, allCyclesTheNodeIsPartOf) { const cyclesStartWithThisNode = []; const cyclesWithThisNode = []; for (const cycle of allCyclesTheNodeIsPartOf) { const nodeStartsCycle = cycle[0] === nodeId; if (nodeStartsCycle) { cyclesStartWithThisNode.push(cycle); } else { cyclesWithThisNode.push(cycle); } } return { cyclesStartWithThisNode, cyclesWithThisNode }; } exports.partitionCycles = partitionCycles; //# sourceMappingURL=cycles.js.map /***/ }), /***/ 3042: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.graphToDepTree = exports.depTreeToGraph = void 0; const crypto = __webpack_require__(6113); const event_loop_spinner_1 = __webpack_require__(77158); const builder_1 = __webpack_require__(50437); const objectHash = __webpack_require__(70394); const cycles_1 = __webpack_require__(4570); const memiozation_1 = __webpack_require__(3143); function addLabel(dep, key, value) { if (!dep.labels) { dep.labels = {}; } dep.labels[key] = value; } /** * @deprecated Don't use dep trees as an intermediate step, because they are * large structures, resulting in high memory usage and high CPU costs from * serializing / deserializing. Instead, create a graph directly with * {@link DepGraphBuilder} */ async function depTreeToGraph(depTree, pkgManagerName) { const rootPkg = { name: depTree.name, version: depTree.version || undefined, }; const pkgManagerInfo = { name: pkgManagerName, }; const targetOS = depTree.targetOS; if (targetOS) { pkgManagerInfo.repositories = [ { alias: `${targetOS.name}:${targetOS.version}`, }, ]; } const builder = new builder_1.DepGraphBuilder(pkgManagerInfo, rootPkg); await buildGraph(builder, depTree, depTree.name, true); const depGraph = await builder.build(); return shortenNodeIds(depGraph); } exports.depTreeToGraph = depTreeToGraph; async function buildGraph(builder, depTree, pkgName, isRoot = false, memoizationMap = new Map()) { if (memoizationMap.has(depTree)) { return memoizationMap.get(depTree); } const getNodeId = (name, version, hashId) => `${name}@${version || ''}|${hashId}`; const depNodesIds = []; const hash = crypto.createHash('sha1'); if (depTree.versionProvenance) { hash.update(objectHash(depTree.versionProvenance)); } if (depTree.labels) { hash.update(objectHash(depTree.labels)); } const deps = depTree.dependencies || {}; // filter-out invalid null deps (shouldn't happen - but did...) const depNames = Object.keys(deps).filter((d) => !!deps[d]); for (const depName of depNames.sort()) { const dep = deps[depName]; const subtreeHash = await buildGraph(builder, dep, depName, false, memoizationMap); const depPkg = { name: depName, version: dep.version, }; const depNodeId = getNodeId(depPkg.name, depPkg.version, subtreeHash); depNodesIds.push(depNodeId); const nodeInfo = {}; if (dep.versionProvenance) { nodeInfo.versionProvenance = dep.versionProvenance; } if (dep.labels) { nodeInfo.labels = dep.labels; } builder.addPkgNode(depPkg, depNodeId, nodeInfo); hash.update(depNodeId); } const treeHash = hash.digest('hex'); let pkgNodeId; if (isRoot) { pkgNodeId = builder.rootNodeId; } else { // we don't assume depTree has a .name to support output of `npm list --json` const pkg = { name: pkgName, version: depTree.version, }; pkgNodeId = getNodeId(pkg.name, pkg.version, treeHash); const nodeInfo = {}; if (depTree.versionProvenance) { nodeInfo.versionProvenance = depTree.versionProvenance; } if (depTree.labels) { nodeInfo.labels = depTree.labels; } builder.addPkgNode(pkg, pkgNodeId, nodeInfo); } for (const depNodeId of depNodesIds) { builder.connectDep(pkgNodeId, depNodeId); } if (depNodesIds.length > 0 && event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } memoizationMap.set(depTree, treeHash); return treeHash; } async function shortenNodeIds(depGraph) { const builder = new builder_1.DepGraphBuilder(depGraph.pkgManager, depGraph.rootPkg); const nodesMap = {}; // create nodes with shorter ids for (const pkg of depGraph.getPkgs()) { const nodeIds = depGraph.getPkgNodeIds(pkg); for (let i = 0; i < nodeIds.length; i++) { const nodeId = nodeIds[i]; if (nodeId === depGraph.rootNodeId) { continue; } const nodeInfo = depGraph.getNode(nodeId); let newNodeId; if (nodeIds.length === 1) { newNodeId = `${trimAfterLastSep(nodeId, '|')}`; } else { newNodeId = `${trimAfterLastSep(nodeId, '|')}|${i + 1}`; } nodesMap[nodeId] = newNodeId; builder.addPkgNode(pkg, newNodeId, nodeInfo); } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } // connect nodes for (const pkg of depGraph.getPkgs()) { for (const nodeId of depGraph.getPkgNodeIds(pkg)) { for (const depNodeId of depGraph.getNodeDepsNodeIds(nodeId)) { const parentNode = nodesMap[nodeId] || nodeId; const childNode = nodesMap[depNodeId] || depNodeId; builder.connectDep(parentNode, childNode); } } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } return builder.build(); } /** * @deprecated Don't use dep trees. You should adapt your code to use graphs, * and enhance the dep-graph library if there is missing functionality from * the graph structure */ async function graphToDepTree(depGraphInterface, pkgType, opts = { deduplicateWithinTopLevelDeps: false }) { const depGraph = depGraphInterface; const [depTree] = await buildSubtree(depGraph, depGraph.rootNodeId, opts.deduplicateWithinTopLevelDeps ? null : false); depTree.type = depGraph.pkgManager.name; depTree.packageFormatVersion = constructPackageFormatVersion(pkgType); const targetOS = constructTargetOS(depGraph); if (targetOS) { depTree.targetOS = targetOS; } return depTree; } exports.graphToDepTree = graphToDepTree; function constructPackageFormatVersion(pkgType) { if (pkgType === 'maven') { pkgType = 'mvn'; } return `${pkgType}:0.0.1`; } function constructTargetOS(depGraph) { if (['apk', 'apt', 'deb', 'rpm', 'linux'].indexOf(depGraph.pkgManager.name) === -1) { // .targetOS is undefined unless its a linux pkgManager return; } if (!depGraph.pkgManager.repositories || !depGraph.pkgManager.repositories.length || !depGraph.pkgManager.repositories[0].alias) { throw new Error('Incomplete .pkgManager, could not create .targetOS'); } const [name, version] = depGraph.pkgManager.repositories[0].alias.split(':'); return { name, version }; } async function buildSubtree(depGraph, nodeId, maybeDeduplicationSet = false, // false = disabled; null = not in deduplication scope yet ancestors = [], memoizationMap = new Map()) { if (!maybeDeduplicationSet) { const memoizedDepTree = memiozation_1.getMemoizedDepTree(nodeId, ancestors, memoizationMap); if (memoizedDepTree) { return [memoizedDepTree, undefined]; } } const isRoot = nodeId === depGraph.rootNodeId; const nodePkg = depGraph.getNodePkg(nodeId); const nodeInfo = depGraph.getNode(nodeId); const depTree = {}; depTree.name = nodePkg.name; depTree.version = nodePkg.version; if (nodeInfo.versionProvenance) { depTree.versionProvenance = nodeInfo.versionProvenance; } if (nodeInfo.labels) { depTree.labels = Object.assign({}, nodeInfo.labels); } const depInstanceIds = depGraph.getNodeDepsNodeIds(nodeId); if (!depInstanceIds || depInstanceIds.length === 0) { memoizationMap.set(nodeId, { depTree }); return [depTree, undefined]; } const cycle = cycles_1.getCycle(ancestors, nodeId); if (cycle) { // This node starts a cycle and now it's the second visit. addLabel(depTree, 'pruned', 'cyclic'); return [depTree, [cycle]]; } if (maybeDeduplicationSet) { if (maybeDeduplicationSet.has(nodeId)) { if (depInstanceIds.length > 0) { addLabel(depTree, 'pruned', 'true'); } return [depTree, undefined]; } maybeDeduplicationSet.add(nodeId); } const cycles = []; for (const depInstId of depInstanceIds) { // Deduplication of nodes occurs only within a scope of a top-level dependency. // Therefore, every top-level dep gets an independent set to track duplicates. if (isRoot && maybeDeduplicationSet !== false) { maybeDeduplicationSet = new Set(); } const [subtree, subtreeCycles] = await buildSubtree(depGraph, depInstId, maybeDeduplicationSet, ancestors.concat(nodeId), memoizationMap); if (subtreeCycles) { for (const cycle of subtreeCycles) { cycles.push(cycle); } } if (!subtree) { continue; } if (!depTree.dependencies) { depTree.dependencies = {}; } depTree.dependencies[subtree.name] = subtree; } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } const partitionedCycles = cycles_1.partitionCycles(nodeId, cycles); memiozation_1.memoize(nodeId, memoizationMap, depTree, partitionedCycles); return [depTree, partitionedCycles.cyclesWithThisNode]; } function trimAfterLastSep(str, sep) { return str.slice(0, str.lastIndexOf(sep)); } //# sourceMappingURL=index.js.map /***/ }), /***/ 3143: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getMemoizedDepTree = exports.memoize = void 0; function memoize(nodeId, memoizationMap, depTree, partitionedCycles) { const { cyclesStartWithThisNode, cyclesWithThisNode } = partitionedCycles; if (cyclesStartWithThisNode.length > 0) { const cycleNodeIds = new Set(...cyclesStartWithThisNode); memoizationMap.set(nodeId, { depTree, cycleNodeIds }); } else if (cyclesWithThisNode.length === 0) { memoizationMap.set(nodeId, { depTree }); } // Don't memoize nodes in cycles (cyclesWithThisNode.length > 0) } exports.memoize = memoize; function getMemoizedDepTree(nodeId, ancestors, memoizationMap) { if (!memoizationMap.has(nodeId)) return null; const { depTree, cycleNodeIds } = memoizationMap.get(nodeId); if (!cycleNodeIds) return depTree; const ancestorsArePartOfTheCycle = ancestors.some((nodeId) => cycleNodeIds.has(nodeId)); return ancestorsArePartOfTheCycle ? null : depTree; } exports.getMemoizedDepTree = getMemoizedDepTree; //# sourceMappingURL=memiozation.js.map /***/ }), /***/ 34030: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // A linked list to keep track of recently-used-ness const Yallist = __webpack_require__(79534) const MAX = Symbol('max') const LENGTH = Symbol('length') const LENGTH_CALCULATOR = Symbol('lengthCalculator') const ALLOW_STALE = Symbol('allowStale') const MAX_AGE = Symbol('maxAge') const DISPOSE = Symbol('dispose') const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') const LRU_LIST = Symbol('lruList') const CACHE = Symbol('cache') const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') const naiveLength = () => 1 // lruList is a yallist where the head is the youngest // item, and the tail is the oldest. the list contains the Hit // objects as the entries. // Each Hit object has a reference to its Yallist.Node. This // never changes. // // cache is a Map (or PseudoMap) that matches the keys to // the Yallist.Node object. class LRUCache { constructor (options) { if (typeof options === 'number') options = { max: options } if (!options) options = {} if (options.max && (typeof options.max !== 'number' || options.max < 0)) throw new TypeError('max must be a non-negative number') // Kind of weird to have a default max of Infinity, but oh well. const max = this[MAX] = options.max || Infinity const lc = options.length || naiveLength this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc this[ALLOW_STALE] = options.stale || false if (options.maxAge && typeof options.maxAge !== 'number') throw new TypeError('maxAge must be a number') this[MAX_AGE] = options.maxAge || 0 this[DISPOSE] = options.dispose this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false this.reset() } // resize the cache when the max changes. set max (mL) { if (typeof mL !== 'number' || mL < 0) throw new TypeError('max must be a non-negative number') this[MAX] = mL || Infinity trim(this) } get max () { return this[MAX] } set allowStale (allowStale) { this[ALLOW_STALE] = !!allowStale } get allowStale () { return this[ALLOW_STALE] } set maxAge (mA) { if (typeof mA !== 'number') throw new TypeError('maxAge must be a non-negative number') this[MAX_AGE] = mA trim(this) } get maxAge () { return this[MAX_AGE] } // resize the cache when the lengthCalculator changes. set lengthCalculator (lC) { if (typeof lC !== 'function') lC = naiveLength if (lC !== this[LENGTH_CALCULATOR]) { this[LENGTH_CALCULATOR] = lC this[LENGTH] = 0 this[LRU_LIST].forEach(hit => { hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) this[LENGTH] += hit.length }) } trim(this) } get lengthCalculator () { return this[LENGTH_CALCULATOR] } get length () { return this[LENGTH] } get itemCount () { return this[LRU_LIST].length } rforEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].tail; walker !== null;) { const prev = walker.prev forEachStep(this, fn, walker, thisp) walker = prev } } forEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].head; walker !== null;) { const next = walker.next forEachStep(this, fn, walker, thisp) walker = next } } keys () { return this[LRU_LIST].toArray().map(k => k.key) } values () { return this[LRU_LIST].toArray().map(k => k.value) } reset () { if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) { this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) } this[CACHE] = new Map() // hash of items by key this[LRU_LIST] = new Yallist() // list of items in order of use recency this[LENGTH] = 0 // length of items in the list } dump () { return this[LRU_LIST].map(hit => isStale(this, hit) ? false : { k: hit.key, v: hit.value, e: hit.now + (hit.maxAge || 0) }).toArray().filter(h => h) } dumpLru () { return this[LRU_LIST] } set (key, value, maxAge) { maxAge = maxAge || this[MAX_AGE] if (maxAge && typeof maxAge !== 'number') throw new TypeError('maxAge must be a number') const now = maxAge ? Date.now() : 0 const len = this[LENGTH_CALCULATOR](value, key) if (this[CACHE].has(key)) { if (len > this[MAX]) { del(this, this[CACHE].get(key)) return false } const node = this[CACHE].get(key) const item = node.value // dispose of the old one before overwriting // split out into 2 ifs for better coverage tracking if (this[DISPOSE]) { if (!this[NO_DISPOSE_ON_SET]) this[DISPOSE](key, item.value) } item.now = now item.maxAge = maxAge item.value = value this[LENGTH] += len - item.length item.length = len this.get(key) trim(this) return true } const hit = new Entry(key, value, len, now, maxAge) // oversized objects fall out of cache automatically. if (hit.length > this[MAX]) { if (this[DISPOSE]) this[DISPOSE](key, value) return false } this[LENGTH] += hit.length this[LRU_LIST].unshift(hit) this[CACHE].set(key, this[LRU_LIST].head) trim(this) return true } has (key) { if (!this[CACHE].has(key)) return false const hit = this[CACHE].get(key).value return !isStale(this, hit) } get (key) { return get(this, key, true) } peek (key) { return get(this, key, false) } pop () { const node = this[LRU_LIST].tail if (!node) return null del(this, node) return node.value } del (key) { del(this, this[CACHE].get(key)) } load (arr) { // reset the cache this.reset() const now = Date.now() // A previous serialized cache has the most recent items first for (let l = arr.length - 1; l >= 0; l--) { const hit = arr[l] const expiresAt = hit.e || 0 if (expiresAt === 0) // the item was created without expiration in a non aged cache this.set(hit.k, hit.v) else { const maxAge = expiresAt - now // dont add already expired items if (maxAge > 0) { this.set(hit.k, hit.v, maxAge) } } } } prune () { this[CACHE].forEach((value, key) => get(this, key, false)) } } const get = (self, key, doUse) => { const node = self[CACHE].get(key) if (node) { const hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) return undefined } else { if (doUse) { if (self[UPDATE_AGE_ON_GET]) node.value.now = Date.now() self[LRU_LIST].unshiftNode(node) } } return hit.value } } const isStale = (self, hit) => { if (!hit || (!hit.maxAge && !self[MAX_AGE])) return false const diff = Date.now() - hit.now return hit.maxAge ? diff > hit.maxAge : self[MAX_AGE] && (diff > self[MAX_AGE]) } const trim = self => { if (self[LENGTH] > self[MAX]) { for (let walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) { // We know that we're about to delete this one, and also // what the next least recently used key will be, so just // go ahead and set it now. const prev = walker.prev del(self, walker) walker = prev } } } const del = (self, node) => { if (node) { const hit = node.value if (self[DISPOSE]) self[DISPOSE](hit.key, hit.value) self[LENGTH] -= hit.length self[CACHE].delete(hit.key) self[LRU_LIST].removeNode(node) } } class Entry { constructor (key, value, length, now, maxAge) { this.key = key this.value = value this.length = length this.now = now this.maxAge = maxAge || 0 } } const forEachStep = (self, fn, node, thisp) => { let hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) hit = undefined } if (hit) fn.call(thisp, hit.value, hit.key, self) } module.exports = LRUCache /***/ }), /***/ 70394: /***/ ((module, exports, __webpack_require__) => { "use strict"; var crypto = __webpack_require__(6113); /** * Exported function * * Options: * * - `algorithm` hash algo to be used by this instance: *'sha1', 'md5' * - `excludeValues` {true|*false} hash object keys, values ignored * - `encoding` hash encoding, supports 'buffer', '*hex', 'binary', 'base64' * - `ignoreUnknown` {true|*false} ignore unknown object types * - `replacer` optional function that replaces values before hashing * - `respectFunctionProperties` {*true|false} consider function properties when hashing * - `respectFunctionNames` {*true|false} consider 'name' property of functions for hashing * - `respectType` {*true|false} Respect special properties (prototype, constructor) * when hashing to distinguish between types * - `unorderedArrays` {true|*false} Sort all arrays before hashing * - `unorderedSets` {*true|false} Sort `Set` and `Map` instances before hashing * * = default * * @param {object} object value to hash * @param {object} options hashing options * @return {string} hash value * @api public */ exports = module.exports = objectHash; function objectHash(object, options){ options = applyDefaults(object, options); return hash(object, options); } /** * Exported sugar methods * * @param {object} object value to hash * @return {string} hash value * @api public */ exports.sha1 = function(object){ return objectHash(object); }; exports.keys = function(object){ return objectHash(object, {excludeValues: true, algorithm: 'sha1', encoding: 'hex'}); }; exports.MD5 = function(object){ return objectHash(object, {algorithm: 'md5', encoding: 'hex'}); }; exports.keysMD5 = function(object){ return objectHash(object, {algorithm: 'md5', encoding: 'hex', excludeValues: true}); }; // Internals var hashes = crypto.getHashes ? crypto.getHashes().slice() : ['sha1', 'md5']; hashes.push('passthrough'); var encodings = ['buffer', 'hex', 'binary', 'base64']; function applyDefaults(object, sourceOptions){ sourceOptions = sourceOptions || {}; // create a copy rather than mutating var options = {}; options.algorithm = sourceOptions.algorithm || 'sha1'; options.encoding = sourceOptions.encoding || 'hex'; options.excludeValues = sourceOptions.excludeValues ? true : false; options.algorithm = options.algorithm.toLowerCase(); options.encoding = options.encoding.toLowerCase(); options.ignoreUnknown = sourceOptions.ignoreUnknown !== true ? false : true; // default to false options.respectType = sourceOptions.respectType === false ? false : true; // default to true options.respectFunctionNames = sourceOptions.respectFunctionNames === false ? false : true; options.respectFunctionProperties = sourceOptions.respectFunctionProperties === false ? false : true; options.unorderedArrays = sourceOptions.unorderedArrays !== true ? false : true; // default to false options.unorderedSets = sourceOptions.unorderedSets === false ? false : true; // default to false options.unorderedObjects = sourceOptions.unorderedObjects === false ? false : true; // default to true options.replacer = sourceOptions.replacer || undefined; options.excludeKeys = sourceOptions.excludeKeys || undefined; if(typeof object === 'undefined') { throw new Error('Object argument required.'); } // if there is a case-insensitive match in the hashes list, accept it // (i.e. SHA256 for sha256) for (var i = 0; i < hashes.length; ++i) { if (hashes[i].toLowerCase() === options.algorithm.toLowerCase()) { options.algorithm = hashes[i]; } } if(hashes.indexOf(options.algorithm) === -1){ throw new Error('Algorithm "' + options.algorithm + '" not supported. ' + 'supported values: ' + hashes.join(', ')); } if(encodings.indexOf(options.encoding) === -1 && options.algorithm !== 'passthrough'){ throw new Error('Encoding "' + options.encoding + '" not supported. ' + 'supported values: ' + encodings.join(', ')); } return options; } /** Check if the given function is a native function */ function isNativeFunction(f) { if ((typeof f) !== 'function') { return false; } var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i; return exp.exec(Function.prototype.toString.call(f)) != null; } function hash(object, options) { var hashingStream; if (options.algorithm !== 'passthrough') { hashingStream = crypto.createHash(options.algorithm); } else { hashingStream = new PassThrough(); } if (typeof hashingStream.write === 'undefined') { hashingStream.write = hashingStream.update; hashingStream.end = hashingStream.update; } var hasher = typeHasher(options, hashingStream); hasher.dispatch(object); if (!hashingStream.update) { hashingStream.end(''); } if (hashingStream.digest) { return hashingStream.digest(options.encoding === 'buffer' ? undefined : options.encoding); } var buf = hashingStream.read(); if (options.encoding === 'buffer') { return buf; } return buf.toString(options.encoding); } /** * Expose streaming API * * @param {object} object Value to serialize * @param {object} options Options, as for hash() * @param {object} stream A stream to write the serializiation to * @api public */ exports.writeToStream = function(object, options, stream) { if (typeof stream === 'undefined') { stream = options; options = {}; } options = applyDefaults(object, options); return typeHasher(options, stream).dispatch(object); }; function typeHasher(options, writeTo, context){ context = context || []; var write = function(str) { if (writeTo.update) { return writeTo.update(str, 'utf8'); } else { return writeTo.write(str, 'utf8'); } }; return { dispatch: function(value){ if (options.replacer) { value = options.replacer(value); } var type = typeof value; if (value === null) { type = 'null'; } //console.log("[DEBUG] Dispatch: ", value, "->", type, " -> ", "_" + type); return this['_' + type](value); }, _object: function(object) { var pattern = (/\[object (.*)\]/i); var objString = Object.prototype.toString.call(object); var objType = pattern.exec(objString); if (!objType) { // object type did not match [object ...] objType = 'unknown:[' + objString + ']'; } else { objType = objType[1]; // take only the class name } objType = objType.toLowerCase(); var objectNumber = null; if ((objectNumber = context.indexOf(object)) >= 0) { return this.dispatch('[CIRCULAR:' + objectNumber + ']'); } else { context.push(object); } if (typeof Buffer !== 'undefined' && Buffer.isBuffer && Buffer.isBuffer(object)) { write('buffer:'); return write(object); } if(objType !== 'object' && objType !== 'function' && objType !== 'asyncfunction') { if(this['_' + objType]) { this['_' + objType](object); } else if (options.ignoreUnknown) { return write('[' + objType + ']'); } else { throw new Error('Unknown object type "' + objType + '"'); } }else{ var keys = Object.keys(object); if (options.unorderedObjects) { keys = keys.sort(); } // Make sure to incorporate special properties, so // Types with different prototypes will produce // a different hash and objects derived from // different functions (`new Foo`, `new Bar`) will // produce different hashes. // We never do this for native functions since some // seem to break because of that. if (options.respectType !== false && !isNativeFunction(object)) { keys.splice(0, 0, 'prototype', '__proto__', 'constructor'); } if (options.excludeKeys) { keys = keys.filter(function(key) { return !options.excludeKeys(key); }); } write('object:' + keys.length + ':'); var self = this; return keys.forEach(function(key){ self.dispatch(key); write(':'); if(!options.excludeValues) { self.dispatch(object[key]); } write(','); }); } }, _array: function(arr, unordered){ unordered = typeof unordered !== 'undefined' ? unordered : options.unorderedArrays !== false; // default to options.unorderedArrays var self = this; write('array:' + arr.length + ':'); if (!unordered || arr.length <= 1) { return arr.forEach(function(entry) { return self.dispatch(entry); }); } // the unordered case is a little more complicated: // since there is no canonical ordering on objects, // i.e. {a:1} < {a:2} and {a:1} > {a:2} are both false, // we first serialize each entry using a PassThrough stream // before sorting. // also: we can’t use the same context array for all entries // since the order of hashing should *not* matter. instead, // we keep track of the additions to a copy of the context array // and add all of them to the global context array when we’re done var contextAdditions = []; var entries = arr.map(function(entry) { var strm = new PassThrough(); var localContext = context.slice(); // make copy var hasher = typeHasher(options, strm, localContext); hasher.dispatch(entry); // take only what was added to localContext and append it to contextAdditions contextAdditions = contextAdditions.concat(localContext.slice(context.length)); return strm.read().toString(); }); context = context.concat(contextAdditions); entries.sort(); return this._array(entries, false); }, _date: function(date){ return write('date:' + date.toJSON()); }, _symbol: function(sym){ return write('symbol:' + sym.toString()); }, _error: function(err){ return write('error:' + err.toString()); }, _boolean: function(bool){ return write('bool:' + bool.toString()); }, _string: function(string){ write('string:' + string.length + ':'); write(string.toString()); }, _function: function(fn){ write('fn:'); if (isNativeFunction(fn)) { this.dispatch('[native]'); } else { this.dispatch(fn.toString()); } if (options.respectFunctionNames !== false) { // Make sure we can still distinguish native functions // by their name, otherwise String and Function will // have the same hash this.dispatch("function-name:" + String(fn.name)); } if (options.respectFunctionProperties) { this._object(fn); } }, _number: function(number){ return write('number:' + number.toString()); }, _xml: function(xml){ return write('xml:' + xml.toString()); }, _null: function() { return write('Null'); }, _undefined: function() { return write('Undefined'); }, _regexp: function(regex){ return write('regex:' + regex.toString()); }, _uint8array: function(arr){ write('uint8array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _uint8clampedarray: function(arr){ write('uint8clampedarray:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _int8array: function(arr){ write('uint8array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _uint16array: function(arr){ write('uint16array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _int16array: function(arr){ write('uint16array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _uint32array: function(arr){ write('uint32array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _int32array: function(arr){ write('uint32array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _float32array: function(arr){ write('float32array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _float64array: function(arr){ write('float64array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _arraybuffer: function(arr){ write('arraybuffer:'); return this.dispatch(new Uint8Array(arr)); }, _url: function(url) { return write('url:' + url.toString(), 'utf8'); }, _map: function(map) { write('map:'); var arr = Array.from(map); return this._array(arr, options.unorderedSets !== false); }, _set: function(set) { write('set:'); var arr = Array.from(set); return this._array(arr, options.unorderedSets !== false); }, _file: function(file) { write('file:'); return this.dispatch([file.name, file.size, file.type, file.lastModfied]); }, _blob: function() { if (options.ignoreUnknown) { return write('[blob]'); } throw Error('Hashing Blob objects is currently not supported\n' + '(see https://github.com/puleos/object-hash/issues/26)\n' + 'Use "options.replacer" or "options.ignoreUnknown"\n'); }, _domwindow: function() { return write('domwindow'); }, _bigint: function(number){ return write('bigint:' + number.toString()); }, /* Node.js standard native objects */ _process: function() { return write('process'); }, _timer: function() { return write('timer'); }, _pipe: function() { return write('pipe'); }, _tcp: function() { return write('tcp'); }, _udp: function() { return write('udp'); }, _tty: function() { return write('tty'); }, _statwatcher: function() { return write('statwatcher'); }, _securecontext: function() { return write('securecontext'); }, _connection: function() { return write('connection'); }, _zlib: function() { return write('zlib'); }, _context: function() { return write('context'); }, _nodescript: function() { return write('nodescript'); }, _httpparser: function() { return write('httpparser'); }, _dataview: function() { return write('dataview'); }, _signal: function() { return write('signal'); }, _fsevent: function() { return write('fsevent'); }, _tlswrap: function() { return write('tlswrap'); }, }; } // Mini-implementation of stream.PassThrough // We are far from having need for the full implementation, and we can // make assumptions like "many writes, then only one final read" // and we can ignore encoding specifics function PassThrough() { return { buf: '', write: function(b) { this.buf += b; }, end: function(b) { this.buf += b; }, read: function() { return this.buf; } }; } /***/ }), /***/ 80977: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const ANY = Symbol('SemVer ANY') // hoisted class for cyclic dependency class Comparator { static get ANY () { return ANY } constructor (comp, options) { options = parseOptions(options) if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } comp = comp.trim().split(/\s+/).join(' ') debug('comparator', comp, options) this.options = options this.loose = !!options.loose this.parse(comp) if (this.semver === ANY) { this.value = '' } else { this.value = this.operator + this.semver.version } debug('comp', this) } parse (comp) { const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] const m = comp.match(r) if (!m) { throw new TypeError(`Invalid comparator: ${comp}`) } this.operator = m[1] !== undefined ? m[1] : '' if (this.operator === '=') { this.operator = '' } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY } else { this.semver = new SemVer(m[2], this.options.loose) } } toString () { return this.value } test (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY || version === ANY) { return true } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } return cmp(version, this.operator, this.semver, this.options) } intersects (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (this.operator === '') { if (this.value === '') { return true } return new Range(comp.value, options).test(this.value) } else if (comp.operator === '') { if (comp.value === '') { return true } return new Range(this.value, options).test(comp.semver) } options = parseOptions(options) // Special cases where nothing can possibly be lower if (options.includePrerelease && (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { return false } if (!options.includePrerelease && (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { return false } // Same direction increasing (> or >=) if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { return true } // Same direction decreasing (< or <=) if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { return true } // same SemVer and both sides are inclusive (<= or >=) if ( (this.semver.version === comp.semver.version) && this.operator.includes('=') && comp.operator.includes('=')) { return true } // opposite directions less than if (cmp(this.semver, '<', comp.semver, options) && this.operator.startsWith('>') && comp.operator.startsWith('<')) { return true } // opposite directions greater than if (cmp(this.semver, '>', comp.semver, options) && this.operator.startsWith('<') && comp.operator.startsWith('>')) { return true } return false } } module.exports = Comparator const parseOptions = __webpack_require__(99936) const { safeRe: re, t } = __webpack_require__(20149) const cmp = __webpack_require__(71430) const debug = __webpack_require__(39433) const SemVer = __webpack_require__(21963) const Range = __webpack_require__(43929) /***/ }), /***/ 43929: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // hoisted class for cyclic dependency class Range { constructor (range, options) { options = parseOptions(options) if (range instanceof Range) { if ( range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease ) { return range } else { return new Range(range.raw, options) } } if (range instanceof Comparator) { // just put it in the set and return this.raw = range.value this.set = [[range]] this.format() return this } this.options = options this.loose = !!options.loose this.includePrerelease = !!options.includePrerelease // First reduce all whitespace as much as possible so we do not have to rely // on potentially slow regexes like \s*. This is then stored and used for // future error messages as well. this.raw = range .trim() .split(/\s+/) .join(' ') // First, split on || this.set = this.raw .split('||') // map the range to a 2d array of comparators .map(r => this.parseRange(r.trim())) // throw out any comparator lists that are empty // this generally means that it was not a valid range, which is allowed // in loose mode, but will still throw if the WHOLE range is invalid. .filter(c => c.length) if (!this.set.length) { throw new TypeError(`Invalid SemVer Range: ${this.raw}`) } // if we have any that are not the null set, throw out null sets. if (this.set.length > 1) { // keep the first one, in case they're all null sets const first = this.set[0] this.set = this.set.filter(c => !isNullSet(c[0])) if (this.set.length === 0) { this.set = [first] } else if (this.set.length > 1) { // if we have any that are *, then the range is just * for (const c of this.set) { if (c.length === 1 && isAny(c[0])) { this.set = [c] break } } } } this.format() } format () { this.range = this.set .map((comps) => comps.join(' ').trim()) .join('||') .trim() return this.range } toString () { return this.range } parseRange (range) { // memoize range parsing for performance. // this is a very hot path, and fully deterministic. const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE) const memoKey = memoOpts + ':' + range const cached = cache.get(memoKey) if (cached) { return cached } const loose = this.options.loose // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range) // `~ 1.2.3` => `~1.2.3` range = range.replace(re[t.TILDETRIM], tildeTrimReplace) debug('tilde trim', range) // `^ 1.2.3` => `^1.2.3` range = range.replace(re[t.CARETTRIM], caretTrimReplace) debug('caret trim', range) // At this point, the range is completely trimmed and // ready to be split into comparators. let rangeList = range .split(' ') .map(comp => parseComparator(comp, this.options)) .join(' ') .split(/\s+/) // >=0.0.0 is equivalent to * .map(comp => replaceGTE0(comp, this.options)) if (loose) { // in loose mode, throw out any that are not valid comparators rangeList = rangeList.filter(comp => { debug('loose invalid filter', comp, this.options) return !!comp.match(re[t.COMPARATORLOOSE]) }) } debug('range list', rangeList) // if any comparators are the null set, then replace with JUST null set // if more than one comparator, remove any * comparators // also, don't include the same comparator more than once const rangeMap = new Map() const comparators = rangeList.map(comp => new Comparator(comp, this.options)) for (const comp of comparators) { if (isNullSet(comp)) { return [comp] } rangeMap.set(comp.value, comp) } if (rangeMap.size > 1 && rangeMap.has('')) { rangeMap.delete('') } const result = [...rangeMap.values()] cache.set(memoKey, result) return result } intersects (range, options) { if (!(range instanceof Range)) { throw new TypeError('a Range is required') } return this.set.some((thisComparators) => { return ( isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => { return ( isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { return rangeComparators.every((rangeComparator) => { return thisComparator.intersects(rangeComparator, options) }) }) ) }) ) }) } // if ANY of the sets match ALL of its comparators, then pass test (version) { if (!version) { return false } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } for (let i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true } } return false } } module.exports = Range const LRU = __webpack_require__(34030) const cache = new LRU({ max: 1000 }) const parseOptions = __webpack_require__(99936) const Comparator = __webpack_require__(80977) const debug = __webpack_require__(39433) const SemVer = __webpack_require__(21963) const { safeRe: re, t, comparatorTrimReplace, tildeTrimReplace, caretTrimReplace, } = __webpack_require__(20149) const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __webpack_require__(20184) const isNullSet = c => c.value === '<0.0.0-0' const isAny = c => c.value === '' // take a set of comparators and determine whether there // exists a version which can satisfy it const isSatisfiable = (comparators, options) => { let result = true const remainingComparators = comparators.slice() let testComparator = remainingComparators.pop() while (result && remainingComparators.length) { result = remainingComparators.every((otherComparator) => { return testComparator.intersects(otherComparator, options) }) testComparator = remainingComparators.pop() } return result } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. const parseComparator = (comp, options) => { debug('comp', comp, options) comp = replaceCarets(comp, options) debug('caret', comp) comp = replaceTildes(comp, options) debug('tildes', comp) comp = replaceXRanges(comp, options) debug('xrange', comp) comp = replaceStars(comp, options) debug('stars', comp) return comp } const isX = id => !id || id.toLowerCase() === 'x' || id === '*' // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 // ~0.0.1 --> >=0.0.1 <0.1.0-0 const replaceTildes = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceTilde(c, options)) .join(' ') } const replaceTilde = (comp, options) => { const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] return comp.replace(r, (_, M, m, p, pr) => { debug('tilde', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0 <${+M + 1}.0.0-0` } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0-0 ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` } else if (pr) { debug('replaceTilde pr', pr) ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } else { // ~1.2.3 == >=1.2.3 <1.3.0-0 ret = `>=${M}.${m}.${p } <${M}.${+m + 1}.0-0` } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 // ^1.2.3 --> >=1.2.3 <2.0.0-0 // ^1.2.0 --> >=1.2.0 <2.0.0-0 // ^0.0.1 --> >=0.0.1 <0.0.2-0 // ^0.1.0 --> >=0.1.0 <0.2.0-0 const replaceCarets = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceCaret(c, options)) .join(' ') } const replaceCaret = (comp, options) => { debug('caret', comp, options) const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] const z = options.includePrerelease ? '-0' : '' return comp.replace(r, (_, M, m, p, pr) => { debug('caret', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` } else if (isX(p)) { if (M === '0') { ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` } else { ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p}-${pr } <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p}-${pr } <${+M + 1}.0.0-0` } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p }${z} <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p }${z} <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p } <${+M + 1}.0.0-0` } } debug('caret return', ret) return ret }) } const replaceXRanges = (comp, options) => { debug('replaceXRanges', comp, options) return comp .split(/\s+/) .map((c) => replaceXRange(c, options)) .join(' ') } const replaceXRange = (comp, options) => { comp = comp.trim() const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] return comp.replace(r, (ret, gtlt, M, m, p, pr) => { debug('xRange', comp, ret, gtlt, M, m, p, pr) const xM = isX(M) const xm = xM || isX(m) const xp = xm || isX(p) const anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } // if we're including prereleases in the match, then we need // to fix this to -0, the lowest possible prerelease value pr = options.includePrerelease ? '-0' : '' if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0-0' } else { // nothing is forbidden ret = '*' } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0 } p = 0 if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 gtlt = '>=' if (xm) { M = +M + 1 m = 0 p = 0 } else { m = +m + 1 p = 0 } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<' if (xm) { M = +M + 1 } else { m = +m + 1 } } if (gtlt === '<') { pr = '-0' } ret = `${gtlt + M}.${m}.${p}${pr}` } else if (xm) { ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` } else if (xp) { ret = `>=${M}.${m}.0${pr } <${M}.${+m + 1}.0-0` } debug('xRange return', ret) return ret }) } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. const replaceStars = (comp, options) => { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp .trim() .replace(re[t.STAR], '') } const replaceGTE0 = (comp, options) => { debug('replaceGTE0', comp, options) return comp .trim() .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') } // This function is passed to string.replace(re[t.HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 const hyphenReplace = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) => { if (isX(fM)) { from = '' } else if (isX(fm)) { from = `>=${fM}.0.0${incPr ? '-0' : ''}` } else if (isX(fp)) { from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` } else if (fpr) { from = `>=${from}` } else { from = `>=${from}${incPr ? '-0' : ''}` } if (isX(tM)) { to = '' } else if (isX(tm)) { to = `<${+tM + 1}.0.0-0` } else if (isX(tp)) { to = `<${tM}.${+tm + 1}.0-0` } else if (tpr) { to = `<=${tM}.${tm}.${tp}-${tpr}` } else if (incPr) { to = `<${tM}.${tm}.${+tp + 1}-0` } else { to = `<=${to}` } return `${from} ${to}`.trim() } const testSet = (set, version, options) => { for (let i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (let i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === Comparator.ANY) { continue } if (set[i].semver.prerelease.length > 0) { const allowed = set[i].semver if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } /***/ }), /***/ 21963: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const debug = __webpack_require__(39433) const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(20184) const { safeRe: re, t } = __webpack_require__(20149) const parseOptions = __webpack_require__(99936) const { compareIdentifiers } = __webpack_require__(49210) class SemVer { constructor (version, options) { options = parseOptions(options) if (version instanceof SemVer) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) } if (version.length > MAX_LENGTH) { throw new TypeError( `version is longer than ${MAX_LENGTH} characters` ) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose // this isn't actually relevant for versions, but keep it so that we // don't run into trouble passing this.options around. this.includePrerelease = !!options.includePrerelease const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) if (!m) { throw new TypeError(`Invalid Version: ${version}`) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map((id) => { if (/^[0-9]+$/.test(id)) { const num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } format () { this.version = `${this.major}.${this.minor}.${this.patch}` if (this.prerelease.length) { this.version += `-${this.prerelease.join('.')}` } return this.version } toString () { return this.version } compare (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { if (typeof other === 'string' && other === this.version) { return 0 } other = new SemVer(other, this.options) } if (other.version === this.version) { return 0 } return this.compareMain(other) || this.comparePre(other) } compareMain (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return ( compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) ) } comparePre (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } let i = 0 do { const a = this.prerelease[i] const b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } compareBuild (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } let i = 0 do { const a = this.build[i] const b = other.build[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc (release, identifier, identifierBase) { switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier, identifierBase) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier, identifierBase) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier, identifierBase) this.inc('pre', identifier, identifierBase) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier, identifierBase) } this.inc('pre', identifier, identifierBase) break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if ( this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0 ) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. case 'pre': { const base = Number(identifierBase) ? 1 : 0 if (!identifier && identifierBase === false) { throw new Error('invalid increment argument: identifier is empty') } if (this.prerelease.length === 0) { this.prerelease = [base] } else { let i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything if (identifier === this.prerelease.join('.') && identifierBase === false) { throw new Error('invalid increment argument: identifier already exists') } this.prerelease.push(base) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 let prerelease = [identifier, base] if (identifierBase === false) { prerelease = [identifier] } if (compareIdentifiers(this.prerelease[0], identifier) === 0) { if (isNaN(this.prerelease[1])) { this.prerelease = prerelease } } else { this.prerelease = prerelease } } break } default: throw new Error(`invalid increment argument: ${release}`) } this.raw = this.format() if (this.build.length) { this.raw += `+${this.build.join('.')}` } return this } } module.exports = SemVer /***/ }), /***/ 18734: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(52993) const clean = (version, options) => { const s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } module.exports = clean /***/ }), /***/ 71430: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const eq = __webpack_require__(19271) const neq = __webpack_require__(46267) const gt = __webpack_require__(25591) const gte = __webpack_require__(35740) const lt = __webpack_require__(7315) const lte = __webpack_require__(33017) const cmp = (a, op, b, loose) => { switch (op) { case '===': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a === b case '!==': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError(`Invalid operator: ${op}`) } } module.exports = cmp /***/ }), /***/ 9610: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(21963) const parse = __webpack_require__(52993) const { safeRe: re, t } = __webpack_require__(20149) const coerce = (version, options) => { if (version instanceof SemVer) { return version } if (typeof version === 'number') { version = String(version) } if (typeof version !== 'string') { return null } options = options || {} let match = null if (!options.rtl) { match = version.match(re[t.COERCE]) } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' // // Walk through the string checking with a /g regexp // Manually set the index so as to pick up overlapping matches. // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. let next while ((next = re[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next } re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length } // leave it in a clean state re[t.COERCERTL].lastIndex = -1 } if (match === null) { return null } return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) } module.exports = coerce /***/ }), /***/ 32866: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(21963) const compareBuild = (a, b, loose) => { const versionA = new SemVer(a, loose) const versionB = new SemVer(b, loose) return versionA.compare(versionB) || versionA.compareBuild(versionB) } module.exports = compareBuild /***/ }), /***/ 76288: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(82762) const compareLoose = (a, b) => compare(a, b, true) module.exports = compareLoose /***/ }), /***/ 82762: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(21963) const compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)) module.exports = compare /***/ }), /***/ 76649: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(52993) const diff = (version1, version2) => { const v1 = parse(version1, null, true) const v2 = parse(version2, null, true) const comparison = v1.compare(v2) if (comparison === 0) { return null } const v1Higher = comparison > 0 const highVersion = v1Higher ? v1 : v2 const lowVersion = v1Higher ? v2 : v1 const highHasPre = !!highVersion.prerelease.length const lowHasPre = !!lowVersion.prerelease.length if (lowHasPre && !highHasPre) { // Going from prerelease -> no prerelease requires some special casing // If the low version has only a major, then it will always be a major // Some examples: // 1.0.0-1 -> 1.0.0 // 1.0.0-1 -> 1.1.1 // 1.0.0-1 -> 2.0.0 if (!lowVersion.patch && !lowVersion.minor) { return 'major' } // Otherwise it can be determined by checking the high version if (highVersion.patch) { // anything higher than a patch bump would result in the wrong version return 'patch' } if (highVersion.minor) { // anything higher than a minor bump would result in the wrong version return 'minor' } // bumping major/minor/patch all have same result return 'major' } // add the `pre` prefix if we are going to a prerelease version const prefix = highHasPre ? 'pre' : '' if (v1.major !== v2.major) { return prefix + 'major' } if (v1.minor !== v2.minor) { return prefix + 'minor' } if (v1.patch !== v2.patch) { return prefix + 'patch' } // high and low are preleases return 'prerelease' } module.exports = diff /***/ }), /***/ 19271: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(82762) const eq = (a, b, loose) => compare(a, b, loose) === 0 module.exports = eq /***/ }), /***/ 25591: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(82762) const gt = (a, b, loose) => compare(a, b, loose) > 0 module.exports = gt /***/ }), /***/ 35740: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(82762) const gte = (a, b, loose) => compare(a, b, loose) >= 0 module.exports = gte /***/ }), /***/ 45268: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(21963) const inc = (version, release, options, identifier, identifierBase) => { if (typeof (options) === 'string') { identifierBase = identifier identifier = options options = undefined } try { return new SemVer( version instanceof SemVer ? version.version : version, options ).inc(release, identifier, identifierBase).version } catch (er) { return null } } module.exports = inc /***/ }), /***/ 7315: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(82762) const lt = (a, b, loose) => compare(a, b, loose) < 0 module.exports = lt /***/ }), /***/ 33017: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(82762) const lte = (a, b, loose) => compare(a, b, loose) <= 0 module.exports = lte /***/ }), /***/ 70241: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(21963) const major = (a, loose) => new SemVer(a, loose).major module.exports = major /***/ }), /***/ 80291: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(21963) const minor = (a, loose) => new SemVer(a, loose).minor module.exports = minor /***/ }), /***/ 46267: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(82762) const neq = (a, b, loose) => compare(a, b, loose) !== 0 module.exports = neq /***/ }), /***/ 52993: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(21963) const parse = (version, options, throwErrors = false) => { if (version instanceof SemVer) { return version } try { return new SemVer(version, options) } catch (er) { if (!throwErrors) { return null } throw er } } module.exports = parse /***/ }), /***/ 58428: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(21963) const patch = (a, loose) => new SemVer(a, loose).patch module.exports = patch /***/ }), /***/ 10139: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(52993) const prerelease = (version, options) => { const parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } module.exports = prerelease /***/ }), /***/ 28856: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(82762) const rcompare = (a, b, loose) => compare(b, a, loose) module.exports = rcompare /***/ }), /***/ 98811: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(32866) const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) module.exports = rsort /***/ }), /***/ 48529: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(43929) const satisfies = (version, range, options) => { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } module.exports = satisfies /***/ }), /***/ 48679: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(32866) const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) module.exports = sort /***/ }), /***/ 7828: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(52993) const valid = (version, options) => { const v = parse(version, options) return v ? v.version : null } module.exports = valid /***/ }), /***/ 78502: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // just pre-load all the stuff that index.js lazily exports const internalRe = __webpack_require__(20149) const constants = __webpack_require__(20184) const SemVer = __webpack_require__(21963) const identifiers = __webpack_require__(49210) const parse = __webpack_require__(52993) const valid = __webpack_require__(7828) const clean = __webpack_require__(18734) const inc = __webpack_require__(45268) const diff = __webpack_require__(76649) const major = __webpack_require__(70241) const minor = __webpack_require__(80291) const patch = __webpack_require__(58428) const prerelease = __webpack_require__(10139) const compare = __webpack_require__(82762) const rcompare = __webpack_require__(28856) const compareLoose = __webpack_require__(76288) const compareBuild = __webpack_require__(32866) const sort = __webpack_require__(48679) const rsort = __webpack_require__(98811) const gt = __webpack_require__(25591) const lt = __webpack_require__(7315) const eq = __webpack_require__(19271) const neq = __webpack_require__(46267) const gte = __webpack_require__(35740) const lte = __webpack_require__(33017) const cmp = __webpack_require__(71430) const coerce = __webpack_require__(9610) const Comparator = __webpack_require__(80977) const Range = __webpack_require__(43929) const satisfies = __webpack_require__(48529) const toComparators = __webpack_require__(72371) const maxSatisfying = __webpack_require__(90088) const minSatisfying = __webpack_require__(82283) const minVersion = __webpack_require__(20582) const validRange = __webpack_require__(89031) const outside = __webpack_require__(97833) const gtr = __webpack_require__(69028) const ltr = __webpack_require__(41146) const intersects = __webpack_require__(53407) const simplifyRange = __webpack_require__(7933) const subset = __webpack_require__(59874) module.exports = { parse, valid, clean, inc, diff, major, minor, patch, prerelease, compare, rcompare, compareLoose, compareBuild, sort, rsort, gt, lt, eq, neq, gte, lte, cmp, coerce, Comparator, Range, satisfies, toComparators, maxSatisfying, minSatisfying, minVersion, validRange, outside, gtr, ltr, intersects, simplifyRange, subset, SemVer, re: internalRe.re, src: internalRe.src, tokens: internalRe.t, SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, RELEASE_TYPES: constants.RELEASE_TYPES, compareIdentifiers: identifiers.compareIdentifiers, rcompareIdentifiers: identifiers.rcompareIdentifiers, } /***/ }), /***/ 20184: /***/ ((module) => { // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. const SEMVER_SPEC_VERSION = '2.0.0' const MAX_LENGTH = 256 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. const MAX_SAFE_COMPONENT_LENGTH = 16 // Max safe length for a build identifier. The max length minus 6 characters for // the shortest version with a build 0.0.0+BUILD. const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 const RELEASE_TYPES = [ 'major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease', ] module.exports = { MAX_LENGTH, MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_SAFE_INTEGER, RELEASE_TYPES, SEMVER_SPEC_VERSION, FLAG_INCLUDE_PRERELEASE: 0b001, FLAG_LOOSE: 0b010, } /***/ }), /***/ 39433: /***/ ((module) => { const debug = ( typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ) ? (...args) => console.error('SEMVER', ...args) : () => {} module.exports = debug /***/ }), /***/ 49210: /***/ ((module) => { const numeric = /^[0-9]+$/ const compareIdentifiers = (a, b) => { const anum = numeric.test(a) const bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) module.exports = { compareIdentifiers, rcompareIdentifiers, } /***/ }), /***/ 99936: /***/ ((module) => { // parse out just the options we care about const looseOption = Object.freeze({ loose: true }) const emptyOpts = Object.freeze({ }) const parseOptions = options => { if (!options) { return emptyOpts } if (typeof options !== 'object') { return looseOption } return options } module.exports = parseOptions /***/ }), /***/ 20149: /***/ ((module, exports, __webpack_require__) => { const { MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_LENGTH, } = __webpack_require__(20184) const debug = __webpack_require__(39433) exports = module.exports = {} // The actual regexps go on exports.re const re = exports.re = [] const safeRe = exports.safeRe = [] const src = exports.src = [] const t = exports.t = {} let R = 0 const LETTERDASHNUMBER = '[a-zA-Z0-9-]' // Replace some greedy regex tokens to prevent regex dos issues. These regex are // used internally via the safeRe object since all inputs in this library get // normalized first to trim and collapse all extra whitespace. The original // regexes are exported for userland consumption and lower level usage. A // future breaking change could export the safer regex only with a note that // all input should have extra whitespace removed. const safeRegexReplacements = [ ['\\s', 1], ['\\d', MAX_LENGTH], [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], ] const makeSafeRegex = (value) => { for (const [token, max] of safeRegexReplacements) { value = value .split(`${token}*`).join(`${token}{0,${max}}`) .split(`${token}+`).join(`${token}{1,${max}}`) } return value } const createToken = (name, value, isGlobal) => { const safe = makeSafeRegex(value) const index = R++ debug(name, index, value) t[name] = index src[index] = value re[index] = new RegExp(value, isGlobal ? 'g' : undefined) safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) } // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') createToken('NUMERICIDENTIFIERLOOSE', '\\d+') // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) // ## Main Version // Three dot-separated numeric identifiers. createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`) createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] }|${src[t.NONNUMERICIDENTIFIER]})`) createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] }|${src[t.NONNUMERICIDENTIFIER]})`) // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] }(?:\\.${src[t.BUILDIDENTIFIER]})*))`) // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. createToken('FULLPLAIN', `v?${src[t.MAINVERSION] }${src[t.PRERELEASE]}?${ src[t.BUILD]}?`) createToken('FULL', `^${src[t.FULLPLAIN]}$`) // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] }${src[t.PRERELEASELOOSE]}?${ src[t.BUILD]}?`) createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) createToken('GTLT', '((?:<|>)?=?)') // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) // Coercion. // Extract anything that could conceivably be a part of a valid semver createToken('COERCE', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:$|[^\\d])`) createToken('COERCERTL', src[t.COERCE], true) // Tilde ranges. // Meaning is "reasonably at or greater than" createToken('LONETILDE', '(?:~>?)') createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) exports.tildeTrimReplace = '$1~' createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) // Caret ranges. // Meaning is "at least and backwards compatible with" createToken('LONECARET', '(?:\\^)') createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) exports.caretTrimReplace = '$1^' createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) // A simple gt/lt/eq thing, or just "" to indicate "any version" createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) exports.comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`) createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`) // Star ranges basically just allow anything at all. createToken('STAR', '(<|>)?=?\\s*\\*') // >=0.0.0 is like a star createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') /***/ }), /***/ 69028: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Determine if version is greater than all the versions possible in the range. const outside = __webpack_require__(97833) const gtr = (version, range, options) => outside(version, range, '>', options) module.exports = gtr /***/ }), /***/ 53407: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(43929) const intersects = (r1, r2, options) => { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2, options) } module.exports = intersects /***/ }), /***/ 41146: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const outside = __webpack_require__(97833) // Determine if version is less than all the versions possible in the range const ltr = (version, range, options) => outside(version, range, '<', options) module.exports = ltr /***/ }), /***/ 90088: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(21963) const Range = __webpack_require__(43929) const maxSatisfying = (versions, range, options) => { let max = null let maxSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } module.exports = maxSatisfying /***/ }), /***/ 82283: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(21963) const Range = __webpack_require__(43929) const minSatisfying = (versions, range, options) => { let min = null let minSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } module.exports = minSatisfying /***/ }), /***/ 20582: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(21963) const Range = __webpack_require__(43929) const gt = __webpack_require__(25591) const minVersion = (range, loose) => { range = new Range(range, loose) let minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let setMin = null comparators.forEach((comparator) => { // Clone to avoid manipulating the comparator's semver object. const compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!setMin || gt(compver, setMin)) { setMin = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error(`Unexpected operation: ${comparator.operator}`) } }) if (setMin && (!minver || gt(minver, setMin))) { minver = setMin } } if (minver && range.test(minver)) { return minver } return null } module.exports = minVersion /***/ }), /***/ 97833: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(21963) const Comparator = __webpack_require__(80977) const { ANY } = Comparator const Range = __webpack_require__(43929) const satisfies = __webpack_require__(48529) const gt = __webpack_require__(25591) const lt = __webpack_require__(7315) const lte = __webpack_require__(33017) const gte = __webpack_require__(35740) const outside = (version, range, hilo, options) => { version = new SemVer(version, options) range = new Range(range, options) let gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisfies the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let high = null let low = null comparators.forEach((comparator) => { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } module.exports = outside /***/ }), /***/ 7933: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // given a set of versions and a range, create a "simplified" range // that includes the same versions that the original range does // If the original range is shorter than the simplified one, return that. const satisfies = __webpack_require__(48529) const compare = __webpack_require__(82762) module.exports = (versions, range, options) => { const set = [] let first = null let prev = null const v = versions.sort((a, b) => compare(a, b, options)) for (const version of v) { const included = satisfies(version, range, options) if (included) { prev = version if (!first) { first = version } } else { if (prev) { set.push([first, prev]) } prev = null first = null } } if (first) { set.push([first, null]) } const ranges = [] for (const [min, max] of set) { if (min === max) { ranges.push(min) } else if (!max && min === v[0]) { ranges.push('*') } else if (!max) { ranges.push(`>=${min}`) } else if (min === v[0]) { ranges.push(`<=${max}`) } else { ranges.push(`${min} - ${max}`) } } const simplified = ranges.join(' || ') const original = typeof range.raw === 'string' ? range.raw : String(range) return simplified.length < original.length ? simplified : range } /***/ }), /***/ 59874: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(43929) const Comparator = __webpack_require__(80977) const { ANY } = Comparator const satisfies = __webpack_require__(48529) const compare = __webpack_require__(82762) // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: // - Every simple range `r1, r2, ...` is a null set, OR // - Every simple range `r1, r2, ...` which is not a null set is a subset of // some `R1, R2, ...` // // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: // - If c is only the ANY comparator // - If C is only the ANY comparator, return true // - Else if in prerelease mode, return false // - else replace c with `[>=0.0.0]` // - If C is only the ANY comparator // - if in prerelease mode, return true // - else replace C with `[>=0.0.0]` // - Let EQ be the set of = comparators in c // - If EQ is more than one, return true (null set) // - Let GT be the highest > or >= comparator in c // - Let LT be the lowest < or <= comparator in c // - If GT and LT, and GT.semver > LT.semver, return true (null set) // - If any C is a = range, and GT or LT are set, return false // - If EQ // - If GT, and EQ does not satisfy GT, return true (null set) // - If LT, and EQ does not satisfy LT, return true (null set) // - If EQ satisfies every C, return true // - Else return false // - If GT // - If GT.semver is lower than any > or >= comp in C, return false // - If GT is >=, and GT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the GT.semver tuple, return false // - If LT // - If LT.semver is greater than any < or <= comp in C, return false // - If LT is <=, and LT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the LT.semver tuple, return false // - Else return true const subset = (sub, dom, options = {}) => { if (sub === dom) { return true } sub = new Range(sub, options) dom = new Range(dom, options) let sawNonNull = false OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { const isSub = simpleSubset(simpleSub, simpleDom, options) sawNonNull = sawNonNull || isSub !== null if (isSub) { continue OUTER } } // the null set is a subset of everything, but null simple ranges in // a complex range should be ignored. so if we saw a non-null range, // then we know this isn't a subset, but if EVERY simple range was null, // then it is a subset. if (sawNonNull) { return false } } return true } const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] const minimumVersion = [new Comparator('>=0.0.0')] const simpleSubset = (sub, dom, options) => { if (sub === dom) { return true } if (sub.length === 1 && sub[0].semver === ANY) { if (dom.length === 1 && dom[0].semver === ANY) { return true } else if (options.includePrerelease) { sub = minimumVersionWithPreRelease } else { sub = minimumVersion } } if (dom.length === 1 && dom[0].semver === ANY) { if (options.includePrerelease) { return true } else { dom = minimumVersion } } const eqSet = new Set() let gt, lt for (const c of sub) { if (c.operator === '>' || c.operator === '>=') { gt = higherGT(gt, c, options) } else if (c.operator === '<' || c.operator === '<=') { lt = lowerLT(lt, c, options) } else { eqSet.add(c.semver) } } if (eqSet.size > 1) { return null } let gtltComp if (gt && lt) { gtltComp = compare(gt.semver, lt.semver, options) if (gtltComp > 0) { return null } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { return null } } // will iterate one or zero times for (const eq of eqSet) { if (gt && !satisfies(eq, String(gt), options)) { return null } if (lt && !satisfies(eq, String(lt), options)) { return null } for (const c of dom) { if (!satisfies(eq, String(c), options)) { return false } } return true } let higher, lower let hasDomLT, hasDomGT // if the subset has a prerelease, we need a comparator in the superset // with the same tuple and a prerelease, or it's not a subset let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false // exception: <1.2.3-0 is the same as <1.2.3 if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { needDomLTPre = false } for (const c of dom) { hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' if (gt) { if (needDomGTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { needDomGTPre = false } } if (c.operator === '>' || c.operator === '>=') { higher = higherGT(gt, c, options) if (higher === c && higher !== gt) { return false } } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { return false } } if (lt) { if (needDomLTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { needDomLTPre = false } } if (c.operator === '<' || c.operator === '<=') { lower = lowerLT(lt, c, options) if (lower === c && lower !== lt) { return false } } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { return false } } if (!c.operator && (lt || gt) && gtltComp !== 0) { return false } } // if there was a < or >, and nothing in the dom, then must be false // UNLESS it was limited by another range in the other direction. // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 if (gt && hasDomLT && !lt && gtltComp !== 0) { return false } if (lt && hasDomGT && !gt && gtltComp !== 0) { return false } // we needed a prerelease range in a specific tuple, but didn't get one // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, // because it includes prereleases in the 1.2.3 tuple if (needDomGTPre || needDomLTPre) { return false } return true } // >=1.2.3 is lower than >1.2.3 const higherGT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp > 0 ? a : comp < 0 ? b : b.operator === '>' && a.operator === '>=' ? b : a } // <=1.2.3 is higher than <1.2.3 const lowerLT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp < 0 ? a : comp > 0 ? b : b.operator === '<' && a.operator === '<=' ? b : a } module.exports = subset /***/ }), /***/ 72371: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(43929) // Mostly just for testing and legacy API reasons const toComparators = (range, options) => new Range(range, options).set .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) module.exports = toComparators /***/ }), /***/ 89031: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(43929) const validRange = (range, options) => { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } module.exports = validRange /***/ }), /***/ 58432: /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "__extends": () => (/* binding */ __extends), /* harmony export */ "__assign": () => (/* binding */ __assign), /* harmony export */ "__rest": () => (/* binding */ __rest), /* harmony export */ "__decorate": () => (/* binding */ __decorate), /* harmony export */ "__param": () => (/* binding */ __param), /* harmony export */ "__metadata": () => (/* binding */ __metadata), /* harmony export */ "__awaiter": () => (/* binding */ __awaiter), /* harmony export */ "__generator": () => (/* binding */ __generator), /* harmony export */ "__createBinding": () => (/* binding */ __createBinding), /* harmony export */ "__exportStar": () => (/* binding */ __exportStar), /* harmony export */ "__values": () => (/* binding */ __values), /* harmony export */ "__read": () => (/* binding */ __read), /* harmony export */ "__spread": () => (/* binding */ __spread), /* harmony export */ "__spreadArrays": () => (/* binding */ __spreadArrays), /* harmony export */ "__spreadArray": () => (/* binding */ __spreadArray), /* harmony export */ "__await": () => (/* binding */ __await), /* harmony export */ "__asyncGenerator": () => (/* binding */ __asyncGenerator), /* harmony export */ "__asyncDelegator": () => (/* binding */ __asyncDelegator), /* harmony export */ "__asyncValues": () => (/* binding */ __asyncValues), /* harmony export */ "__makeTemplateObject": () => (/* binding */ __makeTemplateObject), /* harmony export */ "__importStar": () => (/* binding */ __importStar), /* harmony export */ "__importDefault": () => (/* binding */ __importDefault), /* harmony export */ "__classPrivateFieldGet": () => (/* binding */ __classPrivateFieldGet), /* harmony export */ "__classPrivateFieldSet": () => (/* binding */ __classPrivateFieldSet) /* harmony export */ }); /*! ***************************************************************************** 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 */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; } return __assign.apply(this, arguments); } 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; } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var __createBinding = Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; }); function __exportStar(m, o) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } /** @deprecated */ function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } /** @deprecated */ function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; var __setModuleDefault = Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }; function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; } function __importDefault(mod) { return (mod && mod.__esModule) ? mod : { default: mod }; } function __classPrivateFieldGet(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); } function __classPrivateFieldSet(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; } /***/ }), /***/ 66163: /***/ ((module) => { "use strict"; module.exports = function (Yallist) { Yallist.prototype[Symbol.iterator] = function* () { for (let walker = this.head; walker; walker = walker.next) { yield walker.value } } } /***/ }), /***/ 79534: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = Yallist Yallist.Node = Node Yallist.create = Yallist function Yallist (list) { var self = this if (!(self instanceof Yallist)) { self = new Yallist() } self.tail = null self.head = null self.length = 0 if (list && typeof list.forEach === 'function') { list.forEach(function (item) { self.push(item) }) } else if (arguments.length > 0) { for (var i = 0, l = arguments.length; i < l; i++) { self.push(arguments[i]) } } return self } Yallist.prototype.removeNode = function (node) { if (node.list !== this) { throw new Error('removing node which does not belong to this list') } var next = node.next var prev = node.prev if (next) { next.prev = prev } if (prev) { prev.next = next } if (node === this.head) { this.head = next } if (node === this.tail) { this.tail = prev } node.list.length-- node.next = null node.prev = null node.list = null return next } Yallist.prototype.unshiftNode = function (node) { if (node === this.head) { return } if (node.list) { node.list.removeNode(node) } var head = this.head node.list = this node.next = head if (head) { head.prev = node } this.head = node if (!this.tail) { this.tail = node } this.length++ } Yallist.prototype.pushNode = function (node) { if (node === this.tail) { return } if (node.list) { node.list.removeNode(node) } var tail = this.tail node.list = this node.prev = tail if (tail) { tail.next = node } this.tail = node if (!this.head) { this.head = node } this.length++ } Yallist.prototype.push = function () { for (var i = 0, l = arguments.length; i < l; i++) { push(this, arguments[i]) } return this.length } Yallist.prototype.unshift = function () { for (var i = 0, l = arguments.length; i < l; i++) { unshift(this, arguments[i]) } return this.length } Yallist.prototype.pop = function () { if (!this.tail) { return undefined } var res = this.tail.value this.tail = this.tail.prev if (this.tail) { this.tail.next = null } else { this.head = null } this.length-- return res } Yallist.prototype.shift = function () { if (!this.head) { return undefined } var res = this.head.value this.head = this.head.next if (this.head) { this.head.prev = null } else { this.tail = null } this.length-- return res } Yallist.prototype.forEach = function (fn, thisp) { thisp = thisp || this for (var walker = this.head, i = 0; walker !== null; i++) { fn.call(thisp, walker.value, i, this) walker = walker.next } } Yallist.prototype.forEachReverse = function (fn, thisp) { thisp = thisp || this for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { fn.call(thisp, walker.value, i, this) walker = walker.prev } } Yallist.prototype.get = function (n) { for (var i = 0, walker = this.head; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.next } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.getReverse = function (n) { for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.prev } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.map = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.head; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.next } return res } Yallist.prototype.mapReverse = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.tail; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.prev } return res } Yallist.prototype.reduce = function (fn, initial) { var acc var walker = this.head if (arguments.length > 1) { acc = initial } else if (this.head) { walker = this.head.next acc = this.head.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = 0; walker !== null; i++) { acc = fn(acc, walker.value, i) walker = walker.next } return acc } Yallist.prototype.reduceReverse = function (fn, initial) { var acc var walker = this.tail if (arguments.length > 1) { acc = initial } else if (this.tail) { walker = this.tail.prev acc = this.tail.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = this.length - 1; walker !== null; i--) { acc = fn(acc, walker.value, i) walker = walker.prev } return acc } Yallist.prototype.toArray = function () { var arr = new Array(this.length) for (var i = 0, walker = this.head; walker !== null; i++) { arr[i] = walker.value walker = walker.next } return arr } Yallist.prototype.toArrayReverse = function () { var arr = new Array(this.length) for (var i = 0, walker = this.tail; walker !== null; i++) { arr[i] = walker.value walker = walker.prev } return arr } Yallist.prototype.slice = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = 0, walker = this.head; walker !== null && i < from; i++) { walker = walker.next } for (; walker !== null && i < to; i++, walker = walker.next) { ret.push(walker.value) } return ret } Yallist.prototype.sliceReverse = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { walker = walker.prev } for (; walker !== null && i > from; i--, walker = walker.prev) { ret.push(walker.value) } return ret } Yallist.prototype.splice = function (start, deleteCount, ...nodes) { if (start > this.length) { start = this.length - 1 } if (start < 0) { start = this.length + start; } for (var i = 0, walker = this.head; walker !== null && i < start; i++) { walker = walker.next } var ret = [] for (var i = 0; walker && i < deleteCount; i++) { ret.push(walker.value) walker = this.removeNode(walker) } if (walker === null) { walker = this.tail } if (walker !== this.head && walker !== this.tail) { walker = walker.prev } for (var i = 0; i < nodes.length; i++) { walker = insert(this, walker, nodes[i]) } return ret; } Yallist.prototype.reverse = function () { var head = this.head var tail = this.tail for (var walker = head; walker !== null; walker = walker.prev) { var p = walker.prev walker.prev = walker.next walker.next = p } this.head = tail this.tail = head return this } function insert (self, node, value) { var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self) if (inserted.next === null) { self.tail = inserted } if (inserted.prev === null) { self.head = inserted } self.length++ return inserted } function push (self, item) { self.tail = new Node(item, self.tail, null, self) if (!self.head) { self.head = self.tail } self.length++ } function unshift (self, item) { self.head = new Node(item, null, self.head, self) if (!self.tail) { self.tail = self.head } self.length++ } function Node (value, prev, next, list) { if (!(this instanceof Node)) { return new Node(value, prev, next, list) } this.list = list this.value = value if (prev) { prev.next = this this.prev = prev } else { this.prev = null } if (next) { next.prev = this this.next = next } else { this.next = null } } try { // add if support for Symbol.iterator is present __webpack_require__(66163)(Yallist) } catch (er) {} /***/ }), /***/ 1735: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DockerPull = void 0; const docker_registry_v2_client_1 = __webpack_require__(28310); const registryClient = __webpack_require__(28310); const crypto = __webpack_require__(6113); const fs = __webpack_require__(57147); const os = __webpack_require__(22037); const path = __webpack_require__(71017); const tar = __webpack_require__(75993); const crypto_1 = __webpack_require__(6113); const util_1 = __webpack_require__(73837); const subProcess = __webpack_require__(77685); const tmp = __webpack_require__(62697); const errors_1 = __webpack_require__(26518); const readFile = (0, util_1.promisify)(fs.readFile); const link = (0, util_1.promisify)(fs.link); const stat = (0, util_1.promisify)(fs.stat); const DEFAULT_LAYER_JSON = { created: "0001-01-01T00:00:00Z", container_config: { Hostname: "", Domainname: "", User: "", AttachStdin: false, AttachStdout: false, AttachStderr: false, Tty: false, OpenStdin: false, StdinOnce: false, Env: null, Cmd: null, Image: "", Volumes: null, WorkingDir: "", Entrypoint: null, OnBuild: null, Labels: null, }, }; class DockerPull { static async findDockerBinary() { return subProcess .execute("which", ["docker"], undefined, undefined, true) .then((cmdOutput) => cmdOutput.stdout.trim()) .catch((cmdOutput) => { throw new Error(cmdOutput.stderr); }); } /** * Downloads an image from a Container Registry. */ async pull(registryBase, repo, tag, opt) { var _a, _b; const loadImage = (opt === null || opt === void 0 ? void 0 : opt.loadImage) === undefined ? true : opt.loadImage; const manifest = await registryClient.getManifest(registryBase, repo, tag, opt === null || opt === void 0 ? void 0 : opt.username, opt === null || opt === void 0 ? void 0 : opt.password, opt === null || opt === void 0 ? void 0 : opt.reqOptions, opt === null || opt === void 0 ? void 0 : opt.platform); const indexDigest = (_a = manifest.indexDigest) !== null && _a !== void 0 ? _a : undefined; const manifestDigest = (_b = manifest.manifestDigest) !== null && _b !== void 0 ? _b : undefined; if (manifest.schemaVersion !== 2) { throw new errors_1.InvalidManifestSchemaVersionError(manifest.schemaVersion); } const imageConfigMetadata = manifest.config; const imageConfig = await registryClient.getImageConfig(registryBase, repo, imageConfigMetadata.digest, opt === null || opt === void 0 ? void 0 : opt.username, opt === null || opt === void 0 ? void 0 : opt.password, opt === null || opt === void 0 ? void 0 : opt.reqOptions); const t0 = Date.now(); const layersConfigs = manifest.layers; const blobDir = tmp.dirSync(); const missingLayers = await this.downloadLayers(blobDir, layersConfigs, registryBase, repo, opt === null || opt === void 0 ? void 0 : opt.username, opt === null || opt === void 0 ? void 0 : opt.password, opt === null || opt === void 0 ? void 0 : opt.reqOptions); const stagingDirPath = opt.stagingDirPath ? opt.stagingDirPath : os.tmpdir(); const pullDuration = Date.now() - t0; let imageDigest; const stagingDir = this.createDownloadedImageDestination(stagingDirPath, opt === null || opt === void 0 ? void 0 : opt.imageSavePath); try { if ((manifest === null || manifest === void 0 ? void 0 : manifest.manifestContentType) === docker_registry_v2_client_1.contentTypes.OCI_MANIFEST_V1) { await this.buildOCIImage(imageConfigMetadata.digest, manifest, imageConfig, missingLayers, blobDir, stagingDir); } else { await this.buildImage(imageConfigMetadata.digest, imageConfig, layersConfigs, missingLayers, blobDir, stagingDir); } if (loadImage) { imageDigest = await this.loadImage(registryBase, repo, tag, stagingDir); } } catch (err) { throw new Error(err.stderr); } finally { try { // Check is the image should be saved for debugging const saveMatcher = Object.assign(Object.assign({}, opt), { registryBase, repo, tag }); for (const [name, requestMatcher] of Object.entries(await this.saveRequests())) { if (Object.keys(requestMatcher).every((key) => requestMatcher[key] === saveMatcher[key])) { await link(path.join(stagingDir.name, "image.tar"), path.join(stagingDirPath, `${name}-${(0, crypto_1.randomUUID)()}.tar`)); break; } } } catch (err) { console.error("pullSaveRequest error: ", err); } blobDir.removeCallback(); if (loadImage) { stagingDir.removeCallback(); } } return { imageDigest, stagingDir: loadImage ? null : stagingDir, cachedLayersDigests: [], missingLayersDigests: missingLayers.map((layer) => layer.config.digest), pullDuration, indexDigest, manifestDigest, }; } async downloadLayers(blobDir, layersConfigs, registryBase, repo, username, password, // weak typing on the client // eslint-disable-next-line @typescript-eslint/no-explicit-any reqOptions = {}) { return await Promise.all(layersConfigs.map(async (config) => { const blobName = crypto.randomUUID(); await registryClient.downloadLayer(path.join(blobDir.name, blobName), registryBase, repo, config.digest, username, password, reqOptions); return { config, blobName }; })); } async saveRequests() { const saveRequestsPath = path.join(os.tmpdir(), "pullSaveRequest.json"); try { if (await stat(saveRequestsPath)) { return JSON.parse((await readFile(saveRequestsPath)).toString("utf-8")); } } catch (err) { return {}; } } async buildOCIImage(imageDigest, manifest, imageConfig, layers, blobDir, stagingDir) { const pack = tar.pack(blobDir.name, { // write layers entries: layers.map((layer) => layer.blobName), map(header) { const layer = layers.find((layer) => layer.blobName == header.name); const digest = layer.config.digest.replace("sha256:", ""); header.name = path.join("blobs", "sha256", digest); return header; }, finalize: false, finish(pack) { const configContent = JSON.stringify(imageConfig); const configDigest = imageDigest.replace("sha256:", ""); pack.entry({ name: path.join("blobs", "sha256", configDigest) }, configContent); // Ensure config digest and size is accurate following serialization round trip manifest.config.digest = `sha256:${configDigest}`; manifest.config.size = Buffer.byteLength(configContent, "utf8"); // Unset properties added by docker-registry-v2-client manifest.indexDigest = undefined; manifest.manifestDigest = undefined; manifest.manifestContentType = undefined; const manifestContent = JSON.stringify(manifest); const manifestDigest = crypto .createHash("sha256") .update(manifestContent) .digest("hex") .toLowerCase(); pack.entry({ name: path.join("blobs", "sha256", manifestDigest) }, manifestContent); const indexContent = JSON.stringify({ schemaVersion: 2, mediaType: docker_registry_v2_client_1.contentTypes.OCI_INDEX_V1, manifests: [ { mediaType: docker_registry_v2_client_1.contentTypes.OCI_MANIFEST_V1, size: Buffer.byteLength(manifestContent, "utf8"), digest: `sha256:${manifestDigest}`, }, ], }); pack.entry({ name: "index.json" }, indexContent); const ociLayoutContent = JSON.stringify({ imageLayoutVersion: "1.0.0", }); pack.entry({ name: "oci-layout" }, ociLayoutContent, () => { pack.finalize(); }); }, }); const imagePath = path.join(stagingDir.name, "image.tar"); const file = fs.createWriteStream(imagePath); pack.pipe(file); return new Promise((resolve, reject) => { file.on("close", () => resolve(path.join(imagePath))); file.on("error", (err) => reject(err)); }); } async buildImage(imageDigest, imageConfig, layersConfigs, layers, blobDir, stagingDir) { // generate layer metadata let parentDigest; const layerMetadata = {}; for (const layerConfig of layersConfigs) { const digest = layerConfig.digest.replace("sha256:", ""); let json = Object.assign({}, { id: digest }, DEFAULT_LAYER_JSON); if (parentDigest) { json = Object.assign({ parent: parentDigest }); } parentDigest = digest; layerMetadata[digest] = { json: JSON.stringify(json), version: "1.0", }; } const pack = tar.pack(blobDir.name, { // write layers entries: layers.map((layer) => layer.blobName), map(header) { const layer = layers.find((layer) => layer.blobName === header.name); const digest = layer.config.digest.replace("sha256:", ""); header.name = path.join(digest, "layer.tar"); return header; }, finalize: false, finish(pack) { // write layer metadata for (const digest of Object.keys(layerMetadata)) { const metadata = layerMetadata[digest]; pack.entry({ name: path.join(digest, "json") }, metadata.json); pack.entry({ name: path.join(digest, "VERSION") }, metadata.version); } imageDigest = imageDigest.replace("sha256:", ""); // write image json pack.entry({ name: `${imageDigest}.json` }, JSON.stringify(imageConfig)); // write manifest.json const manifestJson = [ { Config: `${imageDigest}.json`, RepoTags: null, Layers: layersConfigs.map((config) => `${config.digest.replace("sha256:", "")}/layer.tar`), }, ]; pack.entry({ name: "manifest.json" }, JSON.stringify(manifestJson), () => { pack.finalize(); }); }, }); const imagePath = path.join(stagingDir.name, "image.tar"); const file = fs.createWriteStream(imagePath); pack.pipe(file); return new Promise((resolve, reject) => { file.on("close", () => resolve(path.join(imagePath))); file.on("error", (err) => reject(err)); }); } async loadImage(registryBase, repo, tag, stagingDir) { const dockerBinary = await DockerPull.findDockerBinary(); const stdout = (await subProcess.execute(dockerBinary, ["load", "-i", "image.tar"], stagingDir.name)).stdout; // Loaded image ID: sha256:36456e9e9cb7c4b17d97461a5aeb062a481401e3d2b559285c7083d8e7f8efa6 const imgDigest = stdout.split("sha256:")[1].trim(); await subProcess.execute(dockerBinary, [ "tag", `${imgDigest}`, `${registryBase}/${repo}:${tag}`, ]); return imgDigest; } createDownloadedImageDestination(stagingDirPath, imageSavePath) { if (!imageSavePath) { return tmp.dirSync({ path: stagingDirPath }); } return { name: imageSavePath, removeCallback: () => { /* do nothing */ }, }; } } exports.DockerPull = DockerPull; //# sourceMappingURL=docker-pull.js.map /***/ }), /***/ 26518: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.InvalidManifestSchemaVersionError = void 0; class InvalidManifestSchemaVersionError extends Error { constructor(version) { super(`Invalid manifest schema version ${version}`); this.code = 422; } } exports.InvalidManifestSchemaVersionError = InvalidManifestSchemaVersionError; //# sourceMappingURL=errors.js.map /***/ }), /***/ 39106: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.InvalidManifestSchemaVersionError = exports.DockerPull = void 0; var docker_pull_1 = __webpack_require__(1735); Object.defineProperty(exports, "DockerPull", ({ enumerable: true, get: function () { return docker_pull_1.DockerPull; } })); var errors_1 = __webpack_require__(26518); Object.defineProperty(exports, "InvalidManifestSchemaVersionError", ({ enumerable: true, get: function () { return errors_1.InvalidManifestSchemaVersionError; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 77685: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.execute = void 0; const childProcess = __webpack_require__(32081); async function execute(command, args, cwd, env, shell = false) { const spawnOptions = { shell }; if (cwd) { spawnOptions.cwd = cwd; } if (env) { spawnOptions.env = env; } return new Promise((resolve, reject) => { let stdout = ""; let stderr = ""; const proc = childProcess.spawn(command, args, spawnOptions); proc.stdout.on("data", (data) => { stdout = stdout + data; }); proc.stderr.on("data", (data) => { stderr = stderr + data; }); proc.on("close", (code) => { const output = { stdout, stderr }; if (code !== 0) { return reject(output); } resolve(output); }); }); } exports.execute = execute; //# sourceMappingURL=sub-process.js.map /***/ }), /***/ 62697: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.dirSync = void 0; const fs = __webpack_require__(57147); const os = __webpack_require__(22037); const path = __webpack_require__(71017); /** * Creates a temporary directory. */ function dirSync(options) { var _a; const name = fs.mkdtempSync(`${(_a = options === null || options === void 0 ? void 0 : options.path) !== null && _a !== void 0 ? _a : os.tmpdir()}${path.sep}`); return { name, removeCallback() { fs.rmSync(name, { recursive: true }); }, }; } exports.dirSync = dirSync; //# sourceMappingURL=tmp.js.map /***/ }), /***/ 75993: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { const tar = __webpack_require__(5464) const pump = __webpack_require__(74286) const fs = __webpack_require__(57147) const path = __webpack_require__(71017) const win32 = (global.Bare?.platform || process.platform) === 'win32' exports.pack = function pack (cwd, opts) { if (!cwd) cwd = '.' if (!opts) opts = {} const xfs = opts.fs || fs const ignore = opts.ignore || opts.filter || noop const mapStream = opts.mapStream || echo const statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort) const strict = opts.strict !== false const umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask() const pack = opts.pack || tar.pack() const finish = opts.finish || noop let map = opts.map || noop let dmode = typeof opts.dmode === 'number' ? opts.dmode : 0 let fmode = typeof opts.fmode === 'number' ? opts.fmode : 0 if (opts.strip) map = strip(map, opts.strip) if (opts.readable) { dmode |= parseInt(555, 8) fmode |= parseInt(444, 8) } if (opts.writable) { dmode |= parseInt(333, 8) fmode |= parseInt(222, 8) } onnextentry() function onsymlink (filename, header) { xfs.readlink(path.join(cwd, filename), function (err, linkname) { if (err) return pack.destroy(err) header.linkname = normalize(linkname) pack.entry(header, onnextentry) }) } function onstat (err, filename, stat) { if (pack.destroyed) return if (err) return pack.destroy(err) if (!filename) { if (opts.finalize !== false) pack.finalize() return finish(pack) } if (stat.isSocket()) return onnextentry() // tar does not support sockets... let header = { name: normalize(filename), mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask, mtime: stat.mtime, size: stat.size, type: 'file', uid: stat.uid, gid: stat.gid } if (stat.isDirectory()) { header.size = 0 header.type = 'directory' header = map(header) || header return pack.entry(header, onnextentry) } if (stat.isSymbolicLink()) { header.size = 0 header.type = 'symlink' header = map(header) || header return onsymlink(filename, header) } // TODO: add fifo etc... header = map(header) || header if (!stat.isFile()) { if (strict) return pack.destroy(new Error('unsupported type for ' + filename)) return onnextentry() } const entry = pack.entry(header, onnextentry) const rs = mapStream(xfs.createReadStream(path.join(cwd, filename), { start: 0, end: header.size > 0 ? header.size - 1 : header.size }), header) rs.on('error', function (err) { // always forward errors on destroy entry.destroy(err) }) pump(rs, entry) } function onnextentry (err) { if (err) return pack.destroy(err) statNext(onstat) } return pack } function head (list) { return list.length ? list[list.length - 1] : null } function processGetuid () { return process.getuid ? process.getuid() : -1 } function processUmask () { return process.umask ? process.umask() : 0 } exports.extract = function extract (cwd, opts) { if (!cwd) cwd = '.' if (!opts) opts = {} cwd = path.resolve(cwd) const xfs = opts.fs || fs const ignore = opts.ignore || opts.filter || noop const mapStream = opts.mapStream || echo const own = opts.chown !== false && !win32 && processGetuid() === 0 const extract = opts.extract || tar.extract() const stack = [] const now = new Date() const umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask() const strict = opts.strict !== false let map = opts.map || noop let dmode = typeof opts.dmode === 'number' ? opts.dmode : 0 let fmode = typeof opts.fmode === 'number' ? opts.fmode : 0 if (opts.strip) map = strip(map, opts.strip) if (opts.readable) { dmode |= parseInt(555, 8) fmode |= parseInt(444, 8) } if (opts.writable) { dmode |= parseInt(333, 8) fmode |= parseInt(222, 8) } extract.on('entry', onentry) if (opts.finish) extract.on('finish', opts.finish) return extract function onentry (header, stream, next) { header = map(header) || header header.name = normalize(header.name) const name = path.join(cwd, path.join('/', header.name)) if (ignore(name, header)) { stream.resume() return next() } if (header.type === 'directory') { stack.push([name, header.mtime]) return mkdirfix(name, { fs: xfs, own, uid: header.uid, gid: header.gid, mode: header.mode }, stat) } const dir = path.dirname(name) validate(xfs, dir, path.join(cwd, '.'), function (err, valid) { if (err) return next(err) if (!valid) return next(new Error(dir + ' is not a valid path')) mkdirfix(dir, { fs: xfs, own, uid: header.uid, gid: header.gid, // normally, the folders with rights and owner should be part of the TAR file // if this is not the case, create folder for same user as file and with // standard permissions of 0o755 (rwxr-xr-x) mode: 0o755 }, function (err) { if (err) return next(err) switch (header.type) { case 'file': return onfile() case 'link': return onlink() case 'symlink': return onsymlink() } if (strict) return next(new Error('unsupported type for ' + name + ' (' + header.type + ')')) stream.resume() next() }) }) function stat (err) { if (err) return next(err) utimes(name, header, function (err) { if (err) return next(err) if (win32) return next() chperm(name, header, next) }) } function onsymlink () { if (win32) return next() // skip symlinks on win for now before it can be tested xfs.unlink(name, function () { const dst = path.resolve(path.dirname(name), header.linkname) if (!inCwd(dst)) return next(new Error(name + ' is not a valid symlink')) xfs.symlink(header.linkname, name, stat) }) } function onlink () { if (win32) return next() // skip links on win for now before it can be tested xfs.unlink(name, function () { const dst = path.join(cwd, path.join('/', header.linkname)) xfs.link(dst, name, function (err) { if (err && err.code === 'EPERM' && opts.hardlinkAsFilesFallback) { stream = xfs.createReadStream(dst) return onfile() } stat(err) }) }) } function inCwd (dst) { return dst.startsWith(cwd) } function onfile () { const ws = xfs.createWriteStream(name) const rs = mapStream(stream, header) ws.on('error', function (err) { // always forward errors on destroy rs.destroy(err) }) pump(rs, ws, function (err) { if (err) return next(err) ws.on('close', stat) }) } } function utimesParent (name, cb) { // we just set the mtime on the parent dir again everytime we write an entry let top while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop() if (!top) return cb() xfs.utimes(top[0], now, top[1], cb) } function utimes (name, header, cb) { if (opts.utimes === false) return cb() if (header.type === 'directory') return xfs.utimes(name, now, header.mtime, cb) if (header.type === 'symlink') return utimesParent(name, cb) // TODO: how to set mtime on link? xfs.utimes(name, now, header.mtime, function (err) { if (err) return cb(err) utimesParent(name, cb) }) } function chperm (name, header, cb) { const link = header.type === 'symlink' /* eslint-disable n/no-deprecated-api */ const chmod = link ? xfs.lchmod : xfs.chmod const chown = link ? xfs.lchown : xfs.chown /* eslint-enable n/no-deprecated-api */ if (!chmod) return cb() const mode = (header.mode | (header.type === 'directory' ? dmode : fmode)) & umask if (chown && own) chown.call(xfs, name, header.uid, header.gid, onchown) else onchown(null) function onchown (err) { if (err) return cb(err) if (!chmod) return cb() chmod.call(xfs, name, mode, cb) } } function mkdirfix (name, opts, cb) { // when mkdir is called on an existing directory, the permissions // will be overwritten (?), to avoid this we check for its existance first xfs.stat(name, function (err) { if (!err) return cb(null) if (err.code !== 'ENOENT') return cb(err) xfs.mkdir(name, { mode: opts.mode, recursive: true }, function (err, made) { if (err) return cb(err) chperm(name, opts, cb) }) }) } } function validate (fs, name, root, cb) { if (name === root) return cb(null, true) fs.lstat(name, function (err, st) { if (err && err.code === 'ENOENT') return validate(fs, path.join(name, '..'), root, cb) else if (err) return cb(err) cb(null, st.isDirectory()) }) } function noop () {} function echo (name) { return name } function normalize (name) { return win32 ? name.replace(/\\/g, '/').replace(/[:?<>|]/g, '_') : name } function statAll (fs, stat, cwd, ignore, entries, sort) { if (!entries) entries = ['.'] const queue = entries.slice(0) return function loop (callback) { if (!queue.length) return callback(null) const next = queue.shift() const nextAbs = path.join(cwd, next) stat.call(fs, nextAbs, function (err, stat) { // ignore errors if the files were deleted while buffering if (err) return callback(entries.indexOf(next) === -1 && err.code === 'ENOENT' ? null : err) if (!stat.isDirectory()) return callback(null, next, stat) fs.readdir(nextAbs, function (err, files) { if (err) return callback(err) if (sort) files.sort() for (let i = 0; i < files.length; i++) { if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i])) } callback(null, next, stat) }) }) } } function strip (map, level) { return function (header) { header.name = header.name.split('/').slice(level).join('/') const linkname = header.linkname if (linkname && (header.type === 'link' || path.isAbsolute(linkname))) { header.linkname = linkname.split('/').slice(level).join('/') } return map(header) } } /***/ }), /***/ 44152: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const constants = { // just for envs without fs S_IFMT: 61440, S_IFDIR: 16384, S_IFCHR: 8192, S_IFBLK: 24576, S_IFIFO: 4096, S_IFLNK: 40960 } try { module.exports = __webpack_require__(57147).constants || constants } catch { module.exports = constants } /***/ }), /***/ 32374: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const { Writable, Readable, getStreamError } = __webpack_require__(81237) const FIFO = __webpack_require__(91607) const b4a = __webpack_require__(85792) const headers = __webpack_require__(33335) const EMPTY = b4a.alloc(0) class BufferList { constructor () { this.buffered = 0 this.shifted = 0 this.queue = new FIFO() this._offset = 0 } push (buffer) { this.buffered += buffer.byteLength this.queue.push(buffer) } shiftFirst (size) { return this._buffered === 0 ? null : this._next(size) } shift (size) { if (size > this.buffered) return null if (size === 0) return EMPTY let chunk = this._next(size) if (size === chunk.byteLength) return chunk // likely case const chunks = [chunk] while ((size -= chunk.byteLength) > 0) { chunk = this._next(size) chunks.push(chunk) } return b4a.concat(chunks) } _next (size) { const buf = this.queue.peek() const rem = buf.byteLength - this._offset if (size >= rem) { const sub = this._offset ? buf.subarray(this._offset, buf.byteLength) : buf this.queue.shift() this._offset = 0 this.buffered -= rem this.shifted += rem return sub } this.buffered -= size this.shifted += size return buf.subarray(this._offset, (this._offset += size)) } } class Source extends Readable { constructor (self, header, offset) { super() this.header = header this.offset = offset this._parent = self } _read (cb) { if (this.header.size === 0) { this.push(null) } if (this._parent._stream === this) { this._parent._update() } cb(null) } _predestroy () { this._parent.destroy(getStreamError(this)) } _detach () { if (this._parent._stream === this) { this._parent._stream = null this._parent._missing = overflow(this.header.size) this._parent._update() } } _destroy (cb) { this._detach() cb(null) } } class Extract extends Writable { constructor (opts) { super(opts) if (!opts) opts = {} this._buffer = new BufferList() this._offset = 0 this._header = null this._stream = null this._missing = 0 this._longHeader = false this._callback = noop this._locked = false this._finished = false this._pax = null this._paxGlobal = null this._gnuLongPath = null this._gnuLongLinkPath = null this._filenameEncoding = opts.filenameEncoding || 'utf-8' this._allowUnknownFormat = !!opts.allowUnknownFormat this._unlockBound = this._unlock.bind(this) } _unlock (err) { this._locked = false if (err) { this.destroy(err) this._continueWrite(err) return } this._update() } _consumeHeader () { if (this._locked) return false this._offset = this._buffer.shifted try { this._header = headers.decode(this._buffer.shift(512), this._filenameEncoding, this._allowUnknownFormat) } catch (err) { this._continueWrite(err) return false } if (!this._header) return true switch (this._header.type) { case 'gnu-long-path': case 'gnu-long-link-path': case 'pax-global-header': case 'pax-header': this._longHeader = true this._missing = this._header.size return true } this._locked = true this._applyLongHeaders() if (this._header.size === 0 || this._header.type === 'directory') { this.emit('entry', this._header, this._createStream(), this._unlockBound) return true } this._stream = this._createStream() this._missing = this._header.size this.emit('entry', this._header, this._stream, this._unlockBound) return true } _applyLongHeaders () { if (this._gnuLongPath) { this._header.name = this._gnuLongPath this._gnuLongPath = null } if (this._gnuLongLinkPath) { this._header.linkname = this._gnuLongLinkPath this._gnuLongLinkPath = null } if (this._pax) { if (this._pax.path) this._header.name = this._pax.path if (this._pax.linkpath) this._header.linkname = this._pax.linkpath if (this._pax.size) this._header.size = parseInt(this._pax.size, 10) this._header.pax = this._pax this._pax = null } } _decodeLongHeader (buf) { switch (this._header.type) { case 'gnu-long-path': this._gnuLongPath = headers.decodeLongPath(buf, this._filenameEncoding) break case 'gnu-long-link-path': this._gnuLongLinkPath = headers.decodeLongPath(buf, this._filenameEncoding) break case 'pax-global-header': this._paxGlobal = headers.decodePax(buf) break case 'pax-header': this._pax = this._paxGlobal === null ? headers.decodePax(buf) : Object.assign({}, this._paxGlobal, headers.decodePax(buf)) break } } _consumeLongHeader () { this._longHeader = false this._missing = overflow(this._header.size) const buf = this._buffer.shift(this._header.size) try { this._decodeLongHeader(buf) } catch (err) { this._continueWrite(err) return false } return true } _consumeStream () { const buf = this._buffer.shiftFirst(this._missing) if (buf === null) return false this._missing -= buf.byteLength const drained = this._stream.push(buf) if (this._missing === 0) { this._stream.push(null) if (drained) this._stream._detach() return drained && this._locked === false } return drained } _createStream () { return new Source(this, this._header, this._offset) } _update () { while (this._buffer.buffered > 0 && !this.destroying) { if (this._missing > 0) { if (this._stream !== null) { if (this._consumeStream() === false) return continue } if (this._longHeader === true) { if (this._missing > this._buffer.buffered) break if (this._consumeLongHeader() === false) return false continue } const ignore = this._buffer.shiftFirst(this._missing) if (ignore !== null) this._missing -= ignore.byteLength continue } if (this._buffer.buffered < 512) break if (this._stream !== null || this._consumeHeader() === false) return } this._continueWrite(null) } _continueWrite (err) { const cb = this._callback this._callback = noop cb(err) } _write (data, cb) { this._callback = cb this._buffer.push(data) this._update() } _final (cb) { this._finished = this._missing === 0 && this._buffer.buffered === 0 cb(this._finished ? null : new Error('Unexpected end of data')) } _predestroy () { this._continueWrite(null) } _destroy (cb) { if (this._stream) this._stream.destroy(getStreamError(this)) cb(null) } [Symbol.asyncIterator] () { let error = null let promiseResolve = null let promiseReject = null let entryStream = null let entryCallback = null const extract = this this.on('entry', onentry) this.on('error', (err) => { error = err }) this.on('close', onclose) return { [Symbol.asyncIterator] () { return this }, next () { return new Promise(onnext) }, return () { return destroy(null) }, throw (err) { return destroy(err) } } function consumeCallback (err) { if (!entryCallback) return const cb = entryCallback entryCallback = null cb(err) } function onnext (resolve, reject) { if (error) { return reject(error) } if (entryStream) { resolve({ value: entryStream, done: false }) entryStream = null return } promiseResolve = resolve promiseReject = reject consumeCallback(null) if (extract._finished && promiseResolve) { promiseResolve({ value: undefined, done: true }) promiseResolve = promiseReject = null } } function onentry (header, stream, callback) { entryCallback = callback stream.on('error', noop) // no way around this due to tick sillyness if (promiseResolve) { promiseResolve({ value: stream, done: false }) promiseResolve = promiseReject = null } else { entryStream = stream } } function onclose () { consumeCallback(error) if (!promiseResolve) return if (error) promiseReject(error) else promiseResolve({ value: undefined, done: true }) promiseResolve = promiseReject = null } function destroy (err) { extract.destroy(err) consumeCallback(err) return new Promise((resolve, reject) => { if (extract.destroyed) return resolve({ value: undefined, done: true }) extract.once('close', function () { if (err) reject(err) else resolve({ value: undefined, done: true }) }) }) } } } module.exports = function extract (opts) { return new Extract(opts) } function noop () {} function overflow (size) { size &= 511 return size && 512 - size } /***/ }), /***/ 33335: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { const b4a = __webpack_require__(85792) const ZEROS = '0000000000000000000' const SEVENS = '7777777777777777777' const ZERO_OFFSET = '0'.charCodeAt(0) const USTAR_MAGIC = b4a.from([0x75, 0x73, 0x74, 0x61, 0x72, 0x00]) // ustar\x00 const USTAR_VER = b4a.from([ZERO_OFFSET, ZERO_OFFSET]) const GNU_MAGIC = b4a.from([0x75, 0x73, 0x74, 0x61, 0x72, 0x20]) // ustar\x20 const GNU_VER = b4a.from([0x20, 0x00]) const MASK = 0o7777 const MAGIC_OFFSET = 257 const VERSION_OFFSET = 263 exports.decodeLongPath = function decodeLongPath (buf, encoding) { return decodeStr(buf, 0, buf.length, encoding) } exports.encodePax = function encodePax (opts) { // TODO: encode more stuff in pax let result = '' if (opts.name) result += addLength(' path=' + opts.name + '\n') if (opts.linkname) result += addLength(' linkpath=' + opts.linkname + '\n') const pax = opts.pax if (pax) { for (const key in pax) { result += addLength(' ' + key + '=' + pax[key] + '\n') } } return b4a.from(result) } exports.decodePax = function decodePax (buf) { const result = {} while (buf.length) { let i = 0 while (i < buf.length && buf[i] !== 32) i++ const len = parseInt(b4a.toString(buf.subarray(0, i)), 10) if (!len) return result const b = b4a.toString(buf.subarray(i + 1, len - 1)) const keyIndex = b.indexOf('=') if (keyIndex === -1) return result result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1) buf = buf.subarray(len) } return result } exports.encode = function encode (opts) { const buf = b4a.alloc(512) let name = opts.name let prefix = '' if (opts.typeflag === 5 && name[name.length - 1] !== '/') name += '/' if (b4a.byteLength(name) !== name.length) return null // utf-8 while (b4a.byteLength(name) > 100) { const i = name.indexOf('/') if (i === -1) return null prefix += prefix ? '/' + name.slice(0, i) : name.slice(0, i) name = name.slice(i + 1) } if (b4a.byteLength(name) > 100 || b4a.byteLength(prefix) > 155) return null if (opts.linkname && b4a.byteLength(opts.linkname) > 100) return null b4a.write(buf, name) b4a.write(buf, encodeOct(opts.mode & MASK, 6), 100) b4a.write(buf, encodeOct(opts.uid, 6), 108) b4a.write(buf, encodeOct(opts.gid, 6), 116) encodeSize(opts.size, buf, 124) b4a.write(buf, encodeOct((opts.mtime.getTime() / 1000) | 0, 11), 136) buf[156] = ZERO_OFFSET + toTypeflag(opts.type) if (opts.linkname) b4a.write(buf, opts.linkname, 157) b4a.copy(USTAR_MAGIC, buf, MAGIC_OFFSET) b4a.copy(USTAR_VER, buf, VERSION_OFFSET) if (opts.uname) b4a.write(buf, opts.uname, 265) if (opts.gname) b4a.write(buf, opts.gname, 297) b4a.write(buf, encodeOct(opts.devmajor || 0, 6), 329) b4a.write(buf, encodeOct(opts.devminor || 0, 6), 337) if (prefix) b4a.write(buf, prefix, 345) b4a.write(buf, encodeOct(cksum(buf), 6), 148) return buf } exports.decode = function decode (buf, filenameEncoding, allowUnknownFormat) { let typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET let name = decodeStr(buf, 0, 100, filenameEncoding) const mode = decodeOct(buf, 100, 8) const uid = decodeOct(buf, 108, 8) const gid = decodeOct(buf, 116, 8) const size = decodeOct(buf, 124, 12) const mtime = decodeOct(buf, 136, 12) const type = toType(typeflag) const linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding) const uname = decodeStr(buf, 265, 32) const gname = decodeStr(buf, 297, 32) const devmajor = decodeOct(buf, 329, 8) const devminor = decodeOct(buf, 337, 8) const c = cksum(buf) // checksum is still initial value if header was null. if (c === 8 * 32) return null // valid checksum if (c !== decodeOct(buf, 148, 8)) throw new Error('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?') if (isUSTAR(buf)) { // ustar (posix) format. // prepend prefix, if present. if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + '/' + name } else if (isGNU(buf)) { // 'gnu'/'oldgnu' format. Similar to ustar, but has support for incremental and // multi-volume tarballs. } else { if (!allowUnknownFormat) { throw new Error('Invalid tar header: unknown format.') } } // to support old tar versions that use trailing / to indicate dirs if (typeflag === 0 && name && name[name.length - 1] === '/') typeflag = 5 return { name, mode, uid, gid, size, mtime: new Date(1000 * mtime), type, linkname, uname, gname, devmajor, devminor, pax: null } } function isUSTAR (buf) { return b4a.equals(USTAR_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6)) } function isGNU (buf) { return b4a.equals(GNU_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6)) && b4a.equals(GNU_VER, buf.subarray(VERSION_OFFSET, VERSION_OFFSET + 2)) } function clamp (index, len, defaultValue) { if (typeof index !== 'number') return defaultValue index = ~~index // Coerce to integer. if (index >= len) return len if (index >= 0) return index index += len if (index >= 0) return index return 0 } function toType (flag) { switch (flag) { case 0: return 'file' case 1: return 'link' case 2: return 'symlink' case 3: return 'character-device' case 4: return 'block-device' case 5: return 'directory' case 6: return 'fifo' case 7: return 'contiguous-file' case 72: return 'pax-header' case 55: return 'pax-global-header' case 27: return 'gnu-long-link-path' case 28: case 30: return 'gnu-long-path' } return null } function toTypeflag (flag) { switch (flag) { case 'file': return 0 case 'link': return 1 case 'symlink': return 2 case 'character-device': return 3 case 'block-device': return 4 case 'directory': return 5 case 'fifo': return 6 case 'contiguous-file': return 7 case 'pax-header': return 72 } return 0 } function indexOf (block, num, offset, end) { for (; offset < end; offset++) { if (block[offset] === num) return offset } return end } function cksum (block) { let sum = 8 * 32 for (let i = 0; i < 148; i++) sum += block[i] for (let j = 156; j < 512; j++) sum += block[j] return sum } function encodeOct (val, n) { val = val.toString(8) if (val.length > n) return SEVENS.slice(0, n) + ' ' return ZEROS.slice(0, n - val.length) + val + ' ' } function encodeSizeBin (num, buf, off) { buf[off] = 0x80 for (let i = 11; i > 0; i--) { buf[off + i] = num & 0xff num = Math.floor(num / 0x100) } } function encodeSize (num, buf, off) { if (num.toString(8).length > 11) { encodeSizeBin(num, buf, off) } else { b4a.write(buf, encodeOct(num, 11), off) } } /* Copied from the node-tar repo and modified to meet * tar-stream coding standard. * * Source: https://github.com/npm/node-tar/blob/51b6627a1f357d2eb433e7378e5f05e83b7aa6cd/lib/header.js#L349 */ function parse256 (buf) { // first byte MUST be either 80 or FF // 80 for positive, FF for 2's comp let positive if (buf[0] === 0x80) positive = true else if (buf[0] === 0xFF) positive = false else return null // build up a base-256 tuple from the least sig to the highest const tuple = [] let i for (i = buf.length - 1; i > 0; i--) { const byte = buf[i] if (positive) tuple.push(byte) else tuple.push(0xFF - byte) } let sum = 0 const l = tuple.length for (i = 0; i < l; i++) { sum += tuple[i] * Math.pow(256, i) } return positive ? sum : -1 * sum } function decodeOct (val, offset, length) { val = val.subarray(offset, offset + length) offset = 0 // If prefixed with 0x80 then parse as a base-256 integer if (val[offset] & 0x80) { return parse256(val) } else { // Older versions of tar can prefix with spaces while (offset < val.length && val[offset] === 32) offset++ const end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length) while (offset < end && val[offset] === 0) offset++ if (end === offset) return 0 return parseInt(b4a.toString(val.subarray(offset, end)), 8) } } function decodeStr (val, offset, length, encoding) { return b4a.toString(val.subarray(offset, indexOf(val, 0, offset, offset + length)), encoding) } function addLength (str) { const len = b4a.byteLength(str) let digits = Math.floor(Math.log(len) / Math.log(10)) + 1 if (len + digits >= Math.pow(10, digits)) digits++ return (len + digits) + str } /***/ }), /***/ 5464: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { exports.extract = __webpack_require__(32374) exports.pack = __webpack_require__(80349) /***/ }), /***/ 80349: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const { Readable, Writable, getStreamError } = __webpack_require__(81237) const b4a = __webpack_require__(85792) const constants = __webpack_require__(44152) const headers = __webpack_require__(33335) const DMODE = 0o755 const FMODE = 0o644 const END_OF_TAR = b4a.alloc(1024) class Sink extends Writable { constructor (pack, header, callback) { super({ mapWritable, eagerOpen: true }) this.written = 0 this.header = header this._callback = callback this._linkname = null this._isLinkname = header.type === 'symlink' && !header.linkname this._isVoid = header.type !== 'file' && header.type !== 'contiguous-file' this._finished = false this._pack = pack this._openCallback = null if (this._pack._stream === null) this._pack._stream = this else this._pack._pending.push(this) } _open (cb) { this._openCallback = cb if (this._pack._stream === this) this._continueOpen() } _continuePack (err) { if (this._callback === null) return const callback = this._callback this._callback = null callback(err) } _continueOpen () { if (this._pack._stream === null) this._pack._stream = this const cb = this._openCallback this._openCallback = null if (cb === null) return if (this._pack.destroying) return cb(new Error('pack stream destroyed')) if (this._pack._finalized) return cb(new Error('pack stream is already finalized')) this._pack._stream = this if (!this._isLinkname) { this._pack._encode(this.header) } if (this._isVoid) { this._finish() this._continuePack(null) } cb(null) } _write (data, cb) { if (this._isLinkname) { this._linkname = this._linkname ? b4a.concat([this._linkname, data]) : data return cb(null) } if (this._isVoid) { if (data.byteLength > 0) { return cb(new Error('No body allowed for this entry')) } return cb() } this.written += data.byteLength if (this._pack.push(data)) return cb() this._pack._drain = cb } _finish () { if (this._finished) return this._finished = true if (this._isLinkname) { this.header.linkname = this._linkname ? b4a.toString(this._linkname, 'utf-8') : '' this._pack._encode(this.header) } overflow(this._pack, this.header.size) this._pack._done(this) } _final (cb) { if (this.written !== this.header.size) { // corrupting tar return cb(new Error('Size mismatch')) } this._finish() cb(null) } _getError () { return getStreamError(this) || new Error('tar entry destroyed') } _predestroy () { this._pack.destroy(this._getError()) } _destroy (cb) { this._pack._done(this) this._continuePack(this._finished ? null : this._getError()) cb() } } class Pack extends Readable { constructor (opts) { super(opts) this._drain = noop this._finalized = false this._finalizing = false this._pending = [] this._stream = null } entry (header, buffer, callback) { if (this._finalized || this.destroying) throw new Error('already finalized or destroyed') if (typeof buffer === 'function') { callback = buffer buffer = null } if (!callback) callback = noop if (!header.size || header.type === 'symlink') header.size = 0 if (!header.type) header.type = modeToType(header.mode) if (!header.mode) header.mode = header.type === 'directory' ? DMODE : FMODE if (!header.uid) header.uid = 0 if (!header.gid) header.gid = 0 if (!header.mtime) header.mtime = new Date() if (typeof buffer === 'string') buffer = b4a.from(buffer) const sink = new Sink(this, header, callback) if (b4a.isBuffer(buffer)) { header.size = buffer.byteLength sink.write(buffer) sink.end() return sink } if (sink._isVoid) { return sink } return sink } finalize () { if (this._stream || this._pending.length > 0) { this._finalizing = true return } if (this._finalized) return this._finalized = true this.push(END_OF_TAR) this.push(null) } _done (stream) { if (stream !== this._stream) return this._stream = null if (this._finalizing) this.finalize() if (this._pending.length) this._pending.shift()._continueOpen() } _encode (header) { if (!header.pax) { const buf = headers.encode(header) if (buf) { this.push(buf) return } } this._encodePax(header) } _encodePax (header) { const paxHeader = headers.encodePax({ name: header.name, linkname: header.linkname, pax: header.pax }) const newHeader = { name: 'PaxHeader', mode: header.mode, uid: header.uid, gid: header.gid, size: paxHeader.byteLength, mtime: header.mtime, type: 'pax-header', linkname: header.linkname && 'PaxHeader', uname: header.uname, gname: header.gname, devmajor: header.devmajor, devminor: header.devminor } this.push(headers.encode(newHeader)) this.push(paxHeader) overflow(this, paxHeader.byteLength) newHeader.size = header.size newHeader.type = header.type this.push(headers.encode(newHeader)) } _doDrain () { const drain = this._drain this._drain = noop drain() } _predestroy () { const err = getStreamError(this) if (this._stream) this._stream.destroy(err) while (this._pending.length) { const stream = this._pending.shift() stream.destroy(err) stream._continueOpen() } this._doDrain() } _read (cb) { this._doDrain() cb() } } module.exports = function pack (opts) { return new Pack(opts) } function modeToType (mode) { switch (mode & constants.S_IFMT) { case constants.S_IFBLK: return 'block-device' case constants.S_IFCHR: return 'character-device' case constants.S_IFDIR: return 'directory' case constants.S_IFIFO: return 'fifo' case constants.S_IFLNK: return 'symlink' } return 'file' } function noop () {} function overflow (self, size) { size &= 511 if (size) self.push(END_OF_TAR.subarray(0, 512 - size)) } function mapWritable (buf) { return b4a.isBuffer(buf) ? buf : b4a.from(buf) } /***/ }), /***/ 88395: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.copyElixirCodeToTempDir = void 0; // This file was mostly copied from snyk-python-plugin and its purpose it to support the homebrew package const fs = __webpack_require__(57147); const path = __webpack_require__(85287); const tmp = __webpack_require__(36276); function copyElixirCodeToTempDir() { const tmpDir = tmp.dirSync({ unsafeCleanup: true }); dumpAllFilesInTempDir(tmpDir.name); return tmpDir; } exports.copyElixirCodeToTempDir = copyElixirCodeToTempDir; function dumpAllFilesInTempDir(tempDirName) { createAssets().forEach((currentReadFilePath) => { if (!fs.existsSync(currentReadFilePath)) { throw new Error('The file `' + currentReadFilePath + '` is missing'); } const relFilePathToDumpDir = getFilePathRelativeToDumpDir(currentReadFilePath); const writeFilePath = path.join(tempDirName, relFilePathToDumpDir); const contents = fs.readFileSync(currentReadFilePath, 'utf8'); writeFile(writeFilePath, contents); }); } function createAssets() { return [ path.join(__dirname, '../elixirsrc/mix.exs'), path.join(__dirname, '../elixirsrc/mix.lock'), path.join(__dirname, '../elixirsrc/lib/mix/tasks/read.mix.ex'), path.join(__dirname, '../elixirsrc/lib/json/mix.exs'), path.join(__dirname, '../elixirsrc/lib/json/lib/json/encoder.ex'), path.join(__dirname, '../elixirsrc/lib/json/lib/json/logger.ex'), path.join(__dirname, '../elixirsrc/lib/json/lib/json/decoder.ex'), path.join(__dirname, '../elixirsrc/lib/json/lib/json/encoder/default_implementations.ex'), path.join(__dirname, '../elixirsrc/lib/json/lib/json/encoder/errors.ex'), path.join(__dirname, '../elixirsrc/lib/json/lib/json/encoder/helpers.ex'), path.join(__dirname, '../elixirsrc/lib/json/lib/json/parser/number.ex'), path.join(__dirname, '../elixirsrc/lib/json/lib/json/parser/object.ex'), path.join(__dirname, '../elixirsrc/lib/json/lib/json/parser/unicode.ex'), path.join(__dirname, '../elixirsrc/lib/json/lib/json/parser/string.ex'), path.join(__dirname, '../elixirsrc/lib/json/lib/json/parser/array.ex'), path.join(__dirname, '../elixirsrc/lib/json/lib/json/parser.ex'), path.join(__dirname, '../elixirsrc/lib/json/lib/json.ex'), path.join(__dirname, '../elixirsrc/lib/json/.formatter.exs'), path.join(__dirname, '../elixirsrc/lib/common.ex'), path.join(__dirname, '../elixirsrc/lib/mix_project.ex'), ]; } function getFilePathRelativeToDumpDir(filePath) { let pathParts = filePath.split('\\elixirsrc\\'); // Windows if (pathParts.length > 1) { return pathParts[1]; } // Unix pathParts = filePath.split('/elixirsrc/'); return pathParts[1]; } function writeFile(writeFilePath, contents) { const dirPath = path.dirname(writeFilePath); if (!fs.existsSync(dirPath)) { fs.mkdirSync(dirPath, { recursive: true }); } fs.writeFileSync(writeFilePath, contents); } //# sourceMappingURL=copy-elixir-code-to-temp-dir.js.map /***/ }), /***/ 39410: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.init = exports.debug = void 0; const debugLib = __webpack_require__(15158); const PLUGIN_NAME = 'snyk-hex-plugin'; exports.debug = debugLib(PLUGIN_NAME); function init(enable = false) { enable ? debugLib.enable(PLUGIN_NAME) : debugLib.disable(); } exports.init = init; //# sourceMappingURL=debug.js.map /***/ }), /***/ 1649: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.inspect = exports.scan = void 0; var scan_1 = __webpack_require__(3113); Object.defineProperty(exports, "scan", ({ enumerable: true, get: function () { return scan_1.scan; } })); var inspect_1 = __webpack_require__(12442); Object.defineProperty(exports, "inspect", ({ enumerable: true, get: function () { return inspect_1.inspect; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 12442: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.inspect = void 0; const subProcess = __webpack_require__(21977); const scan_1 = __webpack_require__(3113); const PLUGIN_NAME = 'snyk-hex-plugin'; async function inspect(root, targetFile, options = {}) { const { debug, dev, allProjects, 'project-name': projectName } = options; const [scanResult, pluginVersion] = await Promise.all([ (0, scan_1.scan)({ debug, dev, allProjects, projectName, path: root, targetFile }), getPluginVersion(), ]); const scannedProjects = scanResult.scanResults.map(({ identity, facts: [{ data: depGraph }], name }) => ({ packageManager: 'hex', targetFile: identity.targetFile, depGraph, ...(name ? { meta: { projectName: name } } : {}), })); return { plugin: { name: PLUGIN_NAME, runtime: pluginVersion, targetFile: 'mix.exs', }, scannedProjects, }; } exports.inspect = inspect; async function getPluginVersion() { const output = await subProcess.execute('mix', ['-v']); const versionMatch = /(Mix\s\d+\.\d+\.\d*)/.exec(output); return versionMatch ? versionMatch[0] : 'Unknown version'; } //# sourceMappingURL=inspect.js.map /***/ }), /***/ 3113: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.scan = void 0; const path = __webpack_require__(85287); const fs = __webpack_require__(57147); const mix_parser_1 = __webpack_require__(72559); const subProcess = __webpack_require__(21977); const debug_1 = __webpack_require__(39410); const copy_elixir_code_to_temp_dir_1 = __webpack_require__(88395); const MANIFEST_FILE_NAME = 'mix.exs'; async function scan(options) { (0, debug_1.init)(options.debug); const targetFile = path.parse(path.resolve(options.path, options.targetFile || MANIFEST_FILE_NAME)); if (targetFile.base !== MANIFEST_FILE_NAME) { throw new Error("target file must be 'mix.exs'."); } await verifyMixInstalled(); const mixResult = await getMixResult(targetFile.dir); const depGraphMap = (0, mix_parser_1.buildDepGraphs)(mixResult, !!options.dev, true, options.allProjects); const scanResults = Object.entries(depGraphMap).map(([name, depGraph], index) => { const isRoot = index === 0; const relativePathToManifest = getRelativePathToManifest(options, targetFile, isRoot, name); return { identity: { type: 'hex', targetFile: relativePathToManifest, }, facts: [ { type: 'depGraph', data: depGraph, }, ], ...(options.projectName ? { name: getProjectNamePath(options, relativePathToManifest) } : {}), }; }); return { scanResults }; } exports.scan = scan; async function verifyMixInstalled() { try { const mixVersion = await subProcess.execute('mix', ['-v']); (0, debug_1.debug)(`mix version: `, mixVersion); } catch (_a) { throw new Error('mix is not installed. please make sure Elixir is installed and try again.'); } } async function getMixResult(root) { const elixirTmpDir = (0, copy_elixir_code_to_temp_dir_1.copyElixirCodeToTempDir)(); const cwd = elixirTmpDir.name; let filePath; try { const output = await subProcess.execute('mix', ['read.mix', root], { cwd }); (0, debug_1.debug)(`read.mix output: ${output}`); const fileName = output.trim().split('\n').pop(); (0, debug_1.debug)(`fileName: ${fileName}`); filePath = path.resolve(cwd, fileName); const result = (await fs.promises.readFile(filePath, 'utf8')); return JSON.parse(result); } catch (err) { const errorMessage = `Error parsing manifest file on ${root}`; (0, debug_1.debug)(errorMessage, err); throw new Error(errorMessage); } finally { try { elixirTmpDir.removeCallback(); } catch (err) { (0, debug_1.debug)(`can't remove ${elixirTmpDir.name}`, err); } } } function normalizePath(filePath) { const parts = filePath.split(path.sep); return parts.join(path.posix.sep); } function getRelativePathToManifest(options, targetFile, isRoot, name) { return normalizePath(path.relative(options.path, path.resolve(targetFile.dir, isRoot ? '' : name, targetFile.base))); } function getProjectNamePath(options, relativePathToManifest) { return [ options.projectName, ...relativePathToManifest.split('/').slice(0, -1), ].join('/'); } //# sourceMappingURL=scan.js.map /***/ }), /***/ 21977: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.execute = void 0; const childProcess = __webpack_require__(32081); const debug_1 = __webpack_require__(39410); const shescape_1 = __webpack_require__(79114); function execute(command, args, options) { (0, debug_1.debug)(`running "${command} ${args.join(' ')}"`); const spawnOptions = { shell: true }; if (options && options.cwd) { spawnOptions.cwd = options.cwd; } args = (0, shescape_1.quoteAll)(args, spawnOptions); return new Promise((resolve, reject) => { var _a, _b; let stdout = ''; let stderr = ''; const proc = childProcess.spawn(command, args, spawnOptions); (_a = proc.stdout) === null || _a === void 0 ? void 0 : _a.on('data', (data) => { stdout = stdout + data; }); (_b = proc.stderr) === null || _b === void 0 ? void 0 : _b.on('data', (data) => { stderr = stderr + data; }); proc.on('close', (code) => { if (code !== 0) { (0, debug_1.debug)(`Error running "${command} ${args.join(' ')}", exit code: ${code}`); return reject(stdout || stderr); } (0, debug_1.debug)(`Sub process stderr:`, stderr); resolve(stdout || stderr); }); }); } exports.execute = execute; //# sourceMappingURL=sub-process.js.map /***/ }), /***/ 13173: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isDigest = exports.validateDigest = void 0; const regexp_1 = __webpack_require__(69292); class InvalidDigestFormatError extends Error { constructor() { super('invalid digest format'); this.name = 'InvalidDigestFormatError'; } } class UnsupportedAlgorithmError extends Error { constructor() { super('unsupported digest algorithm'); this.name = 'UnsupportedAlgorithmError'; } } class InvalidDigestLengthError extends Error { constructor() { super('invalid checksum digest length'); this.name = 'InvalidDigestLengthError'; } } const algorithmsSizes = { sha256: 32, sha384: 48, sha512: 64, }; function checkDigest(digest, handleError) { const indexOfColon = digest.indexOf(':'); if (indexOfColon < 0 || indexOfColon + 1 === digest.length || !regexp_1.anchoredDigestRegexp.test(digest)) { return handleError(InvalidDigestFormatError); } const algorithm = digest.substring(0, indexOfColon); if (!Object.hasOwnProperty.call(algorithmsSizes, algorithm)) { return handleError(UnsupportedAlgorithmError); } if (algorithmsSizes[algorithm] * 2 !== (digest.length - indexOfColon - 1)) { return handleError(InvalidDigestLengthError); } return true; } const validateDigest = (digest) => { checkDigest(digest, (ErrorType) => { throw new ErrorType(); }); }; exports.validateDigest = validateDigest; const isDigest = (digest) => { return checkDigest(digest, () => false); }; exports.isDigest = isDigest; //# sourceMappingURL=digest.js.map /***/ }), /***/ 3687: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseAll = exports.parseFamiliarName = exports.parseQualifiedNameOptimized = exports.parseQualifiedName = exports.Reference = void 0; const reference_1 = __webpack_require__(12792); Object.defineProperty(exports, "Reference", ({ enumerable: true, get: function () { return reference_1.Reference; } })); const parsers_1 = __webpack_require__(57094); Object.defineProperty(exports, "parseAll", ({ enumerable: true, get: function () { return parsers_1.parseAll; } })); Object.defineProperty(exports, "parseFamiliarName", ({ enumerable: true, get: function () { return parsers_1.parseFamiliarName; } })); Object.defineProperty(exports, "parseQualifiedName", ({ enumerable: true, get: function () { return parsers_1.parseQualifiedName; } })); Object.defineProperty(exports, "parseQualifiedNameOptimized", ({ enumerable: true, get: function () { return parsers_1.parseQualifiedNameOptimized; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 57094: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseAll = exports.parseFamiliarName = exports.parseQualifiedName = exports.parseQualifiedNameOptimized = void 0; const regexp_1 = __webpack_require__(69292); const digest_1 = __webpack_require__(13173); const reference_1 = __webpack_require__(12792); const NAME_MAX_LENGTH = 255; class InvalidReferenceFormatError extends Error { constructor() { super("invalid reference format"); this.name = "InvalidReferenceFormatError"; } } class NameContainsUppercaseError extends Error { constructor() { super("repository name must be lowercase"); this.name = "NameContainsUppercaseError"; } } class EmptyNameError extends Error { constructor() { super("repository name must have at least one component"); this.name = "EmptyNameError"; } } class NameTooLongError extends Error { constructor() { super(`repository name must not be more than ${NAME_MAX_LENGTH} characters`); this.name = "NameTooLongError"; } } const DEFAULT_DOMAIN = "docker.io"; const LEGACY_DEFAULT_DOMAIN = "index.docker.io"; const OFFICIAL_REPOSITORY_NAME = "library"; function _parseQualifiedName(regexp, name) { const matches = regexp.exec(name); if (!matches) { if (name === "") { throw new EmptyNameError(); } if (regexp.test(name.toLowerCase())) { throw new NameContainsUppercaseError(); } throw new InvalidReferenceFormatError(); } if (matches[1].length > NAME_MAX_LENGTH) { throw new NameTooLongError(); } let reference; const nameMatch = regexp_1.anchoredNameRegexp.exec(matches[1]); if (nameMatch && nameMatch.length === 3) { reference = { domain: nameMatch[1], repository: nameMatch[2], }; } else { reference = { domain: "", repository: matches[1], }; } reference.tag = matches[2]; if (matches[3]) { (0, digest_1.validateDigest)(matches[3]); reference.digest = matches[3]; } return new reference_1.Reference(reference); } const parseQualifiedNameOptimized = (name) => { return _parseQualifiedName(new RegExp(regexp_1.referenceRegexp), name); }; exports.parseQualifiedNameOptimized = parseQualifiedNameOptimized; const parseQualifiedName = (name) => { return _parseQualifiedName(regexp_1.referenceRegexp, name); }; exports.parseQualifiedName = parseQualifiedName; function splitDockerDomain(name) { let domain; let reminder; const indexOfSlash = name.indexOf("/"); if (indexOfSlash === -1 || !(name.lastIndexOf(".", indexOfSlash) !== -1 || name.lastIndexOf(":", indexOfSlash) !== -1 || name.startsWith("localhost/"))) { domain = DEFAULT_DOMAIN; reminder = name; } else { domain = name.substring(0, indexOfSlash); reminder = name.substring(indexOfSlash + 1); } if (domain === LEGACY_DEFAULT_DOMAIN) { domain = DEFAULT_DOMAIN; } if (domain === DEFAULT_DOMAIN && !reminder.includes("/")) { reminder = `${OFFICIAL_REPOSITORY_NAME}/${reminder}`; } return [domain, reminder]; } const parseFamiliarName = (name, parseQualifiedNameFunc) => { if (regexp_1.anchoredIdentifierRegexp.test(name)) { throw new TypeError(`invalid repository name (${name}),` + `cannot specify 64-byte hexadecimal strings`); } const [domain, remainder] = splitDockerDomain(name); let remoteName; const tagSeparatorIndex = remainder.indexOf(":"); if (tagSeparatorIndex > -1) { remoteName = remainder.substring(0, tagSeparatorIndex); } else { remoteName = remainder; } if (remoteName.toLowerCase() !== remoteName) { throw new TypeError(`invalid reference format: repository name must be lowercase`); } if (parseQualifiedNameFunc) { return parseQualifiedNameFunc(`${domain}/${remainder}`); } return parseQualifiedName(`${domain}/${remainder}`); }; exports.parseFamiliarName = parseFamiliarName; const parseAll = (name) => { if (regexp_1.anchoredIdentifierRegexp.test(name)) { return new reference_1.Reference({ digest: `sha256:${name}` }); } if ((0, digest_1.isDigest)(name)) { return new reference_1.Reference({ digest: name }); } return parseFamiliarName(name); }; exports.parseAll = parseAll; //# sourceMappingURL=parsers.js.map /***/ }), /***/ 12792: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Reference = void 0; const typesTemplates = { 'digest': (ref) => `${ref.digest}`, 'canonical': (ref) => `${ref.repositoryUrl}@${ref.digest}`, 'repository': (ref) => `${ref.repositoryUrl}`, 'tagged': (ref) => `${ref.repositoryUrl}:${ref.tag}`, 'dual': (ref) => `${ref.repositoryUrl}:${ref.tag}@${ref.digest}` }; class Reference { get tag() { return this._tag; } get digest() { return this._digest; } get repository() { return this._repository; } get domain() { return this._domain; } get type() { return this._type; } constructor(options) { var _a, _b, _c, _d, _e, _f; if (!options.repository && !options.domain) { if (options.digest) { this._digest = options.digest; this._type = 'digest'; } else { throw new TypeError('Empty Reference'); } } else if (!options.tag) { this._domain = (_a = options.domain) !== null && _a !== void 0 ? _a : ''; this._repository = (_b = options.repository) !== null && _b !== void 0 ? _b : ''; if (options.digest) { this._digest = options.digest; this._type = 'canonical'; } else { this._type = 'repository'; } } else if (!options.digest) { this._domain = (_c = options.domain) !== null && _c !== void 0 ? _c : ''; this._repository = (_d = options.repository) !== null && _d !== void 0 ? _d : ''; this._tag = options.tag; this._type = 'tagged'; } else { this._domain = (_e = options.domain) !== null && _e !== void 0 ? _e : ''; this._repository = (_f = options.repository) !== null && _f !== void 0 ? _f : ''; this._tag = options.tag; this._digest = options.digest; this._type = 'dual'; } } toString() { return typesTemplates[this._type](this); } get repositoryUrl() { if (this._domain && this._repository) { return `${this._domain}/${this._repository}`; } return ''; } } exports.Reference = Reference; //# sourceMappingURL=reference.js.map /***/ }), /***/ 69292: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.anchoredIdentifierRegexp = exports.anchoredDigestRegexp = exports.anchoredNameRegexp = exports.referenceRegexp = void 0; const expression = (...regexps) => new RegExp(regexps .map(re => re.source) .join('')); const group = (...regexps) => new RegExp(`(?:${expression(...regexps).source})`); const optional = (...regexps) => new RegExp(`${group(...regexps).source}?`); const repeated = (...regexps) => new RegExp(`${group(...regexps).source}+`); const anchored = (...regexps) => new RegExp(`^${expression(...regexps).source}$`); const capture = (...regexps) => new RegExp(`(${expression(...regexps).source})`); const alphaNumericRegexp = /[a-z0-9]+/; const separatorRegexp = /(?:[._]|__|[-]*)/; const nameComponentRegexp = expression(alphaNumericRegexp, optional(repeated(separatorRegexp, alphaNumericRegexp))); const domainComponentRegexp = /(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])/; const domainRegexp = expression(domainComponentRegexp, optional(repeated(/\./, domainComponentRegexp)), optional(/:/, /[0-9]+/)); const tagRegexp = /[\w][\w.-]{0,127}/; const digestRegexp = /[a-zA-Z][a-zA-Z0-9]*(?:[-_+.][a-zA-Z][a-zA-Z0-9]*)*[:][a-fA-F0-9]{32,}/; const anchoredDigestRegexp = anchored(digestRegexp); exports.anchoredDigestRegexp = anchoredDigestRegexp; const nameRegexp = expression(optional(domainRegexp, /\//), nameComponentRegexp, optional(repeated(/\//, nameComponentRegexp))); const anchoredNameRegexp = anchored(optional(capture(domainRegexp), /\//), capture(nameComponentRegexp, optional(repeated(/\//, nameComponentRegexp)))); exports.anchoredNameRegexp = anchoredNameRegexp; const referenceRegexp = anchored(capture(nameRegexp), optional(/:/, capture(tagRegexp)), optional(/@/, capture(digestRegexp))); exports.referenceRegexp = referenceRegexp; const identifierRegexp = /[a-f0-9]{64}/; const anchoredIdentifierRegexp = anchored(identifierRegexp); exports.anchoredIdentifierRegexp = anchoredIdentifierRegexp; //# sourceMappingURL=regexp.js.map /***/ }), /***/ 60081: /***/ ((module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const defer_to_connect_1 = __webpack_require__(1313); const util_1 = __webpack_require__(73837); const nodejsMajorVersion = Number(process.versions.node.split('.')[0]); const timer = (request) => { if (request.timings) { return request.timings; } const timings = { start: Date.now(), socket: undefined, lookup: undefined, connect: undefined, secureConnect: undefined, upload: undefined, response: undefined, end: undefined, error: undefined, abort: undefined, phases: { wait: undefined, dns: undefined, tcp: undefined, tls: undefined, request: undefined, firstByte: undefined, download: undefined, total: undefined } }; request.timings = timings; const handleError = (origin) => { const emit = origin.emit.bind(origin); origin.emit = (event, ...args) => { // Catches the `error` event if (event === 'error') { timings.error = Date.now(); timings.phases.total = timings.error - timings.start; origin.emit = emit; } // Saves the original behavior return emit(event, ...args); }; }; handleError(request); const onAbort = () => { timings.abort = Date.now(); // Let the `end` response event be responsible for setting the total phase, // unless the Node.js major version is >= 13. if (!timings.response || nodejsMajorVersion >= 13) { timings.phases.total = Date.now() - timings.start; } }; request.prependOnceListener('abort', onAbort); const onSocket = (socket) => { timings.socket = Date.now(); timings.phases.wait = timings.socket - timings.start; if (util_1.types.isProxy(socket)) { return; } const lookupListener = () => { timings.lookup = Date.now(); timings.phases.dns = timings.lookup - timings.socket; }; socket.prependOnceListener('lookup', lookupListener); defer_to_connect_1.default(socket, { connect: () => { timings.connect = Date.now(); if (timings.lookup === undefined) { socket.removeListener('lookup', lookupListener); timings.lookup = timings.connect; timings.phases.dns = timings.lookup - timings.socket; } timings.phases.tcp = timings.connect - timings.lookup; // This callback is called before flushing any data, // so we don't need to set `timings.phases.request` here. }, secureConnect: () => { timings.secureConnect = Date.now(); timings.phases.tls = timings.secureConnect - timings.connect; } }); }; if (request.socket) { onSocket(request.socket); } else { request.prependOnceListener('socket', onSocket); } const onUpload = () => { var _a; timings.upload = Date.now(); timings.phases.request = timings.upload - ((_a = timings.secureConnect) !== null && _a !== void 0 ? _a : timings.connect); }; const writableFinished = () => { if (typeof request.writableFinished === 'boolean') { return request.writableFinished; } // Node.js doesn't have `request.writableFinished` property return request.finished && request.outputSize === 0 && (!request.socket || request.socket.writableLength === 0); }; if (writableFinished()) { onUpload(); } else { request.prependOnceListener('finish', onUpload); } request.prependOnceListener('response', (response) => { timings.response = Date.now(); timings.phases.firstByte = timings.response - timings.upload; response.timings = timings; handleError(response); response.prependOnceListener('end', () => { timings.end = Date.now(); timings.phases.download = timings.end - timings.response; timings.phases.total = timings.end - timings.start; }); response.prependOnceListener('aborted', onAbort); }); return timings; }; exports["default"] = timer; // For CommonJS default export support module.exports = timer; module.exports["default"] = timer; /***/ }), /***/ 19552: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Cache = void 0; const tslib_1 = __webpack_require__(70655); const fslib_1 = __webpack_require__(91794); const fslib_2 = __webpack_require__(91794); const libzip_1 = __webpack_require__(40364); const fs_1 = tslib_1.__importDefault(__webpack_require__(57147)); const MessageName_1 = __webpack_require__(62755); const Report_1 = __webpack_require__(50334); const hashUtils = tslib_1.__importStar(__webpack_require__(73279)); const miscUtils = tslib_1.__importStar(__webpack_require__(63111)); const structUtils = tslib_1.__importStar(__webpack_require__(34103)); const CACHE_VERSION = 7; class Cache { constructor(cacheCwd, { configuration, immutable = configuration.get(`enableImmutableCache`), check = false }) { // Contains the list of cache files that got accessed since the last time // you cleared the variable. Useful to know which files aren't needed // anymore when used in conjunction with fetchEverything. this.markedFiles = new Set(); this.mutexes = new Map(); this.configuration = configuration; this.cwd = cacheCwd; this.immutable = immutable; this.check = check; const cacheKeyOverride = configuration.get(`cacheKeyOverride`); if (cacheKeyOverride !== null) { this.cacheKey = `${cacheKeyOverride}`; } else { const compressionLevel = configuration.get(`compressionLevel`); const compressionKey = compressionLevel !== fslib_2.DEFAULT_COMPRESSION_LEVEL ? `c${compressionLevel}` : ``; this.cacheKey = [ CACHE_VERSION, compressionKey, ].join(``); } } static async find(configuration, { immutable, check } = {}) { const cache = new Cache(configuration.get(`cacheFolder`), { configuration, immutable, check }); await cache.setup(); return cache; } get mirrorCwd() { if (!this.configuration.get(`enableMirror`)) return null; const mirrorCwd = `${this.configuration.get(`globalFolder`)}/cache`; return mirrorCwd !== this.cwd ? mirrorCwd : null; } getVersionFilename(locator) { return `${structUtils.slugifyLocator(locator)}-${this.cacheKey}.zip`; } getChecksumFilename(locator, checksum) { // We only want the actual checksum (not the cache version, since the whole // point is to avoid changing the filenames when the cache version changes) const contentChecksum = getHashComponent(checksum); // We only care about the first few characters. It doesn't matter if that // makes the hash easier to collide with, because we check the file hashes // during each install anyway. const significantChecksum = contentChecksum.slice(0, 10); return `${structUtils.slugifyLocator(locator)}-${significantChecksum}.zip`; } getLocatorPath(locator, expectedChecksum) { // If there is no mirror, then the local cache *is* the mirror, in which // case we use the versioned filename pattern. if (this.mirrorCwd === null) return fslib_2.ppath.resolve(this.cwd, this.getVersionFilename(locator)); // If we don't yet know the checksum, discard the path resolution for now // until the checksum can be obtained from somewhere (mirror or network). if (expectedChecksum === null) return null; // If the cache key changed then we assume that the content probably got // altered as well and thus the existing path won't be good enough anymore. const cacheKey = getCacheKeyComponent(expectedChecksum); if (cacheKey !== this.cacheKey) return null; return fslib_2.ppath.resolve(this.cwd, this.getChecksumFilename(locator, expectedChecksum)); } getLocatorMirrorPath(locator) { const mirrorCwd = this.mirrorCwd; return mirrorCwd !== null ? fslib_2.ppath.resolve(mirrorCwd, this.getVersionFilename(locator)) : null; } async setup() { if (!this.configuration.get(`enableGlobalCache`)) { await fslib_2.xfs.mkdirPromise(this.cwd, { recursive: true }); const gitignorePath = fslib_2.ppath.resolve(this.cwd, `.gitignore`); await fslib_2.xfs.changeFilePromise(gitignorePath, `/.gitignore\n*.flock\n`); } } async fetchPackageFromCache(locator, expectedChecksum, { onHit, onMiss, loader, skipIntegrityCheck }) { const mirrorPath = this.getLocatorMirrorPath(locator); const baseFs = new fslib_1.NodeFS(); const validateFile = async (path, refetchPath = null) => { const actualChecksum = (!skipIntegrityCheck || !expectedChecksum) ? `${this.cacheKey}/${await hashUtils.checksumFile(path)}` : expectedChecksum; if (refetchPath !== null) { const previousChecksum = (!skipIntegrityCheck || !expectedChecksum) ? `${this.cacheKey}/${await hashUtils.checksumFile(refetchPath)}` : expectedChecksum; if (actualChecksum !== previousChecksum) { throw new Report_1.ReportError(MessageName_1.MessageName.CACHE_CHECKSUM_MISMATCH, `The remote archive doesn't match the local checksum - has the local cache been corrupted?`); } } if (expectedChecksum !== null && actualChecksum !== expectedChecksum) { let checksumBehavior; // Using --check-cache overrides any preconfigured checksum behavior if (this.check) checksumBehavior = `throw`; // If the lockfile references an old cache format, we tolerate different checksums else if (getCacheKeyComponent(expectedChecksum) !== getCacheKeyComponent(actualChecksum)) checksumBehavior = `update`; else checksumBehavior = this.configuration.get(`checksumBehavior`); switch (checksumBehavior) { case `ignore`: return expectedChecksum; case `update`: return actualChecksum; default: case `throw`: { throw new Report_1.ReportError(MessageName_1.MessageName.CACHE_CHECKSUM_MISMATCH, `The remote archive doesn't match the expected checksum`); } } } return actualChecksum; }; const validateFileAgainstRemote = async (cachePath) => { if (!loader) throw new Error(`Cache check required but no loader configured for ${structUtils.prettyLocator(this.configuration, locator)}`); const zipFs = await loader(); const refetchPath = zipFs.getRealPath(); zipFs.saveAndClose(); await fslib_2.xfs.chmodPromise(refetchPath, 0o644); return await validateFile(cachePath, refetchPath); }; const loadPackageThroughMirror = async () => { if (mirrorPath === null || !(await fslib_2.xfs.existsPromise(mirrorPath))) { const zipFs = await loader(); const realPath = zipFs.getRealPath(); zipFs.saveAndClose(); return realPath; } const tempDir = await fslib_2.xfs.mktempPromise(); const tempPath = fslib_2.ppath.join(tempDir, this.getVersionFilename(locator)); await fslib_2.xfs.copyFilePromise(mirrorPath, tempPath, fs_1.default.constants.COPYFILE_FICLONE); return tempPath; }; const loadPackage = async () => { if (!loader) throw new Error(`Cache entry required but missing for ${structUtils.prettyLocator(this.configuration, locator)}`); if (this.immutable) throw new Report_1.ReportError(MessageName_1.MessageName.IMMUTABLE_CACHE, `Cache entry required but missing for ${structUtils.prettyLocator(this.configuration, locator)}`); const originalPath = await loadPackageThroughMirror(); await fslib_2.xfs.chmodPromise(originalPath, 0o644); // Do this before moving the file so that we don't pollute the cache with corrupted archives const checksum = await validateFile(originalPath); const cachePath = this.getLocatorPath(locator, checksum); if (!cachePath) throw new Error(`Assertion failed: Expected the cache path to be available`); return await this.writeFileWithLock(cachePath, async () => { return await this.writeFileWithLock(mirrorPath, async () => { // Doing a move is important to ensure atomic writes (todo: cross-drive?) await fslib_2.xfs.movePromise(originalPath, cachePath); if (mirrorPath !== null) await fslib_2.xfs.copyFilePromise(cachePath, mirrorPath, fs_1.default.constants.COPYFILE_FICLONE); return [cachePath, checksum]; }); }); }; const loadPackageThroughMutex = async () => { const mutexedLoad = async () => { // We don't yet know whether the cache path can be computed yet, since that // depends on whether the cache is actually the mirror or not, and whether // the checksum is known or not. const tentativeCachePath = this.getLocatorPath(locator, expectedChecksum); const cacheExists = tentativeCachePath !== null ? await baseFs.existsPromise(tentativeCachePath) : false; const action = cacheExists ? onHit : onMiss; if (action) action(); if (!cacheExists) { return loadPackage(); } else { let checksum = null; const cachePath = tentativeCachePath; if (this.check) checksum = await validateFileAgainstRemote(cachePath); else checksum = await validateFile(cachePath); return [cachePath, checksum]; } }; const mutex = mutexedLoad(); this.mutexes.set(locator.locatorHash, mutex); try { return await mutex; } finally { this.mutexes.delete(locator.locatorHash); } }; for (let mutex; (mutex = this.mutexes.get(locator.locatorHash));) await mutex; const [cachePath, checksum] = await loadPackageThroughMutex(); this.markedFiles.add(cachePath); let zipFs = null; const libzip = await libzip_1.getLibzipPromise(); const lazyFs = new fslib_1.LazyFS(() => miscUtils.prettifySyncErrors(() => { return zipFs = new fslib_1.ZipFS(cachePath, { baseFs, libzip, readOnly: true }); }, message => { return `Failed to open the cache entry for ${structUtils.prettyLocator(this.configuration, locator)}: ${message}`; }), fslib_2.ppath); // We use an AliasFS to speed up getRealPath calls (e.g. VirtualFetcher.ensureVirtualLink) // (there's no need to create the lazy baseFs instance to gather the already-known cachePath) const aliasFs = new fslib_1.AliasFS(cachePath, { baseFs: lazyFs, pathUtils: fslib_2.ppath }); const releaseFs = () => { if (zipFs !== null) { zipFs.discardAndClose(); } }; return [aliasFs, releaseFs, checksum]; } async writeFileWithLock(file, generator) { if (file === null) return await generator(); await fslib_2.xfs.mkdirPromise(fslib_2.ppath.dirname(file), { recursive: true }); return await fslib_2.xfs.lockPromise(file, async () => { return await generator(); }); } } exports.Cache = Cache; function getCacheKeyComponent(checksum) { const split = checksum.indexOf(`/`); return split !== -1 ? checksum.slice(0, split) : null; } function getHashComponent(checksum) { const split = checksum.indexOf(`/`); return split !== -1 ? checksum.slice(split + 1) : checksum; } /***/ }), /***/ 62889: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Configuration = exports.ProjectLookup = exports.coreDefinitions = exports.FormatType = exports.SettingsType = exports.SECRET = exports.DEFAULT_LOCK_FILENAME = exports.DEFAULT_RC_FILENAME = exports.ENVIRONMENT_PREFIX = void 0; const tslib_1 = __webpack_require__(70655); const fslib_1 = __webpack_require__(91794); const fslib_2 = __webpack_require__(91794); const parsers_1 = __webpack_require__(21717); const camelcase_1 = tslib_1.__importDefault(__webpack_require__(35399)); const ci_info_1 = __webpack_require__(8288); const clipanion_1 = __webpack_require__(87730); const p_limit_1 = tslib_1.__importDefault(__webpack_require__(93743)); const semver_1 = tslib_1.__importDefault(__webpack_require__(74451)); const stream_1 = __webpack_require__(12781); const CorePlugin_1 = __webpack_require__(78101); const Manifest_1 = __webpack_require__(11658); const MultiFetcher_1 = __webpack_require__(74441); const MultiResolver_1 = __webpack_require__(54123); const ProtocolResolver_1 = __webpack_require__(6729); const VirtualFetcher_1 = __webpack_require__(7100); const VirtualResolver_1 = __webpack_require__(55605); const WorkspaceFetcher_1 = __webpack_require__(2925); const WorkspaceResolver_1 = __webpack_require__(83740); const folderUtils = tslib_1.__importStar(__webpack_require__(13061)); const formatUtils = tslib_1.__importStar(__webpack_require__(23821)); const miscUtils = tslib_1.__importStar(__webpack_require__(63111)); const nodeUtils = tslib_1.__importStar(__webpack_require__(83825)); const semverUtils = tslib_1.__importStar(__webpack_require__(51201)); const structUtils = tslib_1.__importStar(__webpack_require__(34103)); const types_1 = __webpack_require__(79588); const IGNORED_ENV_VARIABLES = new Set([ // "binFolder" is the magic location where the parent process stored the // current binaries; not an actual configuration settings `binFolder`, // "version" is set by Docker: // https://github.com/nodejs/docker-node/blob/5a6a5e91999358c5b04fddd6c22a9a4eb0bf3fbf/10/alpine/Dockerfile#L51 `version`, // "flags" is set by Netlify; they use it to specify the flags to send to the // CLI when running the automatic `yarn install` `flags`, // "gpg" and "profile" are used by the install.sh script: // https://classic.yarnpkg.com/install.sh `profile`, `gpg`, // "ignoreNode" is used to disable the Node version check `ignoreNode`, // "wrapOutput" was a variable used to indicate nested "yarn run" processes // back in Yarn 1. `wrapOutput`, ]); exports.ENVIRONMENT_PREFIX = `yarn_`; exports.DEFAULT_RC_FILENAME = `.yarnrc.yml`; exports.DEFAULT_LOCK_FILENAME = `yarn.lock`; exports.SECRET = `********`; var SettingsType; (function (SettingsType) { SettingsType["ANY"] = "ANY"; SettingsType["BOOLEAN"] = "BOOLEAN"; SettingsType["ABSOLUTE_PATH"] = "ABSOLUTE_PATH"; SettingsType["LOCATOR"] = "LOCATOR"; SettingsType["LOCATOR_LOOSE"] = "LOCATOR_LOOSE"; SettingsType["NUMBER"] = "NUMBER"; SettingsType["STRING"] = "STRING"; SettingsType["SECRET"] = "SECRET"; SettingsType["SHAPE"] = "SHAPE"; SettingsType["MAP"] = "MAP"; })(SettingsType = exports.SettingsType || (exports.SettingsType = {})); exports.FormatType = formatUtils.Type; // General rules: // // - filenames that don't accept actual paths must end with the "Filename" suffix // prefer to use absolute paths instead, since they are automatically resolved // ex: lockfileFilename // // - folders must end with the "Folder" suffix // ex: cacheFolder, pnpVirtualFolder // // - actual paths to a file must end with the "Path" suffix // ex: pnpPath // // - options that tweaks the strictness must begin with the "allow" prefix // ex: allowInvalidChecksums // // - options that enable a feature must begin with the "enable" prefix // ex: enableEmojis, enableColors exports.coreDefinitions = { // Not implemented for now, but since it's part of all Yarn installs we want to declare it in order to improve drop-in compatibility lastUpdateCheck: { description: `Last timestamp we checked whether new Yarn versions were available`, type: SettingsType.STRING, default: null, }, // Settings related to proxying all Yarn calls to a specific executable yarnPath: { description: `Path to the local executable that must be used over the global one`, type: SettingsType.ABSOLUTE_PATH, default: null, }, ignorePath: { description: `If true, the local executable will be ignored when using the global one`, type: SettingsType.BOOLEAN, default: false, }, ignoreCwd: { description: `If true, the \`--cwd\` flag will be ignored`, type: SettingsType.BOOLEAN, default: false, }, // Settings related to the package manager internal names cacheKeyOverride: { description: `A global cache key override; used only for test purposes`, type: SettingsType.STRING, default: null, }, globalFolder: { description: `Folder where are stored the system-wide settings`, type: SettingsType.ABSOLUTE_PATH, default: folderUtils.getDefaultGlobalFolder(), }, cacheFolder: { description: `Folder where the cache files must be written`, type: SettingsType.ABSOLUTE_PATH, default: `./.yarn/cache`, }, compressionLevel: { description: `Zip files compression level, from 0 to 9 or mixed (a variant of 9, which stores some files uncompressed, when compression doesn't yield good results)`, type: SettingsType.NUMBER, values: [`mixed`, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9], default: fslib_2.DEFAULT_COMPRESSION_LEVEL, }, virtualFolder: { description: `Folder where the virtual packages (cf doc) will be mapped on the disk (must be named $$virtual)`, type: SettingsType.ABSOLUTE_PATH, default: `./.yarn/$$virtual`, }, bstatePath: { description: `Path of the file where the current state of the built packages must be stored`, type: SettingsType.ABSOLUTE_PATH, default: `./.yarn/build-state.yml`, }, lockfileFilename: { description: `Name of the files where the Yarn dependency tree entries must be stored`, type: SettingsType.STRING, default: exports.DEFAULT_LOCK_FILENAME, }, installStatePath: { description: `Path of the file where the install state will be persisted`, type: SettingsType.ABSOLUTE_PATH, default: `./.yarn/install-state.gz`, }, immutablePatterns: { description: `Array of glob patterns; files matching them won't be allowed to change during immutable installs`, type: SettingsType.STRING, default: [], isArray: true, }, rcFilename: { description: `Name of the files where the configuration can be found`, type: SettingsType.STRING, default: getRcFilename(), }, enableGlobalCache: { description: `If true, the system-wide cache folder will be used regardless of \`cache-folder\``, type: SettingsType.BOOLEAN, default: false, }, enableAbsoluteVirtuals: { description: `If true, the virtual symlinks will use absolute paths if required [non portable!!]`, type: SettingsType.BOOLEAN, default: false, }, // Settings related to the output style enableColors: { description: `If true, the CLI is allowed to use colors in its output`, type: SettingsType.BOOLEAN, default: formatUtils.supportsColor, defaultText: ``, }, enableHyperlinks: { description: `If true, the CLI is allowed to use hyperlinks in its output`, type: SettingsType.BOOLEAN, default: formatUtils.supportsHyperlinks, defaultText: ``, }, enableInlineBuilds: { description: `If true, the CLI will print the build output on the command line`, type: SettingsType.BOOLEAN, default: ci_info_1.isCI, defaultText: ``, }, enableProgressBars: { description: `If true, the CLI is allowed to show a progress bar for long-running events`, type: SettingsType.BOOLEAN, default: !ci_info_1.isCI && process.stdout.isTTY && process.stdout.columns > 22, defaultText: ``, }, enableTimers: { description: `If true, the CLI is allowed to print the time spent executing commands`, type: SettingsType.BOOLEAN, default: true, }, preferAggregateCacheInfo: { description: `If true, the CLI will only print a one-line report of any cache changes`, type: SettingsType.BOOLEAN, default: ci_info_1.isCI, }, preferInteractive: { description: `If true, the CLI will automatically use the interactive mode when called from a TTY`, type: SettingsType.BOOLEAN, default: false, }, preferTruncatedLines: { description: `If true, the CLI will truncate lines that would go beyond the size of the terminal`, type: SettingsType.BOOLEAN, default: false, }, progressBarStyle: { description: `Which style of progress bar should be used (only when progress bars are enabled)`, type: SettingsType.STRING, default: undefined, defaultText: ``, }, // Settings related to how packages are interpreted by default defaultLanguageName: { description: `Default language mode that should be used when a package doesn't offer any insight`, type: SettingsType.STRING, default: `node`, }, defaultProtocol: { description: `Default resolution protocol used when resolving pure semver and tag ranges`, type: SettingsType.STRING, default: `npm:`, }, enableTransparentWorkspaces: { description: `If false, Yarn won't automatically resolve workspace dependencies unless they use the \`workspace:\` protocol`, type: SettingsType.BOOLEAN, default: true, }, // Settings related to network access enableMirror: { description: `If true, the downloaded packages will be retrieved and stored in both the local and global folders`, type: SettingsType.BOOLEAN, default: true, }, enableNetwork: { description: `If false, the package manager will refuse to use the network if required to`, type: SettingsType.BOOLEAN, default: true, }, httpProxy: { description: `URL of the http proxy that must be used for outgoing http requests`, type: SettingsType.STRING, default: null, }, httpsProxy: { description: `URL of the http proxy that must be used for outgoing https requests`, type: SettingsType.STRING, default: null, }, unsafeHttpWhitelist: { description: `List of the hostnames for which http queries are allowed (glob patterns are supported)`, type: SettingsType.STRING, default: [], isArray: true, }, httpTimeout: { description: `Timeout of each http request in milliseconds`, type: SettingsType.NUMBER, default: 60000, }, httpRetry: { description: `Retry times on http failure`, type: SettingsType.NUMBER, default: 3, }, networkConcurrency: { description: `Maximal number of concurrent requests`, type: SettingsType.NUMBER, default: Infinity, }, networkSettings: { description: `Network settings per hostname (glob patterns are supported)`, type: SettingsType.MAP, valueDefinition: { description: ``, type: SettingsType.SHAPE, properties: { caFilePath: { description: `Path to file containing one or multiple Certificate Authority signing certificates`, type: SettingsType.ABSOLUTE_PATH, default: null, }, enableNetwork: { description: `If false, the package manager will refuse to use the network if required to`, type: SettingsType.BOOLEAN, default: null, }, httpProxy: { description: `URL of the http proxy that must be used for outgoing http requests`, type: SettingsType.STRING, default: null, }, httpsProxy: { description: `URL of the http proxy that must be used for outgoing https requests`, type: SettingsType.STRING, default: null, }, }, }, }, caFilePath: { description: `A path to a file containing one or multiple Certificate Authority signing certificates`, type: SettingsType.ABSOLUTE_PATH, default: null, }, enableStrictSsl: { description: `If false, SSL certificate errors will be ignored`, type: SettingsType.BOOLEAN, default: true, }, logFilters: { description: `Overrides for log levels`, type: SettingsType.SHAPE, isArray: true, concatenateValues: true, properties: { code: { description: `Code of the messages covered by this override`, type: SettingsType.STRING, default: undefined, }, text: { description: `Code of the texts covered by this override`, type: SettingsType.STRING, default: undefined, }, level: { description: `Log level override, set to null to remove override`, type: SettingsType.STRING, values: Object.values(formatUtils.LogLevel), isNullable: true, default: undefined, }, }, }, // Settings related to telemetry enableTelemetry: { description: `If true, telemetry will be periodically sent, following the rules in https://yarnpkg.com/advanced/telemetry`, type: SettingsType.BOOLEAN, default: true, }, telemetryInterval: { description: `Minimal amount of time between two telemetry uploads, in days`, type: SettingsType.NUMBER, default: 7, }, telemetryUserId: { description: `If you desire to tell us which project you are, you can set this field. Completely optional and opt-in.`, type: SettingsType.STRING, default: null, }, // Settings related to security enableScripts: { description: `If true, packages are allowed to have install scripts by default`, type: SettingsType.BOOLEAN, default: true, }, enableImmutableCache: { description: `If true, the cache is reputed immutable and actions that would modify it will throw`, type: SettingsType.BOOLEAN, default: false, }, checksumBehavior: { description: `Enumeration defining what to do when a checksum doesn't match expectations`, type: SettingsType.STRING, default: `throw`, }, // Package patching - to fix incorrect definitions packageExtensions: { description: `Map of package corrections to apply on the dependency tree`, type: SettingsType.MAP, valueDefinition: { description: `The extension that will be applied to any package whose version matches the specified range`, type: SettingsType.SHAPE, properties: { dependencies: { description: `The set of dependencies that must be made available to the current package in order for it to work properly`, type: SettingsType.MAP, valueDefinition: { description: `A range`, type: SettingsType.STRING, }, }, peerDependencies: { description: `Inherited dependencies - the consumer of the package will be tasked to provide them`, type: SettingsType.MAP, valueDefinition: { description: `A semver range`, type: SettingsType.STRING, }, }, peerDependenciesMeta: { description: `Extra information related to the dependencies listed in the peerDependencies field`, type: SettingsType.MAP, valueDefinition: { description: `The peerDependency meta`, type: SettingsType.SHAPE, properties: { optional: { description: `If true, the selected peer dependency will be marked as optional by the package manager and the consumer omitting it won't be reported as an error`, type: SettingsType.BOOLEAN, default: false, }, }, }, }, }, }, }, }; function parseValue(configuration, path, value, definition, folder) { if (definition.isArray) { if (!Array.isArray(value)) { return String(value).split(/,/).map(segment => { return parseSingleValue(configuration, path, segment, definition, folder); }); } else { return value.map((sub, i) => parseSingleValue(configuration, `${path}[${i}]`, sub, definition, folder)); } } else { if (Array.isArray(value)) { throw new Error(`Non-array configuration settings "${path}" cannot be an array`); } else { return parseSingleValue(configuration, path, value, definition, folder); } } } function parseSingleValue(configuration, path, value, definition, folder) { var _a; switch (definition.type) { case SettingsType.ANY: return value; case SettingsType.SHAPE: return parseShape(configuration, path, value, definition, folder); case SettingsType.MAP: return parseMap(configuration, path, value, definition, folder); } if (value === null && !definition.isNullable && definition.default !== null) throw new Error(`Non-nullable configuration settings "${path}" cannot be set to null`); if ((_a = definition.values) === null || _a === void 0 ? void 0 : _a.includes(value)) return value; const interpretValue = () => { if (definition.type === SettingsType.BOOLEAN) return miscUtils.parseBoolean(value); if (typeof value !== `string`) throw new Error(`Expected value (${value}) to be a string`); const valueWithReplacedVariables = miscUtils.replaceEnvVariables(value, { env: process.env, }); switch (definition.type) { case SettingsType.ABSOLUTE_PATH: return fslib_1.ppath.resolve(folder, fslib_1.npath.toPortablePath(valueWithReplacedVariables)); case SettingsType.LOCATOR_LOOSE: return structUtils.parseLocator(valueWithReplacedVariables, false); case SettingsType.NUMBER: return parseInt(valueWithReplacedVariables); case SettingsType.LOCATOR: return structUtils.parseLocator(valueWithReplacedVariables); default: return valueWithReplacedVariables; } }; const interpreted = interpretValue(); if (definition.values && !definition.values.includes(interpreted)) throw new Error(`Invalid value, expected one of ${definition.values.join(`, `)}`); return interpreted; } function parseShape(configuration, path, value, definition, folder) { if (typeof value !== `object` || Array.isArray(value)) throw new clipanion_1.UsageError(`Object configuration settings "${path}" must be an object`); const result = getDefaultValue(configuration, definition, { ignoreArrays: true, }); if (value === null) return result; for (const [propKey, propValue] of Object.entries(value)) { const subPath = `${path}.${propKey}`; const subDefinition = definition.properties[propKey]; if (!subDefinition) throw new clipanion_1.UsageError(`Unrecognized configuration settings found: ${path}.${propKey} - run "yarn config -v" to see the list of settings supported in Yarn`); result.set(propKey, parseValue(configuration, subPath, propValue, definition.properties[propKey], folder)); } return result; } function parseMap(configuration, path, value, definition, folder) { const result = new Map(); if (typeof value !== `object` || Array.isArray(value)) throw new clipanion_1.UsageError(`Map configuration settings "${path}" must be an object`); if (value === null) return result; for (const [propKey, propValue] of Object.entries(value)) { const normalizedKey = definition.normalizeKeys ? definition.normalizeKeys(propKey) : propKey; const subPath = `${path}['${normalizedKey}']`; // @ts-expect-error: SettingsDefinitionNoDefault has ... no default ... but // that's fine because we're guaranteed it's not undefined. const valueDefinition = definition.valueDefinition; result.set(normalizedKey, parseValue(configuration, subPath, propValue, valueDefinition, folder)); } return result; } function getDefaultValue(configuration, definition, { ignoreArrays = false } = {}) { switch (definition.type) { case SettingsType.SHAPE: { if (definition.isArray && !ignoreArrays) return []; const result = new Map(); for (const [propKey, propDefinition] of Object.entries(definition.properties)) result.set(propKey, getDefaultValue(configuration, propDefinition)); return result; } break; case SettingsType.MAP: { if (definition.isArray && !ignoreArrays) return []; return new Map(); } break; case SettingsType.ABSOLUTE_PATH: { if (definition.default === null) return null; if (configuration.projectCwd === null) { if (fslib_1.ppath.isAbsolute(definition.default)) { return fslib_1.ppath.normalize(definition.default); } else if (definition.isNullable) { return null; } else { // Reached when a relative path is the default but the current // context is evaluated outside of a Yarn project return undefined; } } else { if (Array.isArray(definition.default)) { return definition.default.map((entry) => fslib_1.ppath.resolve(configuration.projectCwd, entry)); } else { return fslib_1.ppath.resolve(configuration.projectCwd, definition.default); } } } break; default: { return definition.default; } break; } } function transformConfiguration(rawValue, definition, transforms) { if (definition.type === SettingsType.SECRET && typeof rawValue === `string` && transforms.hideSecrets) return exports.SECRET; if (definition.type === SettingsType.ABSOLUTE_PATH && typeof rawValue === `string` && transforms.getNativePaths) return fslib_1.npath.fromPortablePath(rawValue); if (definition.isArray && Array.isArray(rawValue)) { const newValue = []; for (const value of rawValue) newValue.push(transformConfiguration(value, definition, transforms)); return newValue; } if (definition.type === SettingsType.MAP && rawValue instanceof Map) { const newValue = new Map(); for (const [key, value] of rawValue.entries()) newValue.set(key, transformConfiguration(value, definition.valueDefinition, transforms)); return newValue; } if (definition.type === SettingsType.SHAPE && rawValue instanceof Map) { const newValue = new Map(); for (const [key, value] of rawValue.entries()) { const propertyDefinition = definition.properties[key]; newValue.set(key, transformConfiguration(value, propertyDefinition, transforms)); } return newValue; } return rawValue; } function getEnvironmentSettings() { const environmentSettings = {}; for (let [key, value] of Object.entries(process.env)) { key = key.toLowerCase(); if (!key.startsWith(exports.ENVIRONMENT_PREFIX)) continue; key = camelcase_1.default(key.slice(exports.ENVIRONMENT_PREFIX.length)); environmentSettings[key] = value; } return environmentSettings; } function getRcFilename() { const rcKey = `${exports.ENVIRONMENT_PREFIX}rc_filename`; for (const [key, value] of Object.entries(process.env)) if (key.toLowerCase() === rcKey && typeof value === `string`) return value; return exports.DEFAULT_RC_FILENAME; } var ProjectLookup; (function (ProjectLookup) { ProjectLookup[ProjectLookup["LOCKFILE"] = 0] = "LOCKFILE"; ProjectLookup[ProjectLookup["MANIFEST"] = 1] = "MANIFEST"; ProjectLookup[ProjectLookup["NONE"] = 2] = "NONE"; })(ProjectLookup = exports.ProjectLookup || (exports.ProjectLookup = {})); class Configuration { constructor(startingCwd) { this.projectCwd = null; this.plugins = new Map(); this.settings = new Map(); this.values = new Map(); this.sources = new Map(); this.invalid = new Map(); this.packageExtensions = new Map(); this.limits = new Map(); this.startingCwd = startingCwd; } static create(startingCwd, projectCwdOrPlugins, maybePlugins) { const configuration = new Configuration(startingCwd); if (typeof projectCwdOrPlugins !== `undefined` && !(projectCwdOrPlugins instanceof Map)) configuration.projectCwd = projectCwdOrPlugins; configuration.importSettings(exports.coreDefinitions); const plugins = typeof maybePlugins !== `undefined` ? maybePlugins : projectCwdOrPlugins instanceof Map ? projectCwdOrPlugins : new Map(); for (const [name, plugin] of plugins) configuration.activatePlugin(name, plugin); return configuration; } /** * Instantiate a new configuration object exposing the configuration obtained * from reading the various rc files and the environment settings. * * The `pluginConfiguration` parameter is expected to indicate: * * 1. which modules should be made available to plugins when they require a * package (this is the dynamic linking part - for example we want all the * plugins to use the exact same version of @yarnpkg/core, which also is the * version used by the running Yarn instance). * * 2. which of those modules are actually plugins that need to be injected * within the configuration. * * Note that some extra plugins will be automatically added based on the * content of the rc files - with the rc plugins taking precedence over * the other ones. * * One particularity: the plugin initialization order is quite strict, with * plugins listed in /foo/bar/.yarnrc.yml taking precedence over plugins * listed in /foo/.yarnrc.yml and /.yarnrc.yml. Additionally, while plugins * can depend on one another, they can only depend on plugins that have been * instantiated before them (so a plugin listed in /foo/.yarnrc.yml can * depend on another one listed on /foo/bar/.yarnrc.yml, but not the other * way around). */ static async find(startingCwd, pluginConfiguration, { lookup = ProjectLookup.LOCKFILE, strict = true, usePath = false, useRc = true } = {}) { const environmentSettings = getEnvironmentSettings(); delete environmentSettings.rcFilename; const rcFiles = await Configuration.findRcFiles(startingCwd); const homeRcFile = await Configuration.findHomeRcFile(); const pickCoreFields = ({ ignoreCwd, yarnPath, ignorePath, lockfileFilename }) => ({ ignoreCwd, yarnPath, ignorePath, lockfileFilename }); const excludeCoreFields = ({ ignoreCwd, yarnPath, ignorePath, lockfileFilename, ...rest }) => rest; const configuration = new Configuration(startingCwd); configuration.importSettings(pickCoreFields(exports.coreDefinitions)); configuration.useWithSource(``, pickCoreFields(environmentSettings), startingCwd, { strict: false }); for (const { path, cwd, data } of rcFiles) configuration.useWithSource(path, pickCoreFields(data), cwd, { strict: false }); if (homeRcFile) configuration.useWithSource(homeRcFile.path, pickCoreFields(homeRcFile.data), homeRcFile.cwd, { strict: false }); if (usePath) { const yarnPath = configuration.get(`yarnPath`); const ignorePath = configuration.get(`ignorePath`); if (yarnPath !== null && !ignorePath) { return configuration; } } // We need to know the project root before being able to truly instantiate // our configuration, and to know that we need to know the lockfile name const lockfileFilename = configuration.get(`lockfileFilename`); let projectCwd; switch (lookup) { case ProjectLookup.LOCKFILE: { projectCwd = await Configuration.findProjectCwd(startingCwd, lockfileFilename); } break; case ProjectLookup.MANIFEST: { projectCwd = await Configuration.findProjectCwd(startingCwd, null); } break; case ProjectLookup.NONE: { if (fslib_1.xfs.existsSync(fslib_1.ppath.join(startingCwd, `package.json`))) { projectCwd = fslib_1.ppath.resolve(startingCwd); } else { projectCwd = null; } } break; } // Great! We now have enough information to really start to setup the // core configuration object. configuration.startingCwd = startingCwd; configuration.projectCwd = projectCwd; configuration.importSettings(excludeCoreFields(exports.coreDefinitions)); // Now that the configuration object is almost ready, we need to load all // the configured plugins const plugins = new Map([ [`@@core`, CorePlugin_1.CorePlugin], ]); const interop = (obj) => obj.__esModule ? obj.default : obj; if (pluginConfiguration !== null) { for (const request of pluginConfiguration.plugins.keys()) plugins.set(request, interop(pluginConfiguration.modules.get(request))); const requireEntries = new Map(); for (const request of nodeUtils.builtinModules()) requireEntries.set(request, () => nodeUtils.dynamicRequire(request)); for (const [request, embedModule] of pluginConfiguration.modules) requireEntries.set(request, () => embedModule); const dynamicPlugins = new Set(); const getDefault = (object) => { return object.default || object; }; const importPlugin = (pluginPath, source) => { const { factory, name } = nodeUtils.dynamicRequire(fslib_1.npath.fromPortablePath(pluginPath)); // Prevent plugin redefinition so that the ones declared deeper in the // filesystem always have precedence over the ones below. if (dynamicPlugins.has(name)) return; const pluginRequireEntries = new Map(requireEntries); const pluginRequire = (request) => { if (pluginRequireEntries.has(request)) { return pluginRequireEntries.get(request)(); } else { throw new clipanion_1.UsageError(`This plugin cannot access the package referenced via ${request} which is neither a builtin, nor an exposed entry`); } }; const plugin = miscUtils.prettifySyncErrors(() => { return getDefault(factory(pluginRequire)); }, message => { return `${message} (when initializing ${name}, defined in ${source})`; }); requireEntries.set(name, () => plugin); dynamicPlugins.add(name); plugins.set(name, plugin); }; if (environmentSettings.plugins) { for (const userProvidedPath of environmentSettings.plugins.split(`;`)) { const pluginPath = fslib_1.ppath.resolve(startingCwd, fslib_1.npath.toPortablePath(userProvidedPath)); importPlugin(pluginPath, ``); } } for (const { path, cwd, data } of rcFiles) { if (!useRc) continue; if (!Array.isArray(data.plugins)) continue; for (const userPluginEntry of data.plugins) { const userProvidedPath = typeof userPluginEntry !== `string` ? userPluginEntry.path : userPluginEntry; const pluginPath = fslib_1.ppath.resolve(cwd, fslib_1.npath.toPortablePath(userProvidedPath)); importPlugin(pluginPath, path); } } } for (const [name, plugin] of plugins) configuration.activatePlugin(name, plugin); configuration.useWithSource(``, excludeCoreFields(environmentSettings), startingCwd, { strict }); for (const { path, cwd, data } of rcFiles) configuration.useWithSource(path, excludeCoreFields(data), cwd, { strict }); // The home configuration is never strict because it improves support for // multiple projects using different Yarn versions on the same machine if (homeRcFile) configuration.useWithSource(homeRcFile.path, excludeCoreFields(homeRcFile.data), homeRcFile.cwd, { strict: false }); if (configuration.get(`enableGlobalCache`)) { configuration.values.set(`cacheFolder`, `${configuration.get(`globalFolder`)}/cache`); configuration.sources.set(`cacheFolder`, ``); } await configuration.refreshPackageExtensions(); return configuration; } static async findRcFiles(startingCwd) { const rcFilename = getRcFilename(); const rcFiles = []; let nextCwd = startingCwd; let currentCwd = null; while (nextCwd !== currentCwd) { currentCwd = nextCwd; const rcPath = fslib_1.ppath.join(currentCwd, rcFilename); if (fslib_1.xfs.existsSync(rcPath)) { const content = await fslib_1.xfs.readFilePromise(rcPath, `utf8`); let data; try { data = parsers_1.parseSyml(content); } catch (error) { let tip = ``; if (content.match(/^\s+(?!-)[^:]+\s+\S+/m)) tip = ` (in particular, make sure you list the colons after each key name)`; throw new clipanion_1.UsageError(`Parse error when loading ${rcPath}; please check it's proper Yaml${tip}`); } rcFiles.push({ path: rcPath, cwd: currentCwd, data }); } nextCwd = fslib_1.ppath.dirname(currentCwd); } return rcFiles; } static async findHomeRcFile() { const rcFilename = getRcFilename(); const homeFolder = folderUtils.getHomeFolder(); const homeRcFilePath = fslib_1.ppath.join(homeFolder, rcFilename); if (fslib_1.xfs.existsSync(homeRcFilePath)) { const content = await fslib_1.xfs.readFilePromise(homeRcFilePath, `utf8`); const data = parsers_1.parseSyml(content); return { path: homeRcFilePath, cwd: homeFolder, data }; } return null; } static async findProjectCwd(startingCwd, lockfileFilename) { let projectCwd = null; let nextCwd = startingCwd; let currentCwd = null; while (nextCwd !== currentCwd) { currentCwd = nextCwd; if (fslib_1.xfs.existsSync(fslib_1.ppath.join(currentCwd, `package.json`))) projectCwd = currentCwd; if (lockfileFilename !== null) { if (fslib_1.xfs.existsSync(fslib_1.ppath.join(currentCwd, lockfileFilename))) { projectCwd = currentCwd; break; } } else { if (projectCwd !== null) { break; } } nextCwd = fslib_1.ppath.dirname(currentCwd); } return projectCwd; } static async updateConfiguration(cwd, patch) { const rcFilename = getRcFilename(); const configurationPath = fslib_1.ppath.join(cwd, rcFilename); const current = fslib_1.xfs.existsSync(configurationPath) ? parsers_1.parseSyml(await fslib_1.xfs.readFilePromise(configurationPath, `utf8`)) : {}; let patched = false; let replacement; if (typeof patch === `function`) { try { replacement = patch(current); } catch (_a) { replacement = patch({}); } if (replacement === current) { return; } } else { replacement = current; for (const key of Object.keys(patch)) { const currentValue = current[key]; const patchField = patch[key]; let nextValue; if (typeof patchField === `function`) { try { nextValue = patchField(currentValue); } catch (_b) { nextValue = patchField(undefined); } } else { nextValue = patchField; } if (currentValue === nextValue) continue; replacement[key] = nextValue; patched = true; } if (!patched) { return; } } await fslib_1.xfs.changeFilePromise(configurationPath, parsers_1.stringifySyml(replacement), { automaticNewlines: true, }); } static async updateHomeConfiguration(patch) { const homeFolder = folderUtils.getHomeFolder(); return await Configuration.updateConfiguration(homeFolder, patch); } activatePlugin(name, plugin) { this.plugins.set(name, plugin); if (typeof plugin.configuration !== `undefined`) { this.importSettings(plugin.configuration); } } importSettings(definitions) { for (const [name, definition] of Object.entries(definitions)) { if (definition == null) continue; if (this.settings.has(name)) throw new Error(`Cannot redefine settings "${name}"`); this.settings.set(name, definition); this.values.set(name, getDefaultValue(this, definition)); } } useWithSource(source, data, folder, opts) { try { this.use(source, data, folder, opts); } catch (error) { error.message += ` (in ${formatUtils.pretty(this, source, formatUtils.Type.PATH)})`; throw error; } } use(source, data, folder, { strict = true, overwrite = false } = {}) { for (const key of Object.keys(data)) { const value = data[key]; if (typeof value === `undefined`) continue; // The plugins have already been loaded at this point if (key === `plugins`) continue; // Some environment variables should be ignored when applying the configuration if (source === `` && IGNORED_ENV_VARIABLES.has(key)) continue; // It wouldn't make much sense, would it? if (key === `rcFilename`) throw new clipanion_1.UsageError(`The rcFilename settings can only be set via ${`${exports.ENVIRONMENT_PREFIX}RC_FILENAME`.toUpperCase()}, not via a rc file`); const definition = this.settings.get(key); if (!definition) { if (strict) { throw new clipanion_1.UsageError(`Unrecognized or legacy configuration settings found: ${key} - run "yarn config -v" to see the list of settings supported in Yarn`); } else { this.invalid.set(key, source); continue; } } if (this.sources.has(key) && !(overwrite || definition.type === SettingsType.MAP || definition.isArray && definition.concatenateValues)) continue; let parsed; try { parsed = parseValue(this, key, data[key], definition, folder); } catch (error) { error.message += ` in ${formatUtils.pretty(this, source, formatUtils.Type.PATH)}`; throw error; } if (definition.type === SettingsType.MAP) { const previousValue = this.values.get(key); this.values.set(key, new Map(overwrite ? [...previousValue, ...parsed] : [...parsed, ...previousValue])); this.sources.set(key, `${this.sources.get(key)}, ${source}`); } else if (definition.isArray && definition.concatenateValues) { const previousValue = this.values.get(key); this.values.set(key, overwrite ? [...previousValue, ...parsed] : [...parsed, ...previousValue]); this.sources.set(key, `${this.sources.get(key)}, ${source}`); } else { this.values.set(key, parsed); this.sources.set(key, source); } } } get(key) { if (!this.values.has(key)) throw new Error(`Invalid configuration key "${key}"`); return this.values.get(key); } getSpecial(key, { hideSecrets = false, getNativePaths = false }) { const rawValue = this.get(key); const definition = this.settings.get(key); if (typeof definition === `undefined`) throw new clipanion_1.UsageError(`Couldn't find a configuration settings named "${key}"`); return transformConfiguration(rawValue, definition, { hideSecrets, getNativePaths, }); } getSubprocessStreams(logFile, { header, prefix, report }) { let stdout; let stderr; const logStream = fslib_1.xfs.createWriteStream(logFile); if (this.get(`enableInlineBuilds`)) { const stdoutLineReporter = report.createStreamReporter(`${prefix} ${formatUtils.pretty(this, `STDOUT`, `green`)}`); const stderrLineReporter = report.createStreamReporter(`${prefix} ${formatUtils.pretty(this, `STDERR`, `red`)}`); stdout = new stream_1.PassThrough(); stdout.pipe(stdoutLineReporter); stdout.pipe(logStream); stderr = new stream_1.PassThrough(); stderr.pipe(stderrLineReporter); stderr.pipe(logStream); } else { stdout = logStream; stderr = logStream; if (typeof header !== `undefined`) { stdout.write(`${header}\n`); } } return { stdout, stderr }; } makeResolver() { const pluginResolvers = []; for (const plugin of this.plugins.values()) for (const resolver of plugin.resolvers || []) pluginResolvers.push(new resolver()); return new MultiResolver_1.MultiResolver([ new VirtualResolver_1.VirtualResolver(), new WorkspaceResolver_1.WorkspaceResolver(), new ProtocolResolver_1.ProtocolResolver(), ...pluginResolvers, ]); } makeFetcher() { const pluginFetchers = []; for (const plugin of this.plugins.values()) for (const fetcher of plugin.fetchers || []) pluginFetchers.push(new fetcher()); return new MultiFetcher_1.MultiFetcher([ new VirtualFetcher_1.VirtualFetcher(), new WorkspaceFetcher_1.WorkspaceFetcher(), ...pluginFetchers, ]); } getLinkers() { const linkers = []; for (const plugin of this.plugins.values()) for (const linker of plugin.linkers || []) linkers.push(new linker()); return linkers; } async refreshPackageExtensions() { this.packageExtensions = new Map(); const packageExtensions = this.packageExtensions; const registerPackageExtension = (descriptor, extensionData, { userProvided = false } = {}) => { if (!semver_1.default.validRange(descriptor.range)) throw new Error(`Only semver ranges are allowed as keys for the lockfileExtensions setting`); const extension = new Manifest_1.Manifest(); extension.load(extensionData, { yamlCompatibilityMode: true }); const extensionsPerIdent = miscUtils.getArrayWithDefault(packageExtensions, descriptor.identHash); const extensionsPerRange = []; extensionsPerIdent.push([descriptor.range, extensionsPerRange]); const baseExtension = { status: types_1.PackageExtensionStatus.Inactive, userProvided, parentDescriptor: descriptor, }; for (const dependency of extension.dependencies.values()) extensionsPerRange.push({ ...baseExtension, type: types_1.PackageExtensionType.Dependency, descriptor: dependency, description: `${structUtils.stringifyIdent(descriptor)} > ${structUtils.stringifyIdent(dependency)}` }); for (const peerDependency of extension.peerDependencies.values()) extensionsPerRange.push({ ...baseExtension, type: types_1.PackageExtensionType.PeerDependency, descriptor: peerDependency, description: `${structUtils.stringifyIdent(descriptor)} >> ${structUtils.stringifyIdent(peerDependency)}` }); for (const [selector, meta] of extension.peerDependenciesMeta) { for (const [key, value] of Object.entries(meta)) { extensionsPerRange.push({ ...baseExtension, type: types_1.PackageExtensionType.PeerDependencyMeta, selector, key: key, value, description: `${structUtils.stringifyIdent(descriptor)} >> ${selector} / ${key}` }); } } }; await this.triggerHook(hooks => { return hooks.registerPackageExtensions; }, this, registerPackageExtension); for (const [descriptorString, extensionData] of this.get(`packageExtensions`)) { registerPackageExtension(structUtils.parseDescriptor(descriptorString, true), miscUtils.convertMapsToIndexableObjects(extensionData), { userProvided: true }); } } normalizePackage(original) { const pkg = structUtils.copyPackage(original); // We use the extensions to define additional dependencies that weren't // properly listed in the original package definition if (this.packageExtensions == null) throw new Error(`refreshPackageExtensions has to be called before normalizing packages`); const extensionsPerIdent = this.packageExtensions.get(original.identHash); if (typeof extensionsPerIdent !== `undefined`) { const version = original.version; if (version !== null) { for (const [range, extensionsPerRange] of extensionsPerIdent) { if (!semverUtils.satisfiesWithPrereleases(version, range)) continue; for (const extension of extensionsPerRange) { // If an extension is active for a package but redundant // for another one, it should be considered active if (extension.status === types_1.PackageExtensionStatus.Inactive) extension.status = types_1.PackageExtensionStatus.Redundant; switch (extension.type) { case types_1.PackageExtensionType.Dependency: { const currentDependency = pkg.dependencies.get(extension.descriptor.identHash); if (typeof currentDependency === `undefined`) { extension.status = types_1.PackageExtensionStatus.Active; pkg.dependencies.set(extension.descriptor.identHash, extension.descriptor); } } break; case types_1.PackageExtensionType.PeerDependency: { const currentPeerDependency = pkg.peerDependencies.get(extension.descriptor.identHash); if (typeof currentPeerDependency === `undefined`) { extension.status = types_1.PackageExtensionStatus.Active; pkg.peerDependencies.set(extension.descriptor.identHash, extension.descriptor); } } break; case types_1.PackageExtensionType.PeerDependencyMeta: { const currentPeerDependencyMeta = pkg.peerDependenciesMeta.get(extension.selector); if (typeof currentPeerDependencyMeta === `undefined` || !Object.prototype.hasOwnProperty.call(currentPeerDependencyMeta, extension.key) || currentPeerDependencyMeta[extension.key] !== extension.value) { extension.status = types_1.PackageExtensionStatus.Active; miscUtils.getFactoryWithDefault(pkg.peerDependenciesMeta, extension.selector, () => ({}))[extension.key] = extension.value; } } break; default: { miscUtils.assertNever(extension); } break; } } } } } // We also add implicit optional @types peer dependencies for each peer // dependency. This is for compatibility reason, as many existing packages // forget to define their @types/react optional peer dependency when they // peer-depend on react. const getTypesName = (descriptor) => { return descriptor.scope ? `${descriptor.scope}__${descriptor.name}` : `${descriptor.name}`; }; for (const descriptor of pkg.peerDependencies.values()) { if (descriptor.scope === `@types`) continue; const typesName = getTypesName(descriptor); const typesIdent = structUtils.makeIdent(`types`, typesName); if (pkg.peerDependencies.has(typesIdent.identHash) || pkg.peerDependenciesMeta.has(typesIdent.identHash)) continue; pkg.peerDependenciesMeta.set(structUtils.stringifyIdent(typesIdent), { optional: true, }); } // I don't like implicit dependencies, but package authors are reluctant to // use optional peer dependencies because they would print warnings in older // npm releases. for (const identString of pkg.peerDependenciesMeta.keys()) { const ident = structUtils.parseIdent(identString); if (!pkg.peerDependencies.has(ident.identHash)) { pkg.peerDependencies.set(ident.identHash, structUtils.makeDescriptor(ident, `*`)); } } // We sort the dependencies so that further iterations always occur in the // same order, regardless how the various registries formatted their output pkg.dependencies = new Map(miscUtils.sortMap(pkg.dependencies, ([, descriptor]) => structUtils.stringifyDescriptor(descriptor))); pkg.peerDependencies = new Map(miscUtils.sortMap(pkg.peerDependencies, ([, descriptor]) => structUtils.stringifyDescriptor(descriptor))); return pkg; } getLimit(key) { return miscUtils.getFactoryWithDefault(this.limits, key, () => { return p_limit_1.default(this.get(key)); }); } async triggerHook(get, ...args) { for (const plugin of this.plugins.values()) { const hooks = plugin.hooks; if (!hooks) continue; const hook = get(hooks); if (!hook) continue; await hook(...args); } } async triggerMultipleHooks(get, argsList) { for (const args of argsList) { await this.triggerHook(get, ...args); } } async reduceHook(get, initialValue, ...args) { let value = initialValue; for (const plugin of this.plugins.values()) { const hooks = plugin.hooks; if (!hooks) continue; const hook = get(hooks); if (!hook) continue; value = await hook(value, ...args); } return value; } async firstHook(get, ...args) { for (const plugin of this.plugins.values()) { const hooks = plugin.hooks; if (!hooks) continue; const hook = get(hooks); if (!hook) continue; const ret = await hook(...args); if (typeof ret !== `undefined`) { // @ts-expect-error return ret; } } return null; } /** * @deprecated Prefer using formatUtils.pretty instead, which is type-safe */ format(value, formatType) { return formatUtils.pretty(this, value, formatType); } } exports.Configuration = Configuration; Configuration.telemetry = null; /***/ }), /***/ 78101: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CorePlugin = void 0; const tslib_1 = __webpack_require__(70655); const MessageName_1 = __webpack_require__(62755); const structUtils = tslib_1.__importStar(__webpack_require__(34103)); exports.CorePlugin = { hooks: { reduceDependency: (dependency, project, locator, initialDependency, { resolver, resolveOptions }) => { for (const { pattern, reference } of project.topLevelWorkspace.manifest.resolutions) { if (pattern.from && pattern.from.fullName !== structUtils.requirableIdent(locator)) continue; if (pattern.from && pattern.from.description && pattern.from.description !== locator.reference) continue; if (pattern.descriptor.fullName !== structUtils.requirableIdent(dependency)) continue; if (pattern.descriptor.description && pattern.descriptor.description !== dependency.range) continue; const alias = resolver.bindDescriptor(structUtils.makeDescriptor(dependency, reference), project.topLevelWorkspace.anchoredLocator, resolveOptions); return alias; } return dependency; }, validateProject: async (project, report) => { for (const workspace of project.workspaces) { const workspaceName = structUtils.prettyWorkspace(project.configuration, workspace); await project.configuration.triggerHook(hooks => { return hooks.validateWorkspace; }, workspace, { reportWarning: (name, text) => report.reportWarning(name, `${workspaceName}: ${text}`), reportError: (name, text) => report.reportError(name, `${workspaceName}: ${text}`), }); } }, validateWorkspace: async (workspace, report) => { // Validate manifest const { manifest } = workspace; if (manifest.resolutions.length && workspace.cwd !== workspace.project.cwd) manifest.errors.push(new Error(`Resolutions field will be ignored`)); for (const manifestError of manifest.errors) { report.reportWarning(MessageName_1.MessageName.INVALID_MANIFEST, manifestError.message); } }, }, }; /***/ }), /***/ 45006: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BuildType = void 0; var BuildType; (function (BuildType) { BuildType[BuildType["SCRIPT"] = 0] = "SCRIPT"; BuildType[BuildType["SHELLCODE"] = 1] = "SHELLCODE"; })(BuildType = exports.BuildType || (exports.BuildType = {})); /***/ }), /***/ 48900: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LegacyMigrationResolver = void 0; const tslib_1 = __webpack_require__(70655); const fslib_1 = __webpack_require__(91794); const parsers_1 = __webpack_require__(21717); const semver_1 = tslib_1.__importDefault(__webpack_require__(74451)); const MessageName_1 = __webpack_require__(62755); const structUtils = tslib_1.__importStar(__webpack_require__(34103)); const IMPORTED_PATTERNS = [ // These ones come from Git urls [/^(git(?:\+(?:https|ssh))?:\/\/.*(?:\.git)?)#(.*)$/, (version, $0, $1, $2) => `${$1}#commit=${$2}`], // These ones come from the GitHub HTTP endpoints [/^https:\/\/((?:[^/]+?)@)?codeload\.github\.com\/([^/]+\/[^/]+)\/tar\.gz\/([0-9a-f]+)$/, (version, $0, $1 = ``, $2, $3) => `https://${$1}github.com/${$2}.git#commit=${$3}`], [/^https:\/\/((?:[^/]+?)@)?github\.com\/([^/]+\/[^/]+?)(?:\.git)?#([0-9a-f]+)$/, (version, $0, $1 = ``, $2, $3) => `https://${$1}github.com/${$2}.git#commit=${$3}`], // These ones come from the npm registry // Note: /download/ is used by custom registries like Taobao [/^https?:\/\/[^/]+\/(?:[^/]+\/)*(?:@[^/]+\/)?([^/]+)\/(?:-|download)\/\1-[^/]+\.tgz(?:#|$)/, version => `npm:${version}`], // The GitHub package registry uses a different style of URLs [/^https:\/\/npm\.pkg\.github\.com\/download\/(?:@[^/]+)\/(?:[^/]+)\/(?:[^/]+)\/(?:[0-9a-f]+)$/, version => `npm:${version}`], // FontAwesome too; what is it with these registries that made them think using a different url pattern was a good idea? [/^https:\/\/npm\.fontawesome\.com\/(?:@[^/]+)\/([^/]+)\/-\/([^/]+)\/\1-\2.tgz(?:#|$)/, version => `npm:${version}`], // These ones come from the old Yarn offline mirror - we assume they came from npm [/^[^/]+\.tgz#[0-9a-f]+$/, version => `npm:${version}`], ]; class LegacyMigrationResolver { constructor() { this.resolutions = null; } async setup(project, { report }) { const lockfilePath = fslib_1.ppath.join(project.cwd, project.configuration.get(`lockfileFilename`)); // No need to enable it if the lockfile doesn't exist if (!fslib_1.xfs.existsSync(lockfilePath)) return; const content = await fslib_1.xfs.readFilePromise(lockfilePath, `utf8`); const parsed = parsers_1.parseSyml(content); // No need to enable it either if the lockfile is modern if (Object.prototype.hasOwnProperty.call(parsed, `__metadata`)) return; const resolutions = this.resolutions = new Map(); for (const key of Object.keys(parsed)) { let descriptor = structUtils.tryParseDescriptor(key); if (!descriptor) { report.reportWarning(MessageName_1.MessageName.YARN_IMPORT_FAILED, `Failed to parse the string "${key}" into a proper descriptor`); continue; } if (semver_1.default.validRange(descriptor.range)) descriptor = structUtils.makeDescriptor(descriptor, `npm:${descriptor.range}`); const { version, resolved } = parsed[key]; // Workspaces don't have the "resolved" key; we can skip them, as their // resolution will be recomputed when needed anyway if (!resolved) continue; let reference; for (const [pattern, matcher] of IMPORTED_PATTERNS) { const match = resolved.match(pattern); if (match) { reference = matcher(version, ...match); break; } } if (!reference) { report.reportWarning(MessageName_1.MessageName.YARN_IMPORT_FAILED, `${structUtils.prettyDescriptor(project.configuration, descriptor)}: Only some patterns can be imported from legacy lockfiles (not "${resolved}")`); continue; } const resolution = structUtils.makeLocator(descriptor, reference); resolutions.set(descriptor.descriptorHash, resolution); } } supportsDescriptor(descriptor, opts) { if (!this.resolutions) return false; return this.resolutions.has(descriptor.descriptorHash); } supportsLocator(locator, opts) { // This resolver only supports the descriptor -> locator part of the // resolution, not the locator -> package one. return false; } shouldPersistResolution(locator, opts) { throw new Error(`Assertion failed: This resolver doesn't support resolving locators to packages`); } bindDescriptor(descriptor, fromLocator, opts) { return descriptor; } getResolutionDependencies(descriptor, opts) { return []; } async getCandidates(descriptor, dependencies, opts) { if (!this.resolutions) throw new Error(`Assertion failed: The resolution store should have been setup`); const resolution = this.resolutions.get(descriptor.descriptorHash); if (!resolution) throw new Error(`Assertion failed: The resolution should have been registered`); return [resolution]; } async getSatisfying(descriptor, references, opts) { return null; } async resolve(locator, opts) { throw new Error(`Assertion failed: This resolver doesn't support resolving locators to packages`); } } exports.LegacyMigrationResolver = LegacyMigrationResolver; /***/ }), /***/ 60613: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LightReport = void 0; const tslib_1 = __webpack_require__(70655); const Report_1 = __webpack_require__(50334); const StreamReport_1 = __webpack_require__(73759); const formatUtils = tslib_1.__importStar(__webpack_require__(23821)); class LightReport extends Report_1.Report { constructor({ configuration, stdout, suggestInstall = true }) { super(); this.errorCount = 0; formatUtils.addLogFilterSupport(this, { configuration }); this.configuration = configuration; this.stdout = stdout; this.suggestInstall = suggestInstall; } static async start(opts, cb) { const report = new this(opts); try { await cb(report); } catch (error) { report.reportExceptionOnce(error); } finally { await report.finalize(); } return report; } hasErrors() { return this.errorCount > 0; } exitCode() { return this.hasErrors() ? 1 : 0; } reportCacheHit(locator) { } reportCacheMiss(locator) { } startTimerSync(what, opts, cb) { const realCb = typeof opts === `function` ? opts : cb; return realCb(); } async startTimerPromise(what, opts, cb) { const realCb = typeof opts === `function` ? opts : cb; return await realCb(); } async startCacheReport(cb) { return await cb(); } reportSeparator() { } reportInfo(name, text) { } reportWarning(name, text) { } reportError(name, text) { this.errorCount += 1; this.stdout.write(`${formatUtils.pretty(this.configuration, `➤`, `redBright`)} ${this.formatNameWithHyperlink(name)}: ${text}\n`); } reportProgress(progress) { const promise = Promise.resolve().then(async () => { // eslint-disable-next-line no-empty-pattern for await (const {} of progress) { // No need to do anything; we just want to consume the progress events } }); const stop = () => { // Nothing to stop }; return { ...promise, stop }; } reportJson(data) { // Just ignore the json output } async finalize() { if (this.errorCount > 0) { this.stdout.write(`${formatUtils.pretty(this.configuration, `➤`, `redBright`)} Errors happened when preparing the environment required to run this command.\n`); if (this.suggestInstall) { this.stdout.write(`${formatUtils.pretty(this.configuration, `➤`, `redBright`)} This might be caused by packages being missing from the lockfile, in which case running "yarn install" might help.\n`); } } } formatNameWithHyperlink(name) { return StreamReport_1.formatNameWithHyperlink(name, { configuration: this.configuration, json: false, }); } } exports.LightReport = LightReport; /***/ }), /***/ 59909: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LockfileResolver = void 0; const tslib_1 = __webpack_require__(70655); const structUtils = tslib_1.__importStar(__webpack_require__(34103)); class LockfileResolver { supportsDescriptor(descriptor, opts) { const resolution = opts.project.storedResolutions.get(descriptor.descriptorHash); if (resolution) return true; // If the descriptor matches a package that's already been used, we can just use it even if we never resolved the range before // Ex: foo depends on bar@^1.0.0 that we resolved to foo@1.1.0, then we add a package qux that depends on foo@1.1.0 (without the caret) if (opts.project.originalPackages.has(structUtils.convertDescriptorToLocator(descriptor).locatorHash)) return true; return false; } supportsLocator(locator, opts) { if (opts.project.originalPackages.has(locator.locatorHash)) return true; return false; } shouldPersistResolution(locator, opts) { throw new Error(`The shouldPersistResolution method shouldn't be called on the lockfile resolver, which would always answer yes`); } bindDescriptor(descriptor, fromLocator, opts) { return descriptor; } getResolutionDependencies(descriptor, opts) { return []; } async getCandidates(descriptor, dependencies, opts) { let pkg = opts.project.originalPackages.get(structUtils.convertDescriptorToLocator(descriptor).locatorHash); if (pkg) return [pkg]; const resolution = opts.project.storedResolutions.get(descriptor.descriptorHash); if (!resolution) throw new Error(`Expected the resolution to have been successful - resolution not found`); pkg = opts.project.originalPackages.get(resolution); if (!pkg) throw new Error(`Expected the resolution to have been successful - package not found`); return [pkg]; } async getSatisfying(descriptor, references, opts) { return null; } async resolve(locator, opts) { const pkg = opts.project.originalPackages.get(locator.locatorHash); if (!pkg) throw new Error(`The lockfile resolver isn't meant to resolve packages - they should already have been stored into a cache`); return pkg; } } exports.LockfileResolver = LockfileResolver; /***/ }), /***/ 11658: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Manifest = void 0; const tslib_1 = __webpack_require__(70655); const fslib_1 = __webpack_require__(91794); const parsers_1 = __webpack_require__(21717); const semver_1 = tslib_1.__importDefault(__webpack_require__(74451)); const miscUtils = tslib_1.__importStar(__webpack_require__(63111)); const semverUtils = tslib_1.__importStar(__webpack_require__(51201)); const structUtils = tslib_1.__importStar(__webpack_require__(34103)); class Manifest { constructor() { this.indent = ` `; this.name = null; this.version = null; this.os = null; this.cpu = null; this.type = null; this["private"] = false; this.license = null; this.main = null; this.module = null; this.browser = null; this.languageName = null; this.bin = new Map(); this.scripts = new Map(); this.dependencies = new Map(); this.devDependencies = new Map(); this.peerDependencies = new Map(); this.workspaceDefinitions = []; this.dependenciesMeta = new Map(); this.peerDependenciesMeta = new Map(); this.resolutions = []; this.files = null; this.publishConfig = null; this.installConfig = null; this.preferUnplugged = null; this.raw = {}; /** * errors found in the raw manifest while loading */ this.errors = []; } static async tryFind(path, { baseFs = new fslib_1.NodeFS() } = {}) { const manifestPath = fslib_1.ppath.join(path, `package.json`); if (!await baseFs.existsPromise(manifestPath)) return null; return await Manifest.fromFile(manifestPath, { baseFs }); } static async find(path, { baseFs } = {}) { const manifest = await Manifest.tryFind(path, { baseFs }); if (manifest === null) throw new Error(`Manifest not found`); return manifest; } static async fromFile(path, { baseFs = new fslib_1.NodeFS() } = {}) { const manifest = new Manifest(); await manifest.loadFile(path, { baseFs }); return manifest; } static fromText(text) { const manifest = new Manifest(); manifest.loadFromText(text); return manifest; } static isManifestFieldCompatible(rules, actual) { if (rules === null) return true; let isNotOnAllowlist = true; let isOnDenylist = false; for (const rule of rules) { if (rule[0] === `!`) { isOnDenylist = true; if (actual === rule.slice(1)) { return false; } } else { isNotOnAllowlist = false; if (rule === actual) { return true; } } } // Denylists with allowlisted items should be treated as allowlists for `os` and `cpu` in `package.json` return isOnDenylist && isNotOnAllowlist; } loadFromText(text) { let data; try { data = JSON.parse(stripBOM(text) || `{}`); } catch (error) { error.message += ` (when parsing ${text})`; throw error; } this.load(data); this.indent = getIndent(text); } async loadFile(path, { baseFs = new fslib_1.NodeFS() }) { const content = await baseFs.readFilePromise(path, `utf8`); let data; try { data = JSON.parse(stripBOM(content) || `{}`); } catch (error) { error.message += ` (when parsing ${path})`; throw error; } this.load(data); this.indent = getIndent(content); } load(data, { yamlCompatibilityMode = false } = {}) { if (typeof data !== `object` || data === null) throw new Error(`Utterly invalid manifest data (${data})`); this.raw = data; const errors = []; if (typeof data.name === `string`) { try { this.name = structUtils.parseIdent(data.name); } catch (error) { errors.push(new Error(`Parsing failed for the 'name' field`)); } } if (typeof data.version === `string`) this.version = data.version; if (Array.isArray(data.os)) { const os = []; this.os = os; for (const item of data.os) { if (typeof item !== `string`) { errors.push(new Error(`Parsing failed for the 'os' field`)); } else { os.push(item); } } } if (Array.isArray(data.cpu)) { const cpu = []; this.cpu = cpu; for (const item of data.cpu) { if (typeof item !== `string`) { errors.push(new Error(`Parsing failed for the 'cpu' field`)); } else { cpu.push(item); } } } if (typeof data.type === `string`) this.type = data.type; if (typeof data.private === `boolean`) this.private = data.private; if (typeof data.license === `string`) this.license = data.license; if (typeof data.languageName === `string`) this.languageName = data.languageName; if (typeof data.main === `string`) this.main = normalizeSlashes(data.main); if (typeof data.module === `string`) this.module = normalizeSlashes(data.module); if (data.browser != null) { if (typeof data.browser === `string`) { this.browser = normalizeSlashes(data.browser); } else { this.browser = new Map(); for (const [key, value] of Object.entries(data.browser)) { this.browser.set(normalizeSlashes(key), typeof value === `string` ? normalizeSlashes(value) : value); } } } if (typeof data.bin === `string`) { if (this.name !== null) { this.bin = new Map([[this.name.name, normalizeSlashes(data.bin)]]); } else { errors.push(new Error(`String bin field, but no attached package name`)); } } else if (typeof data.bin === `object` && data.bin !== null) { for (const [key, value] of Object.entries(data.bin)) { if (typeof value !== `string`) { errors.push(new Error(`Invalid bin definition for '${key}'`)); continue; } this.bin.set(key, normalizeSlashes(value)); } } if (typeof data.scripts === `object` && data.scripts !== null) { for (const [key, value] of Object.entries(data.scripts)) { if (typeof value !== `string`) { errors.push(new Error(`Invalid script definition for '${key}'`)); continue; } this.scripts.set(key, value); } } if (typeof data.dependencies === `object` && data.dependencies !== null) { for (const [name, range] of Object.entries(data.dependencies)) { if (typeof range !== `string`) { errors.push(new Error(`Invalid dependency range for '${name}'`)); continue; } let ident; try { ident = structUtils.parseIdent(name); } catch (error) { errors.push(new Error(`Parsing failed for the dependency name '${name}'`)); continue; } const descriptor = structUtils.makeDescriptor(ident, range); this.dependencies.set(descriptor.identHash, descriptor); } } if (typeof data.devDependencies === `object` && data.devDependencies !== null) { for (const [name, range] of Object.entries(data.devDependencies)) { if (typeof range !== `string`) { errors.push(new Error(`Invalid dependency range for '${name}'`)); continue; } let ident; try { ident = structUtils.parseIdent(name); } catch (error) { errors.push(new Error(`Parsing failed for the dependency name '${name}'`)); continue; } const descriptor = structUtils.makeDescriptor(ident, range); this.devDependencies.set(descriptor.identHash, descriptor); } } if (typeof data.peerDependencies === `object` && data.peerDependencies !== null) { for (let [name, range] of Object.entries(data.peerDependencies)) { let ident; try { ident = structUtils.parseIdent(name); } catch (error) { errors.push(new Error(`Parsing failed for the dependency name '${name}'`)); continue; } if (typeof range !== `string` || !semverUtils.validRange(range)) { errors.push(new Error(`Invalid dependency range for '${name}'`)); range = `*`; } const descriptor = structUtils.makeDescriptor(ident, range); this.peerDependencies.set(descriptor.identHash, descriptor); } } if (typeof data.workspaces === `object` && data.workspaces.nohoist) errors.push(new Error(`'nohoist' is deprecated, please use 'installConfig.hoistingLimits' instead`)); const workspaces = Array.isArray(data.workspaces) ? data.workspaces : typeof data.workspaces === `object` && data.workspaces !== null && Array.isArray(data.workspaces.packages) ? data.workspaces.packages : []; for (const entry of workspaces) { if (typeof entry !== `string`) { errors.push(new Error(`Invalid workspace definition for '${entry}'`)); continue; } this.workspaceDefinitions.push({ pattern: entry, }); } if (typeof data.dependenciesMeta === `object` && data.dependenciesMeta !== null) { for (const [pattern, meta] of Object.entries(data.dependenciesMeta)) { if (typeof meta !== `object` || meta === null) { errors.push(new Error(`Invalid meta field for '${pattern}`)); continue; } const descriptor = structUtils.parseDescriptor(pattern); const dependencyMeta = this.ensureDependencyMeta(descriptor); const built = tryParseOptionalBoolean(meta.built, { yamlCompatibilityMode }); if (built === null) { errors.push(new Error(`Invalid built meta field for '${pattern}'`)); continue; } const optional = tryParseOptionalBoolean(meta.optional, { yamlCompatibilityMode }); if (optional === null) { errors.push(new Error(`Invalid optional meta field for '${pattern}'`)); continue; } const unplugged = tryParseOptionalBoolean(meta.unplugged, { yamlCompatibilityMode }); if (unplugged === null) { errors.push(new Error(`Invalid unplugged meta field for '${pattern}'`)); continue; } Object.assign(dependencyMeta, { built, optional, unplugged }); } } if (typeof data.peerDependenciesMeta === `object` && data.peerDependenciesMeta !== null) { for (const [pattern, meta] of Object.entries(data.peerDependenciesMeta)) { if (typeof meta !== `object` || meta === null) { errors.push(new Error(`Invalid meta field for '${pattern}'`)); continue; } const descriptor = structUtils.parseDescriptor(pattern); const peerDependencyMeta = this.ensurePeerDependencyMeta(descriptor); const optional = tryParseOptionalBoolean(meta.optional, { yamlCompatibilityMode }); if (optional === null) { errors.push(new Error(`Invalid optional meta field for '${pattern}'`)); continue; } Object.assign(peerDependencyMeta, { optional }); } } if (typeof data.resolutions === `object` && data.resolutions !== null) { for (const [pattern, reference] of Object.entries(data.resolutions)) { if (typeof reference !== `string`) { errors.push(new Error(`Invalid resolution entry for '${pattern}'`)); continue; } try { this.resolutions.push({ pattern: parsers_1.parseResolution(pattern), reference }); } catch (error) { errors.push(error); continue; } } } if (Array.isArray(data.files)) { this.files = new Set(); for (const filename of data.files) { if (typeof filename !== `string`) { errors.push(new Error(`Invalid files entry for '${filename}'`)); continue; } this.files.add(filename); } } if (typeof data.publishConfig === `object` && data.publishConfig !== null) { this.publishConfig = {}; if (typeof data.publishConfig.access === `string`) this.publishConfig.access = data.publishConfig.access; if (typeof data.publishConfig.main === `string`) this.publishConfig.main = normalizeSlashes(data.publishConfig.main); if (typeof data.publishConfig.module === `string`) this.publishConfig.module = normalizeSlashes(data.publishConfig.module); if (data.publishConfig.browser != null) { if (typeof data.publishConfig.browser === `string`) { this.publishConfig.browser = normalizeSlashes(data.publishConfig.browser); } else { this.publishConfig.browser = new Map(); for (const [key, value] of Object.entries(data.publishConfig.browser)) { this.publishConfig.browser.set(normalizeSlashes(key), typeof value === `string` ? normalizeSlashes(value) : value); } } } if (typeof data.publishConfig.registry === `string`) this.publishConfig.registry = data.publishConfig.registry; if (typeof data.publishConfig.bin === `string`) { if (this.name !== null) { this.publishConfig.bin = new Map([[this.name.name, normalizeSlashes(data.publishConfig.bin)]]); } else { errors.push(new Error(`String bin field, but no attached package name`)); } } else if (typeof data.publishConfig.bin === `object` && data.publishConfig.bin !== null) { this.publishConfig.bin = new Map(); for (const [key, value] of Object.entries(data.publishConfig.bin)) { if (typeof value !== `string`) { errors.push(new Error(`Invalid bin definition for '${key}'`)); continue; } this.publishConfig.bin.set(key, normalizeSlashes(value)); } } if (Array.isArray(data.publishConfig.executableFiles)) { this.publishConfig.executableFiles = new Set(); for (const value of data.publishConfig.executableFiles) { if (typeof value !== `string`) { errors.push(new Error(`Invalid executable file definition`)); continue; } this.publishConfig.executableFiles.add(normalizeSlashes(value)); } } } if (typeof data.installConfig === `object` && data.installConfig !== null) { this.installConfig = {}; for (const key of Object.keys(data.installConfig)) { if (key === `hoistingLimits`) { if (typeof data.installConfig.hoistingLimits === `string`) { this.installConfig.hoistingLimits = data.installConfig.hoistingLimits; } else { errors.push(new Error(`Invalid hoisting limits definition`)); } } else { errors.push(new Error(`Unrecognized installConfig key: ${key}`)); } } } // We treat optional dependencies after both the regular dependency field // and the dependenciesMeta field have been generated (because we will // override them) if (typeof data.optionalDependencies === `object` && data.optionalDependencies !== null) { for (const [name, range] of Object.entries(data.optionalDependencies)) { if (typeof range !== `string`) { errors.push(new Error(`Invalid dependency range for '${name}'`)); continue; } let ident; try { ident = structUtils.parseIdent(name); } catch (error) { errors.push(new Error(`Parsing failed for the dependency name '${name}'`)); continue; } // Note that we store the optional dependencies in the same store as // the one that keep the regular dependencies, because they're // effectively the same (the only difference is that optional // dependencies have an extra field set in dependenciesMeta). const realDescriptor = structUtils.makeDescriptor(ident, range); this.dependencies.set(realDescriptor.identHash, realDescriptor); const identDescriptor = structUtils.makeDescriptor(ident, `unknown`); const dependencyMeta = this.ensureDependencyMeta(identDescriptor); Object.assign(dependencyMeta, { optional: true }); } } if (typeof data.preferUnplugged === `boolean`) this.preferUnplugged = data.preferUnplugged; this.errors = errors; } getForScope(type) { switch (type) { case `dependencies`: return this.dependencies; case `devDependencies`: return this.devDependencies; case `peerDependencies`: return this.peerDependencies; default: { throw new Error(`Unsupported value ("${type}")`); } } } hasConsumerDependency(ident) { if (this.dependencies.has(ident.identHash)) return true; if (this.peerDependencies.has(ident.identHash)) return true; return false; } hasHardDependency(ident) { if (this.dependencies.has(ident.identHash)) return true; if (this.devDependencies.has(ident.identHash)) return true; return false; } hasSoftDependency(ident) { if (this.peerDependencies.has(ident.identHash)) return true; return false; } hasDependency(ident) { if (this.hasHardDependency(ident)) return true; if (this.hasSoftDependency(ident)) return true; return false; } isCompatibleWithOS(os) { return Manifest.isManifestFieldCompatible(this.os, os); } isCompatibleWithCPU(cpu) { return Manifest.isManifestFieldCompatible(this.cpu, cpu); } ensureDependencyMeta(descriptor) { if (descriptor.range !== `unknown` && !semver_1.default.valid(descriptor.range)) throw new Error(`Invalid meta field range for '${structUtils.stringifyDescriptor(descriptor)}'`); const identString = structUtils.stringifyIdent(descriptor); const range = descriptor.range !== `unknown` ? descriptor.range : null; let dependencyMetaSet = this.dependenciesMeta.get(identString); if (!dependencyMetaSet) this.dependenciesMeta.set(identString, dependencyMetaSet = new Map()); let dependencyMeta = dependencyMetaSet.get(range); if (!dependencyMeta) dependencyMetaSet.set(range, dependencyMeta = {}); return dependencyMeta; } ensurePeerDependencyMeta(descriptor) { if (descriptor.range !== `unknown`) throw new Error(`Invalid meta field range for '${structUtils.stringifyDescriptor(descriptor)}'`); const identString = structUtils.stringifyIdent(descriptor); let peerDependencyMeta = this.peerDependenciesMeta.get(identString); if (!peerDependencyMeta) this.peerDependenciesMeta.set(identString, peerDependencyMeta = {}); return peerDependencyMeta; } setRawField(name, value, { after = [] } = {}) { const afterSet = new Set(after.filter(key => { return Object.prototype.hasOwnProperty.call(this.raw, key); })); if (afterSet.size === 0 || Object.prototype.hasOwnProperty.call(this.raw, name)) { this.raw[name] = value; } else { const oldRaw = this.raw; const newRaw = this.raw = {}; let inserted = false; for (const key of Object.keys(oldRaw)) { newRaw[key] = oldRaw[key]; if (!inserted) { afterSet.delete(key); if (afterSet.size === 0) { newRaw[name] = value; inserted = true; } } } } } exportTo(data, { compatibilityMode = true } = {}) { // Note that we even set the fields that we re-set later; it // allows us to preserve the key ordering Object.assign(data, this.raw); if (this.name !== null) data.name = structUtils.stringifyIdent(this.name); else delete data.name; if (this.version !== null) data.version = this.version; else delete data.version; if (this.os !== null) data.os = this.os; else delete data.os; if (this.cpu !== null) data.cpu = this.cpu; else delete data.cpu; if (this.type !== null) data.type = this.type; else delete data.type; if (this.private) data.private = true; else delete data.private; if (this.license !== null) data.license = this.license; else delete data.license; if (this.languageName !== null) data.languageName = this.languageName; else delete data.languageName; if (this.main !== null) data.main = this.main; else delete data.main; if (this.module !== null) data.module = this.module; else delete data.module; if (this.browser !== null) { const browser = this.browser; if (typeof browser === `string`) { data.browser = browser; } else if (browser instanceof Map) { data.browser = Object.assign({}, ...Array.from(browser.keys()).sort().map(name => { return { [name]: browser.get(name) }; })); } } else { delete data.browser; } if (this.bin.size === 1 && this.name !== null && this.bin.has(this.name.name)) { data.bin = this.bin.get(this.name.name); } else if (this.bin.size > 0) { data.bin = Object.assign({}, ...Array.from(this.bin.keys()).sort().map(name => { return { [name]: this.bin.get(name) }; })); } else { delete data.bin; } if (this.workspaceDefinitions.length > 0) { if (this.raw.workspaces && !Array.isArray(this.raw.workspaces)) { data.workspaces = { ...this.raw.workspaces, packages: this.workspaceDefinitions.map(({ pattern }) => pattern) }; } else { data.workspaces = this.workspaceDefinitions.map(({ pattern }) => pattern); } } else if (this.raw.workspaces && !Array.isArray(this.raw.workspaces) && Object.keys(this.raw.workspaces).length > 0) { data.workspaces = this.raw.workspaces; } else { delete data.workspaces; } const regularDependencies = []; const optionalDependencies = []; for (const dependency of this.dependencies.values()) { const dependencyMetaSet = this.dependenciesMeta.get(structUtils.stringifyIdent(dependency)); let isOptionallyBuilt = false; if (compatibilityMode) { if (dependencyMetaSet) { const meta = dependencyMetaSet.get(null); if (meta && meta.optional) { isOptionallyBuilt = true; } } } if (isOptionallyBuilt) { optionalDependencies.push(dependency); } else { regularDependencies.push(dependency); } } if (regularDependencies.length > 0) { data.dependencies = Object.assign({}, ...structUtils.sortDescriptors(regularDependencies).map(dependency => { return { [structUtils.stringifyIdent(dependency)]: dependency.range }; })); } else { delete data.dependencies; } if (optionalDependencies.length > 0) { data.optionalDependencies = Object.assign({}, ...structUtils.sortDescriptors(optionalDependencies).map(dependency => { return { [structUtils.stringifyIdent(dependency)]: dependency.range }; })); } else { delete data.optionalDependencies; } if (this.devDependencies.size > 0) { data.devDependencies = Object.assign({}, ...structUtils.sortDescriptors(this.devDependencies.values()).map(dependency => { return { [structUtils.stringifyIdent(dependency)]: dependency.range }; })); } else { delete data.devDependencies; } if (this.peerDependencies.size > 0) { data.peerDependencies = Object.assign({}, ...structUtils.sortDescriptors(this.peerDependencies.values()).map(dependency => { return { [structUtils.stringifyIdent(dependency)]: dependency.range }; })); } else { delete data.peerDependencies; } data.dependenciesMeta = {}; for (const [identString, dependencyMetaSet] of miscUtils.sortMap(this.dependenciesMeta.entries(), ([identString, dependencyMetaSet]) => identString)) { for (const [range, meta] of miscUtils.sortMap(dependencyMetaSet.entries(), ([range, meta]) => range !== null ? `0${range}` : `1`)) { const key = range !== null ? structUtils.stringifyDescriptor(structUtils.makeDescriptor(structUtils.parseIdent(identString), range)) : identString; const metaCopy = { ...meta }; if (compatibilityMode && range === null) delete metaCopy.optional; if (Object.keys(metaCopy).length === 0) continue; data.dependenciesMeta[key] = metaCopy; } } if (Object.keys(data.dependenciesMeta).length === 0) delete data.dependenciesMeta; if (this.peerDependenciesMeta.size > 0) { data.peerDependenciesMeta = Object.assign({}, ...miscUtils.sortMap(this.peerDependenciesMeta.entries(), ([identString, meta]) => identString).map(([identString, meta]) => { return { [identString]: meta }; })); } else { delete data.peerDependenciesMeta; } if (this.resolutions.length > 0) { data.resolutions = Object.assign({}, ...this.resolutions.map(({ pattern, reference }) => { return { [parsers_1.stringifyResolution(pattern)]: reference }; })); } else { delete data.resolutions; } if (this.files !== null) data.files = Array.from(this.files); else delete data.files; if (this.preferUnplugged !== null) data.preferUnplugged = this.preferUnplugged; else delete data.preferUnplugged; return data; } } exports.Manifest = Manifest; Manifest.fileName = `package.json`; Manifest.allDependencies = [`dependencies`, `devDependencies`, `peerDependencies`]; Manifest.hardDependencies = [`dependencies`, `devDependencies`]; function getIndent(content) { const indentMatch = content.match(/^[ \t]+/m); if (indentMatch) { return indentMatch[0]; } else { return ` `; } } function stripBOM(content) { if (content.charCodeAt(0) === 0xFEFF) { return content.slice(1); } else { return content; } } function normalizeSlashes(str) { return str.replace(/\\/g, `/`); } function tryParseOptionalBoolean(value, { yamlCompatibilityMode }) { if (yamlCompatibilityMode) return miscUtils.tryParseOptionalBoolean(value); if (typeof value === `undefined` || typeof value === `boolean`) return value; return null; } /***/ }), /***/ 62755: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.stringifyMessageName = exports.MessageName = void 0; // The values in this enum should never be reassigned, even if some are removed // over time (it would mess up the search results, which are the whole point of // having this system) var MessageName; (function (MessageName) { MessageName[MessageName["UNNAMED"] = 0] = "UNNAMED"; MessageName[MessageName["EXCEPTION"] = 1] = "EXCEPTION"; MessageName[MessageName["MISSING_PEER_DEPENDENCY"] = 2] = "MISSING_PEER_DEPENDENCY"; MessageName[MessageName["CYCLIC_DEPENDENCIES"] = 3] = "CYCLIC_DEPENDENCIES"; MessageName[MessageName["DISABLED_BUILD_SCRIPTS"] = 4] = "DISABLED_BUILD_SCRIPTS"; MessageName[MessageName["BUILD_DISABLED"] = 5] = "BUILD_DISABLED"; MessageName[MessageName["SOFT_LINK_BUILD"] = 6] = "SOFT_LINK_BUILD"; MessageName[MessageName["MUST_BUILD"] = 7] = "MUST_BUILD"; MessageName[MessageName["MUST_REBUILD"] = 8] = "MUST_REBUILD"; MessageName[MessageName["BUILD_FAILED"] = 9] = "BUILD_FAILED"; MessageName[MessageName["RESOLVER_NOT_FOUND"] = 10] = "RESOLVER_NOT_FOUND"; MessageName[MessageName["FETCHER_NOT_FOUND"] = 11] = "FETCHER_NOT_FOUND"; MessageName[MessageName["LINKER_NOT_FOUND"] = 12] = "LINKER_NOT_FOUND"; MessageName[MessageName["FETCH_NOT_CACHED"] = 13] = "FETCH_NOT_CACHED"; MessageName[MessageName["YARN_IMPORT_FAILED"] = 14] = "YARN_IMPORT_FAILED"; MessageName[MessageName["REMOTE_INVALID"] = 15] = "REMOTE_INVALID"; MessageName[MessageName["REMOTE_NOT_FOUND"] = 16] = "REMOTE_NOT_FOUND"; MessageName[MessageName["RESOLUTION_PACK"] = 17] = "RESOLUTION_PACK"; MessageName[MessageName["CACHE_CHECKSUM_MISMATCH"] = 18] = "CACHE_CHECKSUM_MISMATCH"; MessageName[MessageName["UNUSED_CACHE_ENTRY"] = 19] = "UNUSED_CACHE_ENTRY"; MessageName[MessageName["MISSING_LOCKFILE_ENTRY"] = 20] = "MISSING_LOCKFILE_ENTRY"; MessageName[MessageName["WORKSPACE_NOT_FOUND"] = 21] = "WORKSPACE_NOT_FOUND"; MessageName[MessageName["TOO_MANY_MATCHING_WORKSPACES"] = 22] = "TOO_MANY_MATCHING_WORKSPACES"; MessageName[MessageName["CONSTRAINTS_MISSING_DEPENDENCY"] = 23] = "CONSTRAINTS_MISSING_DEPENDENCY"; MessageName[MessageName["CONSTRAINTS_INCOMPATIBLE_DEPENDENCY"] = 24] = "CONSTRAINTS_INCOMPATIBLE_DEPENDENCY"; MessageName[MessageName["CONSTRAINTS_EXTRANEOUS_DEPENDENCY"] = 25] = "CONSTRAINTS_EXTRANEOUS_DEPENDENCY"; MessageName[MessageName["CONSTRAINTS_INVALID_DEPENDENCY"] = 26] = "CONSTRAINTS_INVALID_DEPENDENCY"; MessageName[MessageName["CANT_SUGGEST_RESOLUTIONS"] = 27] = "CANT_SUGGEST_RESOLUTIONS"; MessageName[MessageName["FROZEN_LOCKFILE_EXCEPTION"] = 28] = "FROZEN_LOCKFILE_EXCEPTION"; MessageName[MessageName["CROSS_DRIVE_VIRTUAL_LOCAL"] = 29] = "CROSS_DRIVE_VIRTUAL_LOCAL"; MessageName[MessageName["FETCH_FAILED"] = 30] = "FETCH_FAILED"; MessageName[MessageName["DANGEROUS_NODE_MODULES"] = 31] = "DANGEROUS_NODE_MODULES"; MessageName[MessageName["NODE_GYP_INJECTED"] = 32] = "NODE_GYP_INJECTED"; MessageName[MessageName["AUTHENTICATION_NOT_FOUND"] = 33] = "AUTHENTICATION_NOT_FOUND"; MessageName[MessageName["INVALID_CONFIGURATION_KEY"] = 34] = "INVALID_CONFIGURATION_KEY"; MessageName[MessageName["NETWORK_ERROR"] = 35] = "NETWORK_ERROR"; MessageName[MessageName["LIFECYCLE_SCRIPT"] = 36] = "LIFECYCLE_SCRIPT"; MessageName[MessageName["CONSTRAINTS_MISSING_FIELD"] = 37] = "CONSTRAINTS_MISSING_FIELD"; MessageName[MessageName["CONSTRAINTS_INCOMPATIBLE_FIELD"] = 38] = "CONSTRAINTS_INCOMPATIBLE_FIELD"; MessageName[MessageName["CONSTRAINTS_EXTRANEOUS_FIELD"] = 39] = "CONSTRAINTS_EXTRANEOUS_FIELD"; MessageName[MessageName["CONSTRAINTS_INVALID_FIELD"] = 40] = "CONSTRAINTS_INVALID_FIELD"; MessageName[MessageName["AUTHENTICATION_INVALID"] = 41] = "AUTHENTICATION_INVALID"; MessageName[MessageName["PROLOG_UNKNOWN_ERROR"] = 42] = "PROLOG_UNKNOWN_ERROR"; MessageName[MessageName["PROLOG_SYNTAX_ERROR"] = 43] = "PROLOG_SYNTAX_ERROR"; MessageName[MessageName["PROLOG_EXISTENCE_ERROR"] = 44] = "PROLOG_EXISTENCE_ERROR"; MessageName[MessageName["STACK_OVERFLOW_RESOLUTION"] = 45] = "STACK_OVERFLOW_RESOLUTION"; MessageName[MessageName["AUTOMERGE_FAILED_TO_PARSE"] = 46] = "AUTOMERGE_FAILED_TO_PARSE"; MessageName[MessageName["AUTOMERGE_IMMUTABLE"] = 47] = "AUTOMERGE_IMMUTABLE"; MessageName[MessageName["AUTOMERGE_SUCCESS"] = 48] = "AUTOMERGE_SUCCESS"; MessageName[MessageName["AUTOMERGE_REQUIRED"] = 49] = "AUTOMERGE_REQUIRED"; MessageName[MessageName["DEPRECATED_CLI_SETTINGS"] = 50] = "DEPRECATED_CLI_SETTINGS"; MessageName[MessageName["PLUGIN_NAME_NOT_FOUND"] = 51] = "PLUGIN_NAME_NOT_FOUND"; MessageName[MessageName["INVALID_PLUGIN_REFERENCE"] = 52] = "INVALID_PLUGIN_REFERENCE"; MessageName[MessageName["CONSTRAINTS_AMBIGUITY"] = 53] = "CONSTRAINTS_AMBIGUITY"; MessageName[MessageName["CACHE_OUTSIDE_PROJECT"] = 54] = "CACHE_OUTSIDE_PROJECT"; MessageName[MessageName["IMMUTABLE_INSTALL"] = 55] = "IMMUTABLE_INSTALL"; MessageName[MessageName["IMMUTABLE_CACHE"] = 56] = "IMMUTABLE_CACHE"; MessageName[MessageName["INVALID_MANIFEST"] = 57] = "INVALID_MANIFEST"; MessageName[MessageName["PACKAGE_PREPARATION_FAILED"] = 58] = "PACKAGE_PREPARATION_FAILED"; MessageName[MessageName["INVALID_RANGE_PEER_DEPENDENCY"] = 59] = "INVALID_RANGE_PEER_DEPENDENCY"; MessageName[MessageName["INCOMPATIBLE_PEER_DEPENDENCY"] = 60] = "INCOMPATIBLE_PEER_DEPENDENCY"; MessageName[MessageName["DEPRECATED_PACKAGE"] = 61] = "DEPRECATED_PACKAGE"; MessageName[MessageName["INCOMPATIBLE_OS"] = 62] = "INCOMPATIBLE_OS"; MessageName[MessageName["INCOMPATIBLE_CPU"] = 63] = "INCOMPATIBLE_CPU"; MessageName[MessageName["FROZEN_ARTIFACT_EXCEPTION"] = 64] = "FROZEN_ARTIFACT_EXCEPTION"; MessageName[MessageName["TELEMETRY_NOTICE"] = 65] = "TELEMETRY_NOTICE"; MessageName[MessageName["PATCH_HUNK_FAILED"] = 66] = "PATCH_HUNK_FAILED"; MessageName[MessageName["INVALID_CONFIGURATION_VALUE"] = 67] = "INVALID_CONFIGURATION_VALUE"; MessageName[MessageName["UNUSED_PACKAGE_EXTENSION"] = 68] = "UNUSED_PACKAGE_EXTENSION"; MessageName[MessageName["REDUNDANT_PACKAGE_EXTENSION"] = 69] = "REDUNDANT_PACKAGE_EXTENSION"; })(MessageName = exports.MessageName || (exports.MessageName = {})); function stringifyMessageName(name) { return `YN${name.toString(10).padStart(4, `0`)}`; } exports.stringifyMessageName = stringifyMessageName; /***/ }), /***/ 74441: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MultiFetcher = void 0; const tslib_1 = __webpack_require__(70655); const MessageName_1 = __webpack_require__(62755); const Report_1 = __webpack_require__(50334); const structUtils = tslib_1.__importStar(__webpack_require__(34103)); class MultiFetcher { constructor(fetchers) { this.fetchers = fetchers; } supports(locator, opts) { if (!this.tryFetcher(locator, opts)) return false; return true; } getLocalPath(locator, opts) { const fetcher = this.getFetcher(locator, opts); return fetcher.getLocalPath(locator, opts); } async fetch(locator, opts) { const fetcher = this.getFetcher(locator, opts); return await fetcher.fetch(locator, opts); } tryFetcher(locator, opts) { const fetcher = this.fetchers.find(fetcher => fetcher.supports(locator, opts)); if (!fetcher) return null; return fetcher; } getFetcher(locator, opts) { const fetcher = this.fetchers.find(fetcher => fetcher.supports(locator, opts)); if (!fetcher) throw new Report_1.ReportError(MessageName_1.MessageName.FETCHER_NOT_FOUND, `${structUtils.prettyLocator(opts.project.configuration, locator)} isn't supported by any available fetcher`); return fetcher; } } exports.MultiFetcher = MultiFetcher; /***/ }), /***/ 54123: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MultiResolver = void 0; const tslib_1 = __webpack_require__(70655); const structUtils = tslib_1.__importStar(__webpack_require__(34103)); class MultiResolver { constructor(resolvers) { this.resolvers = resolvers.filter(resolver => resolver); } supportsDescriptor(descriptor, opts) { const resolver = this.tryResolverByDescriptor(descriptor, opts); return !!resolver; } supportsLocator(locator, opts) { const resolver = this.tryResolverByLocator(locator, opts); return !!resolver; } shouldPersistResolution(locator, opts) { const resolver = this.getResolverByLocator(locator, opts); return resolver.shouldPersistResolution(locator, opts); } bindDescriptor(descriptor, fromLocator, opts) { const resolver = this.getResolverByDescriptor(descriptor, opts); return resolver.bindDescriptor(descriptor, fromLocator, opts); } getResolutionDependencies(descriptor, opts) { const resolver = this.getResolverByDescriptor(descriptor, opts); return resolver.getResolutionDependencies(descriptor, opts); } async getCandidates(descriptor, dependencies, opts) { const resolver = this.getResolverByDescriptor(descriptor, opts); return await resolver.getCandidates(descriptor, dependencies, opts); } async getSatisfying(descriptor, references, opts) { const resolver = this.getResolverByDescriptor(descriptor, opts); return resolver.getSatisfying(descriptor, references, opts); } async resolve(locator, opts) { const resolver = this.getResolverByLocator(locator, opts); return await resolver.resolve(locator, opts); } tryResolverByDescriptor(descriptor, opts) { const resolver = this.resolvers.find(resolver => resolver.supportsDescriptor(descriptor, opts)); if (!resolver) return null; return resolver; } getResolverByDescriptor(descriptor, opts) { const resolver = this.resolvers.find(resolver => resolver.supportsDescriptor(descriptor, opts)); if (!resolver) throw new Error(`${structUtils.prettyDescriptor(opts.project.configuration, descriptor)} isn't supported by any available resolver`); return resolver; } tryResolverByLocator(locator, opts) { const resolver = this.resolvers.find(resolver => resolver.supportsLocator(locator, opts)); if (!resolver) return null; return resolver; } getResolverByLocator(locator, opts) { const resolver = this.resolvers.find(resolver => resolver.supportsLocator(locator, opts)); if (!resolver) throw new Error(`${structUtils.prettyLocator(opts.project.configuration, locator)} isn't supported by any available resolver`); return resolver; } } exports.MultiResolver = MultiResolver; /***/ }), /***/ 49015: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Project = void 0; const tslib_1 = __webpack_require__(70655); const fslib_1 = __webpack_require__(91794); const parsers_1 = __webpack_require__(21717); const clipanion_1 = __webpack_require__(87730); const crypto_1 = __webpack_require__(6113); const diff_1 = __webpack_require__(88507); const pick_1 = tslib_1.__importDefault(__webpack_require__(78718)); const p_limit_1 = tslib_1.__importDefault(__webpack_require__(93743)); const semver_1 = tslib_1.__importDefault(__webpack_require__(74451)); const util_1 = __webpack_require__(73837); const v8_1 = tslib_1.__importDefault(__webpack_require__(84655)); const zlib_1 = tslib_1.__importDefault(__webpack_require__(59796)); const Configuration_1 = __webpack_require__(62889); const Installer_1 = __webpack_require__(45006); const LegacyMigrationResolver_1 = __webpack_require__(48900); const LockfileResolver_1 = __webpack_require__(59909); const Manifest_1 = __webpack_require__(11658); const MessageName_1 = __webpack_require__(62755); const MultiResolver_1 = __webpack_require__(54123); const Report_1 = __webpack_require__(50334); const RunInstallPleaseResolver_1 = __webpack_require__(30460); const ThrowReport_1 = __webpack_require__(6059); const Workspace_1 = __webpack_require__(2234); const folderUtils_1 = __webpack_require__(13061); const formatUtils = tslib_1.__importStar(__webpack_require__(23821)); const hashUtils = tslib_1.__importStar(__webpack_require__(73279)); const miscUtils = tslib_1.__importStar(__webpack_require__(63111)); const scriptUtils = tslib_1.__importStar(__webpack_require__(50888)); const semverUtils = tslib_1.__importStar(__webpack_require__(51201)); const structUtils = tslib_1.__importStar(__webpack_require__(34103)); const types_1 = __webpack_require__(79588); const types_2 = __webpack_require__(79588); // When upgraded, the lockfile entries have to be resolved again (but the specific // versions are still pinned, no worry). Bump it when you change the fields within // the Package type; no more no less. const LOCKFILE_VERSION = 4; // Same thing but must be bumped when the members of the Project class changes (we // don't recommend our users to check-in this file, so it's fine to bump it even // between patch or minor releases). const INSTALL_STATE_VERSION = 1; const MULTIPLE_KEYS_REGEXP = / *, */g; const TRAILING_SLASH_REGEXP = /\/$/; const FETCHER_CONCURRENCY = 32; const gzip = util_1.promisify(zlib_1.default.gzip); const gunzip = util_1.promisify(zlib_1.default.gunzip); const INSTALL_STATE_FIELDS = { restoreInstallersCustomData: [ `installersCustomData`, ], restoreResolutions: [ `accessibleLocators`, `optionalBuilds`, `storedDescriptors`, `storedResolutions`, `storedPackages`, `lockFileChecksum`, ], }; class Project { constructor(projectCwd, { configuration }) { /** * Is meant to be populated by the consumer. Should the descriptor referenced * by the key be requested, the descriptor referenced in the value will be * resolved instead. The resolved data will then be used as final resolution * for the initial descriptor. * * Note that the lockfile will contain the second descriptor but not the * first one (meaning that if you remove the alias during a subsequent * install, it'll be lost and the real package will be resolved / installed). */ this.resolutionAliases = new Map(); this.workspaces = []; this.workspacesByCwd = new Map(); this.workspacesByIdent = new Map(); this.storedResolutions = new Map(); this.storedDescriptors = new Map(); this.storedPackages = new Map(); this.storedChecksums = new Map(); this.accessibleLocators = new Set(); this.originalPackages = new Map(); this.optionalBuilds = new Set(); /** * Populated by the `resolveEverything` method. * *Not* stored inside the install state. * * The map keys are 6 hexadecimal characters except the first one, always `p`. */ this.peerRequirements = new Map(); this.installersCustomData = new Map(); this.lockFileChecksum = null; this.configuration = configuration; this.cwd = projectCwd; } static async find(configuration, startingCwd) { var _a, _b, _c; if (!configuration.projectCwd) throw new clipanion_1.UsageError(`No project found in ${startingCwd}`); let packageCwd = configuration.projectCwd; let nextCwd = startingCwd; let currentCwd = null; while (currentCwd !== configuration.projectCwd) { currentCwd = nextCwd; if (fslib_1.xfs.existsSync(fslib_1.ppath.join(currentCwd, fslib_1.Filename.manifest))) { packageCwd = currentCwd; break; } nextCwd = fslib_1.ppath.dirname(currentCwd); } const project = new Project(configuration.projectCwd, { configuration }); (_a = Configuration_1.Configuration.telemetry) === null || _a === void 0 ? void 0 : _a.reportProject(project.cwd); await project.setupResolutions(); await project.setupWorkspaces(); (_b = Configuration_1.Configuration.telemetry) === null || _b === void 0 ? void 0 : _b.reportWorkspaceCount(project.workspaces.length); (_c = Configuration_1.Configuration.telemetry) === null || _c === void 0 ? void 0 : _c.reportDependencyCount(project.workspaces.reduce((sum, workspace) => sum + workspace.manifest.dependencies.size + workspace.manifest.devDependencies.size, 0)); // If we're in a workspace, no need to go any further to find which package we're in const workspace = project.tryWorkspaceByCwd(packageCwd); if (workspace) return { project, workspace, locator: workspace.anchoredLocator }; // Otherwise, we need to ask the project (which will in turn ask the linkers for help) // Note: the trailing slash is caused by a quirk in the PnP implementation that requires folders to end with a trailing slash to disambiguate them from regular files const locator = await project.findLocatorForLocation(`${packageCwd}/`, { strict: true }); if (locator) return { project, locator, workspace: null }; throw new clipanion_1.UsageError(`The nearest package directory (${formatUtils.pretty(configuration, packageCwd, formatUtils.Type.PATH)}) doesn't seem to be part of the project declared in ${formatUtils.pretty(configuration, project.cwd, formatUtils.Type.PATH)}.\n\n- If the project directory is right, it might be that you forgot to list ${formatUtils.pretty(configuration, fslib_1.ppath.relative(project.cwd, packageCwd), formatUtils.Type.PATH)} as a workspace.\n- If it isn't, it's likely because you have a yarn.lock or package.json file there, confusing the project root detection.`); } static generateBuildStateFile(buildState, locatorStore) { let bstateFile = `# Warning: This file is automatically generated. Removing it is fine, but will\n# cause all your builds to become invalidated.\n`; const bstateData = [...buildState].map(([locatorHash, hash]) => { const locator = locatorStore.get(locatorHash); if (typeof locator === `undefined`) throw new Error(`Assertion failed: The locator should have been registered`); return [structUtils.stringifyLocator(locator), locator.locatorHash, hash]; }); for (const [locatorString, locatorHash, buildHash] of miscUtils.sortMap(bstateData, [d => d[0], d => d[1]])) { bstateFile += `\n`; bstateFile += `# ${locatorString}\n`; bstateFile += `${JSON.stringify(locatorHash)}:\n`; bstateFile += ` ${buildHash}\n`; } return bstateFile; } async setupResolutions() { this.storedResolutions = new Map(); this.storedDescriptors = new Map(); this.storedPackages = new Map(); this.lockFileChecksum = null; const lockfilePath = fslib_1.ppath.join(this.cwd, this.configuration.get(`lockfileFilename`)); const defaultLanguageName = this.configuration.get(`defaultLanguageName`); if (fslib_1.xfs.existsSync(lockfilePath)) { const content = await fslib_1.xfs.readFilePromise(lockfilePath, `utf8`); // We store the salted checksum of the lockfile in order to invalidate the install state when needed this.lockFileChecksum = hashUtils.makeHash(`${INSTALL_STATE_VERSION}`, content); const parsed = parsers_1.parseSyml(content); // Protects against v1 lockfiles if (parsed.__metadata) { const lockfileVersion = parsed.__metadata.version; const cacheKey = parsed.__metadata.cacheKey; for (const key of Object.keys(parsed)) { if (key === `__metadata`) continue; const data = parsed[key]; if (typeof data.resolution === `undefined`) throw new Error(`Assertion failed: Expected the lockfile entry to have a resolution field (${key})`); const locator = structUtils.parseLocator(data.resolution, true); const manifest = new Manifest_1.Manifest(); manifest.load(data, { yamlCompatibilityMode: true }); const version = manifest.version; const languageName = manifest.languageName || defaultLanguageName; const linkType = data.linkType.toUpperCase(); const dependencies = manifest.dependencies; const peerDependencies = manifest.peerDependencies; const dependenciesMeta = manifest.dependenciesMeta; const peerDependenciesMeta = manifest.peerDependenciesMeta; const bin = manifest.bin; if (data.checksum != null) { const checksum = typeof cacheKey !== `undefined` && !data.checksum.includes(`/`) ? `${cacheKey}/${data.checksum}` : data.checksum; this.storedChecksums.set(locator.locatorHash, checksum); } if (lockfileVersion >= LOCKFILE_VERSION) { const pkg = { ...locator, version, languageName, linkType, dependencies, peerDependencies, dependenciesMeta, peerDependenciesMeta, bin }; this.originalPackages.set(pkg.locatorHash, pkg); } for (const entry of key.split(MULTIPLE_KEYS_REGEXP)) { const descriptor = structUtils.parseDescriptor(entry); this.storedDescriptors.set(descriptor.descriptorHash, descriptor); if (lockfileVersion >= LOCKFILE_VERSION) { // If the lockfile is up-to-date, we can simply register the // resolution as a done deal. this.storedResolutions.set(descriptor.descriptorHash, locator.locatorHash); } else { // But if it isn't, then we instead setup an alias so that the // descriptor will be re-resolved (so that we get to retrieve the // new fields) while still resolving to the same locators. const resolutionDescriptor = structUtils.convertLocatorToDescriptor(locator); if (resolutionDescriptor.descriptorHash !== descriptor.descriptorHash) { this.storedDescriptors.set(resolutionDescriptor.descriptorHash, resolutionDescriptor); this.resolutionAliases.set(descriptor.descriptorHash, resolutionDescriptor.descriptorHash); } } } } } } } async setupWorkspaces() { this.workspaces = []; this.workspacesByCwd = new Map(); this.workspacesByIdent = new Map(); let workspaceCwds = [this.cwd]; while (workspaceCwds.length > 0) { const passCwds = workspaceCwds; workspaceCwds = []; for (const workspaceCwd of passCwds) { if (this.workspacesByCwd.has(workspaceCwd)) continue; const workspace = await this.addWorkspace(workspaceCwd); const workspacePkg = this.storedPackages.get(workspace.anchoredLocator.locatorHash); if (workspacePkg) workspace.dependencies = workspacePkg.dependencies; for (const workspaceCwd of workspace.workspacesCwds) { workspaceCwds.push(workspaceCwd); } } } } async addWorkspace(workspaceCwd) { const workspace = new Workspace_1.Workspace(workspaceCwd, { project: this }); await workspace.setup(); const dup = this.workspacesByIdent.get(workspace.locator.identHash); if (typeof dup !== `undefined`) throw new Error(`Duplicate workspace name ${structUtils.prettyIdent(this.configuration, workspace.locator)}: ${workspaceCwd} conflicts with ${dup.cwd}`); this.workspaces.push(workspace); this.workspacesByCwd.set(workspaceCwd, workspace); this.workspacesByIdent.set(workspace.locator.identHash, workspace); return workspace; } get topLevelWorkspace() { return this.getWorkspaceByCwd(this.cwd); } tryWorkspaceByCwd(workspaceCwd) { if (!fslib_1.ppath.isAbsolute(workspaceCwd)) workspaceCwd = fslib_1.ppath.resolve(this.cwd, workspaceCwd); workspaceCwd = fslib_1.ppath.normalize(workspaceCwd) .replace(/\/+$/, ``); const workspace = this.workspacesByCwd.get(workspaceCwd); if (!workspace) return null; return workspace; } getWorkspaceByCwd(workspaceCwd) { const workspace = this.tryWorkspaceByCwd(workspaceCwd); if (!workspace) throw new Error(`Workspace not found (${workspaceCwd})`); return workspace; } tryWorkspaceByFilePath(filePath) { let bestWorkspace = null; for (const workspace of this.workspaces) { const rel = fslib_1.ppath.relative(workspace.cwd, filePath); if (rel.startsWith(`../`)) continue; if (bestWorkspace && bestWorkspace.cwd.length >= workspace.cwd.length) continue; bestWorkspace = workspace; } if (!bestWorkspace) return null; return bestWorkspace; } getWorkspaceByFilePath(filePath) { const workspace = this.tryWorkspaceByFilePath(filePath); if (!workspace) throw new Error(`Workspace not found (${filePath})`); return workspace; } tryWorkspaceByIdent(ident) { const workspace = this.workspacesByIdent.get(ident.identHash); if (typeof workspace === `undefined`) return null; return workspace; } getWorkspaceByIdent(ident) { const workspace = this.tryWorkspaceByIdent(ident); if (!workspace) throw new Error(`Workspace not found (${structUtils.prettyIdent(this.configuration, ident)})`); return workspace; } tryWorkspaceByDescriptor(descriptor) { const workspace = this.tryWorkspaceByIdent(descriptor); if (workspace === null || !workspace.accepts(descriptor.range)) return null; return workspace; } getWorkspaceByDescriptor(descriptor) { const workspace = this.tryWorkspaceByDescriptor(descriptor); if (workspace === null) throw new Error(`Workspace not found (${structUtils.prettyDescriptor(this.configuration, descriptor)})`); return workspace; } tryWorkspaceByLocator(locator) { if (structUtils.isVirtualLocator(locator)) locator = structUtils.devirtualizeLocator(locator); const workspace = this.tryWorkspaceByIdent(locator); if (workspace === null || (workspace.locator.locatorHash !== locator.locatorHash && workspace.anchoredLocator.locatorHash !== locator.locatorHash)) return null; return workspace; } getWorkspaceByLocator(locator) { const workspace = this.tryWorkspaceByLocator(locator); if (!workspace) throw new Error(`Workspace not found (${structUtils.prettyLocator(this.configuration, locator)})`); return workspace; } /** * Import the dependencies of each resolved workspace into their own * `Workspace` instance. */ refreshWorkspaceDependencies() { for (const workspace of this.workspaces) { const pkg = this.storedPackages.get(workspace.anchoredLocator.locatorHash); if (!pkg) throw new Error(`Assertion failed: Expected workspace to have been resolved`); workspace.dependencies = new Map(pkg.dependencies); } } forgetResolution(dataStructure) { const deleteDescriptor = (descriptorHash) => { this.storedResolutions.delete(descriptorHash); this.storedDescriptors.delete(descriptorHash); }; const deleteLocator = (locatorHash) => { this.originalPackages.delete(locatorHash); this.storedPackages.delete(locatorHash); this.accessibleLocators.delete(locatorHash); }; if (`descriptorHash` in dataStructure) { const locatorHash = this.storedResolutions.get(dataStructure.descriptorHash); deleteDescriptor(dataStructure.descriptorHash); // We delete unused locators const remainingResolutions = new Set(this.storedResolutions.values()); if (typeof locatorHash !== `undefined` && !remainingResolutions.has(locatorHash)) { deleteLocator(locatorHash); } } if (`locatorHash` in dataStructure) { deleteLocator(dataStructure.locatorHash); // We delete all of the descriptors that have been resolved to the locator for (const [descriptorHash, locatorHash] of this.storedResolutions) { if (locatorHash === dataStructure.locatorHash) { deleteDescriptor(descriptorHash); } } } } forgetTransientResolutions() { const resolver = this.configuration.makeResolver(); for (const pkg of this.originalPackages.values()) { let shouldPersistResolution; try { shouldPersistResolution = resolver.shouldPersistResolution(pkg, { project: this, resolver }); } catch (_a) { shouldPersistResolution = false; } if (!shouldPersistResolution) { this.forgetResolution(pkg); } } } forgetVirtualResolutions() { for (const pkg of this.storedPackages.values()) { for (const [dependencyHash, dependency] of pkg.dependencies) { if (structUtils.isVirtualDescriptor(dependency)) { pkg.dependencies.set(dependencyHash, structUtils.devirtualizeDescriptor(dependency)); } } } } getDependencyMeta(ident, version) { const dependencyMeta = {}; const dependenciesMeta = this.topLevelWorkspace.manifest.dependenciesMeta; const dependencyMetaSet = dependenciesMeta.get(structUtils.stringifyIdent(ident)); if (!dependencyMetaSet) return dependencyMeta; const defaultMeta = dependencyMetaSet.get(null); if (defaultMeta) Object.assign(dependencyMeta, defaultMeta); if (version === null || !semver_1.default.valid(version)) return dependencyMeta; for (const [range, meta] of dependencyMetaSet) if (range !== null && range === version) Object.assign(dependencyMeta, meta); return dependencyMeta; } async findLocatorForLocation(cwd, { strict = false } = {}) { const report = new ThrowReport_1.ThrowReport(); const linkers = this.configuration.getLinkers(); const linkerOptions = { project: this, report }; for (const linker of linkers) { const locator = await linker.findPackageLocator(cwd, linkerOptions); if (locator) { // If strict mode, the specified cwd must be a package, // not merely contained in a package. if (strict) { const location = await linker.findPackageLocation(locator, linkerOptions); if (location.replace(TRAILING_SLASH_REGEXP, ``) !== cwd.replace(TRAILING_SLASH_REGEXP, ``)) { continue; } } return locator; } } return null; } async resolveEverything(opts) { if (!this.workspacesByCwd || !this.workspacesByIdent) throw new Error(`Workspaces must have been setup before calling this function`); // Reverts the changes that have been applied to the tree because of any previous virtual resolution pass this.forgetVirtualResolutions(); // Ensures that we notice it when dependencies are added / removed from all sources coming from the filesystem if (!opts.lockfileOnly) this.forgetTransientResolutions(); // Note that the resolution process is "offline" until everything has been // successfully resolved; all the processing is expected to have zero side // effects until we're ready to set all the variables at once (the one // exception being when a resolver needs to fetch a package, in which case // we might need to populate the cache). // // This makes it possible to use the same Project instance for multiple // purposes at the same time (since `resolveEverything` is async, it might // happen that we want to do something while waiting for it to end; if we // were to mutate the project then it would end up in a partial state that // could lead to hard-to-debug issues). const realResolver = opts.resolver || this.configuration.makeResolver(); const legacyMigrationResolver = new LegacyMigrationResolver_1.LegacyMigrationResolver(); await legacyMigrationResolver.setup(this, { report: opts.report }); const resolver = opts.lockfileOnly ? new MultiResolver_1.MultiResolver([new LockfileResolver_1.LockfileResolver(), new RunInstallPleaseResolver_1.RunInstallPleaseResolver(realResolver)]) : new MultiResolver_1.MultiResolver([new LockfileResolver_1.LockfileResolver(), legacyMigrationResolver, realResolver]); const fetcher = this.configuration.makeFetcher(); const resolveOptions = opts.lockfileOnly ? { project: this, report: opts.report, resolver } : { project: this, report: opts.report, resolver, fetchOptions: { project: this, cache: opts.cache, checksums: this.storedChecksums, report: opts.report, fetcher } }; const allDescriptors = new Map(); const allPackages = new Map(); const allResolutions = new Map(); const originalPackages = new Map(); const packageResolutionPromises = new Map(); const descriptorResolutionPromises = new Map(); const resolutionQueue = []; const startPackageResolution = async (locator) => { const originalPkg = await miscUtils.prettifyAsyncErrors(async () => { return await resolver.resolve(locator, resolveOptions); }, message => { return `${structUtils.prettyLocator(this.configuration, locator)}: ${message}`; }); if (!structUtils.areLocatorsEqual(locator, originalPkg)) throw new Error(`Assertion failed: The locator cannot be changed by the resolver (went from ${structUtils.prettyLocator(this.configuration, locator)} to ${structUtils.prettyLocator(this.configuration, originalPkg)})`); originalPackages.set(originalPkg.locatorHash, originalPkg); const pkg = this.configuration.normalizePackage(originalPkg); for (const [identHash, descriptor] of pkg.dependencies) { const dependency = await this.configuration.reduceHook(hooks => { return hooks.reduceDependency; }, descriptor, this, pkg, descriptor, { resolver, resolveOptions, }); if (!structUtils.areIdentsEqual(descriptor, dependency)) throw new Error(`Assertion failed: The descriptor ident cannot be changed through aliases`); const bound = resolver.bindDescriptor(dependency, locator, resolveOptions); pkg.dependencies.set(identHash, bound); } resolutionQueue.push(Promise.all([...pkg.dependencies.values()].map(descriptor => { return scheduleDescriptorResolution(descriptor); }))); allPackages.set(pkg.locatorHash, pkg); return pkg; }; const schedulePackageResolution = async (locator) => { const promise = packageResolutionPromises.get(locator.locatorHash); if (typeof promise !== `undefined`) return promise; const newPromise = Promise.resolve().then(() => startPackageResolution(locator)); packageResolutionPromises.set(locator.locatorHash, newPromise); return newPromise; }; const startDescriptorAliasing = async (descriptor, alias) => { const resolution = await scheduleDescriptorResolution(alias); allDescriptors.set(descriptor.descriptorHash, descriptor); allResolutions.set(descriptor.descriptorHash, resolution.locatorHash); return resolution; }; const startDescriptorResolution = async (descriptor) => { const alias = this.resolutionAliases.get(descriptor.descriptorHash); if (typeof alias !== `undefined`) return startDescriptorAliasing(descriptor, this.storedDescriptors.get(alias)); const resolutionDependencies = resolver.getResolutionDependencies(descriptor, resolveOptions); const resolvedDependencies = new Map(await Promise.all(resolutionDependencies.map(async (dependency) => { return [dependency.descriptorHash, await scheduleDescriptorResolution(dependency)]; }))); const candidateResolutions = await miscUtils.prettifyAsyncErrors(async () => { return await resolver.getCandidates(descriptor, resolvedDependencies, resolveOptions); }, message => { return `${structUtils.prettyDescriptor(this.configuration, descriptor)}: ${message}`; }); const finalResolution = candidateResolutions[0]; if (typeof finalResolution === `undefined`) throw new Error(`${structUtils.prettyDescriptor(this.configuration, descriptor)}: No candidates found`); allDescriptors.set(descriptor.descriptorHash, descriptor); allResolutions.set(descriptor.descriptorHash, finalResolution.locatorHash); return schedulePackageResolution(finalResolution); }; const scheduleDescriptorResolution = (descriptor) => { const promise = descriptorResolutionPromises.get(descriptor.descriptorHash); if (typeof promise !== `undefined`) return promise; allDescriptors.set(descriptor.descriptorHash, descriptor); const newPromise = Promise.resolve().then(() => startDescriptorResolution(descriptor)); descriptorResolutionPromises.set(descriptor.descriptorHash, newPromise); return newPromise; }; for (const workspace of this.workspaces) { const workspaceDescriptor = workspace.anchoredDescriptor; resolutionQueue.push(scheduleDescriptorResolution(workspaceDescriptor)); } while (resolutionQueue.length > 0) { const copy = [...resolutionQueue]; resolutionQueue.length = 0; await Promise.all(copy); } // In this step we now create virtual packages for each package with at // least one peer dependency. We also use it to search for the alias // descriptors that aren't depended upon by anything and can be safely // pruned. const volatileDescriptors = new Set(this.resolutionAliases.values()); const optionalBuilds = new Set(allPackages.keys()); const accessibleLocators = new Set(); const peerRequirements = new Map(); applyVirtualResolutionMutations({ project: this, report: opts.report, accessibleLocators, volatileDescriptors, optionalBuilds, peerRequirements, allDescriptors, allResolutions, allPackages, }); // All descriptors still referenced within the volatileDescriptors set are // descriptors that aren't depended upon by anything in the dependency tree. for (const descriptorHash of volatileDescriptors) { allDescriptors.delete(descriptorHash); allResolutions.delete(descriptorHash); } // Everything is done, we can now update our internal resolutions to // reference the new ones this.storedResolutions = allResolutions; this.storedDescriptors = allDescriptors; this.storedPackages = allPackages; this.accessibleLocators = accessibleLocators; this.originalPackages = originalPackages; this.optionalBuilds = optionalBuilds; this.peerRequirements = peerRequirements; // Now that the internal resolutions have been updated, we can refresh the // dependencies of each resolved workspace's `Workspace` instance. this.refreshWorkspaceDependencies(); } async fetchEverything({ cache, report, fetcher: userFetcher }) { const fetcher = userFetcher || this.configuration.makeFetcher(); const fetcherOptions = { checksums: this.storedChecksums, project: this, cache, fetcher, report }; const locatorHashes = Array.from(new Set(miscUtils.sortMap(this.storedResolutions.values(), [ (locatorHash) => { const pkg = this.storedPackages.get(locatorHash); if (!pkg) throw new Error(`Assertion failed: The locator should have been registered`); return structUtils.stringifyLocator(pkg); }, ]))); let firstError = false; const progress = Report_1.Report.progressViaCounter(locatorHashes.length); report.reportProgress(progress); const limit = p_limit_1.default(FETCHER_CONCURRENCY); await report.startCacheReport(async () => { await Promise.all(locatorHashes.map(locatorHash => limit(async () => { const pkg = this.storedPackages.get(locatorHash); if (!pkg) throw new Error(`Assertion failed: The locator should have been registered`); if (structUtils.isVirtualLocator(pkg)) return; let fetchResult; try { fetchResult = await fetcher.fetch(pkg, fetcherOptions); } catch (error) { error.message = `${structUtils.prettyLocator(this.configuration, pkg)}: ${error.message}`; report.reportExceptionOnce(error); firstError = error; return; } if (fetchResult.checksum) this.storedChecksums.set(pkg.locatorHash, fetchResult.checksum); else this.storedChecksums.delete(pkg.locatorHash); if (fetchResult.releaseFs) { fetchResult.releaseFs(); } }).finally(() => { progress.tick(); }))); }); if (firstError) { throw firstError; } } async linkEverything({ cache, report, fetcher: optFetcher, skipBuild }) { var _a; const fetcher = optFetcher || this.configuration.makeFetcher(); const fetcherOptions = { checksums: this.storedChecksums, project: this, cache, fetcher, report, skipIntegrityCheck: true }; const linkers = this.configuration.getLinkers(); const linkerOptions = { project: this, report }; const installers = new Map(linkers.map(linker => { const installer = linker.makeInstaller(linkerOptions); const customDataKey = installer.getCustomDataKey(); const customData = this.installersCustomData.get(customDataKey); if (typeof customData !== `undefined`) installer.attachCustomData(customData); return [linker, installer]; })); const packageLinkers = new Map(); const packageLocations = new Map(); const packageBuildDirectives = new Map(); const fetchResultsPerPackage = new Map(await Promise.all([...this.accessibleLocators].map(async (locatorHash) => { const pkg = this.storedPackages.get(locatorHash); if (!pkg) throw new Error(`Assertion failed: The locator should have been registered`); return [locatorHash, await fetcher.fetch(pkg, fetcherOptions)]; }))); // Step 1: Installing the packages on the disk for (const locatorHash of this.accessibleLocators) { const pkg = this.storedPackages.get(locatorHash); if (typeof pkg === `undefined`) throw new Error(`Assertion failed: The locator should have been registered`); const fetchResult = fetchResultsPerPackage.get(pkg.locatorHash); if (typeof fetchResult === `undefined`) throw new Error(`Assertion failed: The fetch result should have been registered`); const workspace = this.tryWorkspaceByLocator(pkg); if (workspace !== null) { const buildScripts = []; const { scripts } = workspace.manifest; for (const scriptName of [`preinstall`, `install`, `postinstall`]) if (scripts.has(scriptName)) buildScripts.push([Installer_1.BuildType.SCRIPT, scriptName]); try { for (const installer of installers.values()) { const result = await installer.installPackage(pkg, fetchResult); if (result.buildDirective !== null) { throw new Error(`Assertion failed: Linkers can't return build directives for workspaces; this responsibility befalls to the Yarn core`); } } } finally { if (fetchResult.releaseFs) { fetchResult.releaseFs(); } } const location = fslib_1.ppath.join(fetchResult.packageFs.getRealPath(), fetchResult.prefixPath); packageLocations.set(pkg.locatorHash, location); if (buildScripts.length > 0) { packageBuildDirectives.set(pkg.locatorHash, { directives: buildScripts, buildLocations: [location], }); } } else { const linker = linkers.find(linker => linker.supportsPackage(pkg, linkerOptions)); if (!linker) throw new Report_1.ReportError(MessageName_1.MessageName.LINKER_NOT_FOUND, `${structUtils.prettyLocator(this.configuration, pkg)} isn't supported by any available linker`); const installer = installers.get(linker); if (!installer) throw new Error(`Assertion failed: The installer should have been registered`); let installStatus; try { installStatus = await installer.installPackage(pkg, fetchResult); } finally { if (fetchResult.releaseFs) { fetchResult.releaseFs(); } } packageLinkers.set(pkg.locatorHash, linker); packageLocations.set(pkg.locatorHash, installStatus.packageLocation); if (installStatus.buildDirective && installStatus.packageLocation) { packageBuildDirectives.set(pkg.locatorHash, { directives: installStatus.buildDirective, buildLocations: [installStatus.packageLocation], }); } } } // Step 2: Link packages together const externalDependents = new Map(); for (const locatorHash of this.accessibleLocators) { const pkg = this.storedPackages.get(locatorHash); if (!pkg) throw new Error(`Assertion failed: The locator should have been registered`); const isWorkspace = this.tryWorkspaceByLocator(pkg) !== null; const linkPackage = async (packageLinker, installer) => { const packageLocation = packageLocations.get(pkg.locatorHash); if (typeof packageLocation === `undefined`) throw new Error(`Assertion failed: The package (${structUtils.prettyLocator(this.configuration, pkg)}) should have been registered`); const internalDependencies = []; for (const descriptor of pkg.dependencies.values()) { const resolution = this.storedResolutions.get(descriptor.descriptorHash); if (typeof resolution === `undefined`) throw new Error(`Assertion failed: The resolution (${structUtils.prettyDescriptor(this.configuration, descriptor)}, from ${structUtils.prettyLocator(this.configuration, pkg)})should have been registered`); const dependency = this.storedPackages.get(resolution); if (typeof dependency === `undefined`) throw new Error(`Assertion failed: The package (${resolution}, resolved from ${structUtils.prettyDescriptor(this.configuration, descriptor)}) should have been registered`); const dependencyLinker = this.tryWorkspaceByLocator(dependency) === null ? packageLinkers.get(resolution) : null; if (typeof dependencyLinker === `undefined`) throw new Error(`Assertion failed: The package (${resolution}, resolved from ${structUtils.prettyDescriptor(this.configuration, descriptor)}) should have been registered`); const isWorkspaceDependency = dependencyLinker === null; if (dependencyLinker === packageLinker || isWorkspace || isWorkspaceDependency) { if (packageLocations.get(dependency.locatorHash) !== null) { internalDependencies.push([descriptor, dependency]); } } else if (packageLocation !== null) { const externalEntry = miscUtils.getArrayWithDefault(externalDependents, resolution); externalEntry.push(packageLocation); } } if (packageLocation !== null) { await installer.attachInternalDependencies(pkg, internalDependencies); } }; if (isWorkspace) { for (const [packageLinker, installer] of installers) { await linkPackage(packageLinker, installer); } } else { const packageLinker = packageLinkers.get(pkg.locatorHash); if (!packageLinker) throw new Error(`Assertion failed: The linker should have been found`); const installer = installers.get(packageLinker); if (!installer) throw new Error(`Assertion failed: The installer should have been registered`); await linkPackage(packageLinker, installer); } } for (const [locatorHash, dependentPaths] of externalDependents) { const pkg = this.storedPackages.get(locatorHash); if (!pkg) throw new Error(`Assertion failed: The package should have been registered`); const packageLinker = packageLinkers.get(pkg.locatorHash); if (!packageLinker) throw new Error(`Assertion failed: The linker should have been found`); const installer = installers.get(packageLinker); if (!installer) throw new Error(`Assertion failed: The installer should have been registered`); await installer.attachExternalDependents(pkg, dependentPaths); } // Step 3: Inform our linkers that they should have all the info needed const installersCustomData = new Map(); for (const installer of installers.values()) { const finalizeInstallData = await installer.finalizeInstall(); for (const installStatus of (_a = finalizeInstallData === null || finalizeInstallData === void 0 ? void 0 : finalizeInstallData.records) !== null && _a !== void 0 ? _a : []) { packageBuildDirectives.set(installStatus.locatorHash, { directives: installStatus.buildDirective, buildLocations: installStatus.buildLocations, }); } if (typeof (finalizeInstallData === null || finalizeInstallData === void 0 ? void 0 : finalizeInstallData.customData) !== `undefined`) { installersCustomData.set(installer.getCustomDataKey(), finalizeInstallData.customData); } } this.installersCustomData = installersCustomData; await this.persistInstallStateFile(); // Step 4: Build the packages in multiple steps if (skipBuild) return; const readyPackages = new Set(this.storedPackages.keys()); const buildablePackages = new Set(packageBuildDirectives.keys()); for (const locatorHash of buildablePackages) readyPackages.delete(locatorHash); const globalHashGenerator = crypto_1.createHash(`sha512`); globalHashGenerator.update(process.versions.node); this.configuration.triggerHook(hooks => { return hooks.globalHashGeneration; }, this, (data) => { globalHashGenerator.update(`\0`); globalHashGenerator.update(data); }); const globalHash = globalHashGenerator.digest(`hex`); const packageHashMap = new Map(); // We'll use this function is order to compute a hash for each package // that exposes a build directive. If the hash changes compared to the // previous run, the package is rebuilt. This has the advantage of making // the rebuilds much more predictable than before, and to give us the tools // later to improve this further by explaining *why* a rebuild happened. const getBaseHash = (locator) => { let hash = packageHashMap.get(locator.locatorHash); if (typeof hash !== `undefined`) return hash; const pkg = this.storedPackages.get(locator.locatorHash); if (typeof pkg === `undefined`) throw new Error(`Assertion failed: The package should have been registered`); const builder = crypto_1.createHash(`sha512`); builder.update(locator.locatorHash); // To avoid the case where one dependency depends on itself somehow packageHashMap.set(locator.locatorHash, ``); for (const descriptor of pkg.dependencies.values()) { const resolution = this.storedResolutions.get(descriptor.descriptorHash); if (typeof resolution === `undefined`) throw new Error(`Assertion failed: The resolution (${structUtils.prettyDescriptor(this.configuration, descriptor)}) should have been registered`); const dependency = this.storedPackages.get(resolution); if (typeof dependency === `undefined`) throw new Error(`Assertion failed: The package should have been registered`); builder.update(getBaseHash(dependency)); } hash = builder.digest(`hex`); packageHashMap.set(locator.locatorHash, hash); return hash; }; const getBuildHash = (locator, buildLocations) => { const builder = crypto_1.createHash(`sha512`); builder.update(globalHash); builder.update(getBaseHash(locator)); for (const location of buildLocations) builder.update(location); return builder.digest(`hex`); }; const bstatePath = this.configuration.get(`bstatePath`); const bstate = fslib_1.xfs.existsSync(bstatePath) ? parsers_1.parseSyml(await fslib_1.xfs.readFilePromise(bstatePath, `utf8`)) : {}; // We reconstruct the build state from an empty object because we want to // remove the state from packages that got removed const nextBState = new Map(); while (buildablePackages.size > 0) { const savedSize = buildablePackages.size; const buildPromises = []; for (const locatorHash of buildablePackages) { const pkg = this.storedPackages.get(locatorHash); if (!pkg) throw new Error(`Assertion failed: The package should have been registered`); let isBuildable = true; for (const dependency of pkg.dependencies.values()) { const resolution = this.storedResolutions.get(dependency.descriptorHash); if (!resolution) throw new Error(`Assertion failed: The resolution (${structUtils.prettyDescriptor(this.configuration, dependency)}) should have been registered`); if (buildablePackages.has(resolution)) { isBuildable = false; break; } } // Wait until all dependencies of the current package have been built // before trying to build it (since it might need them to build itself) if (!isBuildable) continue; buildablePackages.delete(locatorHash); const buildInfo = packageBuildDirectives.get(pkg.locatorHash); if (!buildInfo) throw new Error(`Assertion failed: The build directive should have been registered`); const buildHash = getBuildHash(pkg, buildInfo.buildLocations); // No need to rebuild the package if its hash didn't change if (Object.prototype.hasOwnProperty.call(bstate, pkg.locatorHash) && bstate[pkg.locatorHash] === buildHash) { nextBState.set(pkg.locatorHash, buildHash); continue; } if (Object.prototype.hasOwnProperty.call(bstate, pkg.locatorHash)) report.reportInfo(MessageName_1.MessageName.MUST_REBUILD, `${structUtils.prettyLocator(this.configuration, pkg)} must be rebuilt because its dependency tree changed`); else report.reportInfo(MessageName_1.MessageName.MUST_BUILD, `${structUtils.prettyLocator(this.configuration, pkg)} must be built because it never did before or the last one failed`); for (const location of buildInfo.buildLocations) { if (!fslib_1.ppath.isAbsolute(location)) throw new Error(`Assertion failed: Expected the build location to be absolute (not ${location})`); buildPromises.push((async () => { for (const [buildType, scriptName] of buildInfo.directives) { let header = `# This file contains the result of Yarn building a package (${structUtils.stringifyLocator(pkg)})\n`; switch (buildType) { case Installer_1.BuildType.SCRIPT: { header += `# Script name: ${scriptName}\n`; } break; case Installer_1.BuildType.SHELLCODE: { header += `# Script code: ${scriptName}\n`; } break; } const stdin = null; await fslib_1.xfs.mktempPromise(async (logDir) => { const logFile = fslib_1.ppath.join(logDir, `build.log`); const { stdout, stderr } = this.configuration.getSubprocessStreams(logFile, { header, prefix: structUtils.prettyLocator(this.configuration, pkg), report, }); let exitCode; try { switch (buildType) { case Installer_1.BuildType.SCRIPT: { exitCode = await scriptUtils.executePackageScript(pkg, scriptName, [], { cwd: location, project: this, stdin, stdout, stderr }); } break; case Installer_1.BuildType.SHELLCODE: { exitCode = await scriptUtils.executePackageShellcode(pkg, scriptName, [], { cwd: location, project: this, stdin, stdout, stderr }); } break; } } catch (error) { stderr.write(error.stack); exitCode = 1; } stdout.end(); stderr.end(); if (exitCode === 0) { nextBState.set(pkg.locatorHash, buildHash); return true; } fslib_1.xfs.detachTemp(logDir); const buildMessage = `${structUtils.prettyLocator(this.configuration, pkg)} couldn't be built successfully (exit code ${formatUtils.pretty(this.configuration, exitCode, formatUtils.Type.NUMBER)}, logs can be found here: ${formatUtils.pretty(this.configuration, logFile, formatUtils.Type.PATH)})`; report.reportInfo(MessageName_1.MessageName.BUILD_FAILED, buildMessage); if (this.optionalBuilds.has(pkg.locatorHash)) { nextBState.set(pkg.locatorHash, buildHash); return true; } report.reportError(MessageName_1.MessageName.BUILD_FAILED, buildMessage); return false; }); } })()); } } await Promise.all(buildPromises); // If we reach this code, it means that we have circular dependencies // somewhere. Worst, it means that the circular dependencies both have // build scripts, making them unsatisfiable. if (savedSize === buildablePackages.size) { const prettyLocators = Array.from(buildablePackages).map(locatorHash => { const pkg = this.storedPackages.get(locatorHash); if (!pkg) throw new Error(`Assertion failed: The package should have been registered`); return structUtils.prettyLocator(this.configuration, pkg); }).join(`, `); report.reportError(MessageName_1.MessageName.CYCLIC_DEPENDENCIES, `Some packages have circular dependencies that make their build order unsatisfiable - as a result they won't be built (affected packages are: ${prettyLocators})`); break; } } // We can now generate the bstate file, which will allow us to "remember" // what's the dependency tree subset that we used to build a specific // package (and avoid rebuilding it later if it didn't change). if (nextBState.size > 0) { const bstatePath = this.configuration.get(`bstatePath`); const bstateFile = Project.generateBuildStateFile(nextBState, this.storedPackages); await fslib_1.xfs.mkdirPromise(fslib_1.ppath.dirname(bstatePath), { recursive: true }); await fslib_1.xfs.changeFilePromise(bstatePath, bstateFile, { automaticNewlines: true, }); } else { await fslib_1.xfs.removePromise(bstatePath); } } async install(opts) { var _a, _b; const nodeLinker = this.configuration.get(`nodeLinker`); (_a = Configuration_1.Configuration.telemetry) === null || _a === void 0 ? void 0 : _a.reportInstall(nodeLinker); await opts.report.startTimerPromise(`Project validation`, { skipIfEmpty: true, }, async () => { await this.configuration.triggerHook(hooks => { return hooks.validateProject; }, this, { reportWarning: opts.report.reportWarning.bind(opts.report), reportError: opts.report.reportError.bind(opts.report), }); }); for (const extensionsByIdent of this.configuration.packageExtensions.values()) for (const [, extensionsByRange] of extensionsByIdent) for (const extension of extensionsByRange) extension.status = types_1.PackageExtensionStatus.Inactive; const lockfilePath = fslib_1.ppath.join(this.cwd, this.configuration.get(`lockfileFilename`)); // If we operate with a frozen lockfile, we take a snapshot of it to later make sure it didn't change let initialLockfile = null; if (opts.immutable) { try { initialLockfile = await fslib_1.xfs.readFilePromise(lockfilePath, `utf8`); } catch (error) { if (error.code === `ENOENT`) { throw new Report_1.ReportError(MessageName_1.MessageName.FROZEN_LOCKFILE_EXCEPTION, `The lockfile would have been created by this install, which is explicitly forbidden.`); } else { throw error; } } } await opts.report.startTimerPromise(`Resolution step`, async () => { await this.resolveEverything(opts); }); await opts.report.startTimerPromise(`Post-resolution validation`, { skipIfEmpty: true, }, async () => { for (const [, extensionsPerRange] of this.configuration.packageExtensions) { for (const [, extensions] of extensionsPerRange) { for (const extension of extensions) { if (extension.userProvided) { const prettyPackageExtension = formatUtils.pretty(this.configuration, extension, formatUtils.Type.PACKAGE_EXTENSION); switch (extension.status) { case types_1.PackageExtensionStatus.Inactive: { opts.report.reportWarning(MessageName_1.MessageName.UNUSED_PACKAGE_EXTENSION, `${prettyPackageExtension}: No matching package in the dependency tree; you may not need this rule anymore.`); } break; case types_1.PackageExtensionStatus.Redundant: { opts.report.reportWarning(MessageName_1.MessageName.REDUNDANT_PACKAGE_EXTENSION, `${prettyPackageExtension}: This rule seems redundant when applied on the original package; the extension may have been applied upstream.`); } break; } } } } } if (initialLockfile !== null) { const newLockfile = fslib_1.normalizeLineEndings(initialLockfile, this.generateLockfile()); if (newLockfile !== initialLockfile) { const diff = diff_1.structuredPatch(lockfilePath, lockfilePath, initialLockfile, newLockfile); opts.report.reportSeparator(); for (const hunk of diff.hunks) { opts.report.reportInfo(null, `@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`); for (const line of hunk.lines) { if (line.startsWith(`+`)) { opts.report.reportError(MessageName_1.MessageName.FROZEN_LOCKFILE_EXCEPTION, formatUtils.pretty(this.configuration, line, formatUtils.Type.ADDED)); } else if (line.startsWith(`-`)) { opts.report.reportError(MessageName_1.MessageName.FROZEN_LOCKFILE_EXCEPTION, formatUtils.pretty(this.configuration, line, formatUtils.Type.REMOVED)); } else { opts.report.reportInfo(null, formatUtils.pretty(this.configuration, line, `grey`)); } } } opts.report.reportSeparator(); throw new Report_1.ReportError(MessageName_1.MessageName.FROZEN_LOCKFILE_EXCEPTION, `The lockfile would have been modified by this install, which is explicitly forbidden.`); } } }); for (const extensionsByIdent of this.configuration.packageExtensions.values()) for (const [, extensionsByRange] of extensionsByIdent) for (const extension of extensionsByRange) if (extension.userProvided && extension.status === types_1.PackageExtensionStatus.Active) (_b = Configuration_1.Configuration.telemetry) === null || _b === void 0 ? void 0 : _b.reportPackageExtension(formatUtils.json(extension, formatUtils.Type.PACKAGE_EXTENSION)); await opts.report.startTimerPromise(`Fetch step`, async () => { await this.fetchEverything(opts); if (typeof opts.persistProject === `undefined` || opts.persistProject) { await this.cacheCleanup(opts); } }); if (typeof opts.persistProject === `undefined` || opts.persistProject) await this.persist(); await opts.report.startTimerPromise(`Link step`, async () => { const immutablePatterns = opts.immutable ? [...new Set(this.configuration.get(`immutablePatterns`))].sort() : []; const before = await Promise.all(immutablePatterns.map(async (pattern) => { return hashUtils.checksumPattern(pattern, { cwd: this.cwd }); })); await this.linkEverything(opts); const after = await Promise.all(immutablePatterns.map(async (pattern) => { return hashUtils.checksumPattern(pattern, { cwd: this.cwd }); })); for (let t = 0; t < immutablePatterns.length; ++t) { if (before[t] !== after[t]) { opts.report.reportError(MessageName_1.MessageName.FROZEN_ARTIFACT_EXCEPTION, `The checksum for ${immutablePatterns[t]} has been modified by this install, which is explicitly forbidden.`); } } }); await this.persistInstallStateFile(); await this.configuration.triggerHook(hooks => { return hooks.afterAllInstalled; }, this, opts); } generateLockfile() { // We generate the data structure that will represent our lockfile. To do this, we create a // reverse lookup table, where the key will be the resolved locator and the value will be a set // of all the descriptors that resolved to it. Then we use it to construct an optimized version // if the final object. const reverseLookup = new Map(); for (const [descriptorHash, locatorHash] of this.storedResolutions.entries()) { let descriptorHashes = reverseLookup.get(locatorHash); if (!descriptorHashes) reverseLookup.set(locatorHash, descriptorHashes = new Set()); descriptorHashes.add(descriptorHash); } const optimizedLockfile = {}; optimizedLockfile.__metadata = { version: LOCKFILE_VERSION, }; for (const [locatorHash, descriptorHashes] of reverseLookup.entries()) { const pkg = this.originalPackages.get(locatorHash); // A resolution that isn't in `originalPackages` is a virtual packages. // Since virtual packages can be derived from the information stored in // the rest of the lockfile we don't want to bother storing them. if (!pkg) continue; const descriptors = []; for (const descriptorHash of descriptorHashes) { const descriptor = this.storedDescriptors.get(descriptorHash); if (!descriptor) throw new Error(`Assertion failed: The descriptor should have been registered`); descriptors.push(descriptor); } const key = descriptors.map(descriptor => { return structUtils.stringifyDescriptor(descriptor); }).sort().join(`, `); const manifest = new Manifest_1.Manifest(); manifest.version = pkg.linkType === types_2.LinkType.HARD ? pkg.version : `0.0.0-use.local`; manifest.languageName = pkg.languageName; manifest.dependencies = new Map(pkg.dependencies); manifest.peerDependencies = new Map(pkg.peerDependencies); manifest.dependenciesMeta = new Map(pkg.dependenciesMeta); manifest.peerDependenciesMeta = new Map(pkg.peerDependenciesMeta); manifest.bin = new Map(pkg.bin); let entryChecksum; const checksum = this.storedChecksums.get(pkg.locatorHash); if (typeof checksum !== `undefined`) { const cacheKeyIndex = checksum.indexOf(`/`); if (cacheKeyIndex === -1) throw new Error(`Assertion failed: Expecte the checksum to reference its cache key`); const cacheKey = checksum.slice(0, cacheKeyIndex); const hash = checksum.slice(cacheKeyIndex + 1); if (typeof optimizedLockfile.__metadata.cacheKey === `undefined`) optimizedLockfile.__metadata.cacheKey = cacheKey; if (cacheKey === optimizedLockfile.__metadata.cacheKey) { entryChecksum = hash; } else { entryChecksum = checksum; } } optimizedLockfile[key] = { ...manifest.exportTo({}, { compatibilityMode: false, }), linkType: pkg.linkType.toLowerCase(), resolution: structUtils.stringifyLocator(pkg), checksum: entryChecksum, }; } const header = `${[ `# This file is generated by running "yarn install" inside your project.\n`, `# Manual changes might be lost - proceed with caution!\n`, ].join(``)}\n`; return header + parsers_1.stringifySyml(optimizedLockfile); } async persistLockfile() { const lockfilePath = fslib_1.ppath.join(this.cwd, this.configuration.get(`lockfileFilename`)); const lockfileContent = this.generateLockfile(); await fslib_1.xfs.changeFilePromise(lockfilePath, lockfileContent, { automaticNewlines: true, }); } async persistInstallStateFile() { const fields = []; for (const category of Object.values(INSTALL_STATE_FIELDS)) fields.push(...category); const installState = pick_1.default(this, fields); const serializedState = await gzip(v8_1.default.serialize(installState)); const installStatePath = this.configuration.get(`installStatePath`); await fslib_1.xfs.mkdirPromise(fslib_1.ppath.dirname(installStatePath), { recursive: true }); await fslib_1.xfs.changeFilePromise(installStatePath, serializedState); } async restoreInstallState({ restoreInstallersCustomData = true, restoreResolutions = true } = {}) { const installStatePath = this.configuration.get(`installStatePath`); if (!fslib_1.xfs.existsSync(installStatePath)) { if (restoreResolutions) await this.applyLightResolution(); return; } const serializedState = await fslib_1.xfs.readFilePromise(installStatePath); const installState = v8_1.default.deserialize(await gunzip(serializedState)); if (restoreInstallersCustomData) if (typeof installState.installersCustomData !== `undefined`) this.installersCustomData = installState.installersCustomData; if (restoreResolutions) { if (installState.lockFileChecksum === this.lockFileChecksum) { Object.assign(this, pick_1.default(installState, INSTALL_STATE_FIELDS.restoreResolutions)); this.refreshWorkspaceDependencies(); } else { await this.applyLightResolution(); } } } async applyLightResolution() { await this.resolveEverything({ lockfileOnly: true, report: new ThrowReport_1.ThrowReport(), }); await this.persistInstallStateFile(); } async persist() { await this.persistLockfile(); for (const workspace of this.workspacesByCwd.values()) { await workspace.persistManifest(); } } async cacheCleanup({ cache, report }) { const PRESERVED_FILES = new Set([ `.gitignore`, ]); if (!fslib_1.xfs.existsSync(cache.cwd)) return; if (!folderUtils_1.isFolderInside(cache.cwd, this.cwd)) return; for (const entry of await fslib_1.xfs.readdirPromise(cache.cwd)) { if (PRESERVED_FILES.has(entry)) continue; const entryPath = fslib_1.ppath.resolve(cache.cwd, entry); if (cache.markedFiles.has(entryPath)) continue; if (cache.immutable) { report.reportError(MessageName_1.MessageName.IMMUTABLE_CACHE, `${formatUtils.pretty(this.configuration, fslib_1.ppath.basename(entryPath), `magenta`)} appears to be unused and would marked for deletion, but the cache is immutable`); } else { report.reportInfo(MessageName_1.MessageName.UNUSED_CACHE_ENTRY, `${formatUtils.pretty(this.configuration, fslib_1.ppath.basename(entryPath), `magenta`)} appears to be unused - removing`); await fslib_1.xfs.removePromise(entryPath); } } cache.markedFiles.clear(); } } exports.Project = Project; /** * This function is worth some documentation. It takes a set of packages, * traverses them all, and generates virtual packages for each package that * lists peer dependencies. * * We also take advantage of the tree traversal to detect which packages are * actually used and which have disappeared, and to know which packages truly * have an optional build (since a package may be optional in one part of the * tree but not another). */ function applyVirtualResolutionMutations({ project, allDescriptors, allResolutions, allPackages, accessibleLocators = new Set(), optionalBuilds = new Set(), volatileDescriptors = new Set(), peerRequirements = new Map(), report, tolerateMissingPackages = false, }) { var _a; const virtualStack = new Map(); const resolutionStack = []; const allIdents = new Map(); // We'll be keeping track of all virtual descriptors; once they have all // been generated we'll check whether they can be consolidated into one. const allVirtualInstances = new Map(); const allVirtualDependents = new Map(); // First key is the first package that requests the peer dependency. Second // key is the name of the package in the peer dependency. Value is the list // of all packages that extend the original peer requirement. const peerDependencyLinks = new Map(); // We keep track on which package depend on which other package with peer // dependencies; this way we can emit warnings for them later on. const peerDependencyDependents = new Map(); // We must keep a copy of the workspaces original dependencies, because they // may be overriden during the virtual package resolution - cf Dragon Test #5 const originalWorkspaceDefinitions = new Map(project.workspaces.map(workspace => { const locatorHash = workspace.anchoredLocator.locatorHash; const pkg = allPackages.get(locatorHash); if (typeof pkg === `undefined`) { if (tolerateMissingPackages) { return [locatorHash, null]; } else { throw new Error(`Assertion failed: The workspace should have an associated package`); } } return [locatorHash, structUtils.copyPackage(pkg)]; })); const reportStackOverflow = () => { const logDir = fslib_1.xfs.mktempSync(); const logFile = fslib_1.ppath.join(logDir, `stacktrace.log`); const maxSize = String(resolutionStack.length + 1).length; const content = resolutionStack.map((locator, index) => { const prefix = `${index + 1}.`.padStart(maxSize, ` `); return `${prefix} ${structUtils.stringifyLocator(locator)}\n`; }).join(``); fslib_1.xfs.writeFileSync(logFile, content); throw new Report_1.ReportError(MessageName_1.MessageName.STACK_OVERFLOW_RESOLUTION, `Encountered a stack overflow when resolving peer dependencies; cf ${logFile}`); }; const getPackageFromDescriptor = (descriptor) => { const resolution = allResolutions.get(descriptor.descriptorHash); if (typeof resolution === `undefined`) throw new Error(`Assertion failed: The resolution should have been registered`); const pkg = allPackages.get(resolution); if (!pkg) throw new Error(`Assertion failed: The package could not be found`); return pkg; }; const resolvePeerDependencies = (parentLocator, peerSlots, { first, optional }) => { if (resolutionStack.length > 1000) reportStackOverflow(); resolutionStack.push(parentLocator); const result = resolvePeerDependenciesImpl(parentLocator, peerSlots, { first, optional }); resolutionStack.pop(); return result; }; const resolvePeerDependenciesImpl = (parentLocator, peerSlots, { first, optional }) => { if (accessibleLocators.has(parentLocator.locatorHash)) return; accessibleLocators.add(parentLocator.locatorHash); if (!optional) optionalBuilds.delete(parentLocator.locatorHash); const parentPackage = allPackages.get(parentLocator.locatorHash); if (!parentPackage) { if (tolerateMissingPackages) { return; } else { throw new Error(`Assertion failed: The package (${structUtils.prettyLocator(project.configuration, parentLocator)}) should have been registered`); } } const newVirtualInstances = []; const firstPass = []; const secondPass = []; const thirdPass = []; const fourthPass = []; // During this first pass we virtualize the descriptors. This allows us // to reference them from their sibling without being order-dependent, // which is required to solve cases where packages with peer dependencies // have peer dependencies themselves. for (const descriptor of Array.from(parentPackage.dependencies.values())) { // We shouldn't virtualize the package if it was obtained through a peer // dependency (which can't be the case for workspaces when resolved // through their top-level) if (parentPackage.peerDependencies.has(descriptor.identHash) && !first) continue; // We had some issues where virtual packages were incorrectly set inside // workspaces, causing leaks. Check the Dragon Test #5 for more details. if (structUtils.isVirtualDescriptor(descriptor)) throw new Error(`Assertion failed: Virtual packages shouldn't be encountered when virtualizing a branch`); // Mark this package as being used (won't be removed from the lockfile) volatileDescriptors.delete(descriptor.descriptorHash); // Detect whether this package is being required let isOptional = optional; if (!isOptional) { const dependencyMetaSet = parentPackage.dependenciesMeta.get(structUtils.stringifyIdent(descriptor)); if (typeof dependencyMetaSet !== `undefined`) { const dependencyMeta = dependencyMetaSet.get(null); if (typeof dependencyMeta !== `undefined` && dependencyMeta.optional) { isOptional = true; } } } const resolution = allResolutions.get(descriptor.descriptorHash); if (!resolution) { // Note that we can't use `getPackageFromDescriptor` (defined below, // because when doing the initial tree building right after loading the // project it's possible that we get some entries that haven't been // registered into the lockfile yet - for example when the user has // manually changed the package.json dependencies) if (tolerateMissingPackages) { continue; } else { throw new Error(`Assertion failed: The resolution (${structUtils.prettyDescriptor(project.configuration, descriptor)}) should have been registered`); } } const pkg = originalWorkspaceDefinitions.get(resolution) || allPackages.get(resolution); if (!pkg) throw new Error(`Assertion failed: The package (${resolution}, resolved from ${structUtils.prettyDescriptor(project.configuration, descriptor)}) should have been registered`); if (pkg.peerDependencies.size === 0) { resolvePeerDependencies(pkg, new Map(), { first: false, optional: isOptional }); continue; } // The stack overflow is checked against two level because a workspace // may have a dev dependency on another workspace that lists the first // one as a regular dependency. In this case the loop will break so we // don't need to throw an exception. const stackDepth = virtualStack.get(pkg.locatorHash); if (typeof stackDepth === `number` && stackDepth >= 2) reportStackOverflow(); let virtualizedDescriptor; let virtualizedPackage; const missingPeerDependencies = new Set(); let nextPeerSlots; firstPass.push(() => { virtualizedDescriptor = structUtils.virtualizeDescriptor(descriptor, parentLocator.locatorHash); virtualizedPackage = structUtils.virtualizePackage(pkg, parentLocator.locatorHash); parentPackage.dependencies.delete(descriptor.identHash); parentPackage.dependencies.set(virtualizedDescriptor.identHash, virtualizedDescriptor); allResolutions.set(virtualizedDescriptor.descriptorHash, virtualizedPackage.locatorHash); allDescriptors.set(virtualizedDescriptor.descriptorHash, virtualizedDescriptor); allPackages.set(virtualizedPackage.locatorHash, virtualizedPackage); // Keep track of all new virtual packages since we'll want to dedupe them newVirtualInstances.push([pkg, virtualizedDescriptor, virtualizedPackage]); }); secondPass.push(() => { var _a; nextPeerSlots = new Map(); for (const peerRequest of virtualizedPackage.peerDependencies.values()) { let peerDescriptor = parentPackage.dependencies.get(peerRequest.identHash); if (!peerDescriptor && structUtils.areIdentsEqual(parentLocator, peerRequest)) { peerDescriptor = structUtils.convertLocatorToDescriptor(parentLocator); allDescriptors.set(peerDescriptor.descriptorHash, peerDescriptor); allResolutions.set(peerDescriptor.descriptorHash, parentLocator.locatorHash); volatileDescriptors.delete(peerDescriptor.descriptorHash); } if (!peerDescriptor && virtualizedPackage.dependencies.has(peerRequest.identHash)) { virtualizedPackage.peerDependencies.delete(peerRequest.identHash); continue; } if (!peerDescriptor) peerDescriptor = structUtils.makeDescriptor(peerRequest, `missing:`); virtualizedPackage.dependencies.set(peerDescriptor.identHash, peerDescriptor); // Need to track when a virtual descriptor is set as a dependency in case // the descriptor will be consolidated. if (structUtils.isVirtualDescriptor(peerDescriptor)) { const dependents = miscUtils.getSetWithDefault(allVirtualDependents, peerDescriptor.descriptorHash); dependents.add(virtualizedPackage.locatorHash); } allIdents.set(peerDescriptor.identHash, peerDescriptor); if (peerDescriptor.range === `missing:`) missingPeerDependencies.add(peerDescriptor.identHash); nextPeerSlots.set(peerRequest.identHash, (_a = peerSlots.get(peerRequest.identHash)) !== null && _a !== void 0 ? _a : virtualizedPackage.locatorHash); } // Since we've had to add new dependencies we need to sort them all over again virtualizedPackage.dependencies = new Map(miscUtils.sortMap(virtualizedPackage.dependencies, ([identHash, descriptor]) => { return structUtils.stringifyIdent(descriptor); })); }); thirdPass.push(() => { if (!allPackages.has(virtualizedPackage.locatorHash)) return; const current = virtualStack.get(pkg.locatorHash); const next = typeof current !== `undefined` ? current + 1 : 1; virtualStack.set(pkg.locatorHash, next); resolvePeerDependencies(virtualizedPackage, nextPeerSlots, { first: false, optional: isOptional }); virtualStack.set(pkg.locatorHash, next - 1); }); fourthPass.push(() => { // Regardless of whether the initial virtualized package got deduped // or not, we now register that *this* package is now a dependent on // whatever its peer dependencies have been resolved to. We'll later // use this information to generate warnings. const finalDescriptor = parentPackage.dependencies.get(descriptor.identHash); if (typeof finalDescriptor === `undefined`) throw new Error(`Assertion failed: Expected the peer dependency to have been turned into a dependency`); const finalResolution = allResolutions.get(finalDescriptor.descriptorHash); if (typeof finalResolution === `undefined`) throw new Error(`Assertion failed: Expected the descriptor to be registered`); miscUtils.getSetWithDefault(peerDependencyDependents, finalResolution).add(parentLocator.locatorHash); if (!allPackages.has(virtualizedPackage.locatorHash)) return; for (const descriptor of virtualizedPackage.peerDependencies.values()) { const root = nextPeerSlots.get(descriptor.identHash); if (typeof root === `undefined`) throw new Error(`Assertion failed: Expected the peer dependency ident to be registered`); miscUtils.getArrayWithDefault(miscUtils.getMapWithDefault(peerDependencyLinks, root), structUtils.stringifyIdent(descriptor)).push(virtualizedPackage.locatorHash); } for (const missingPeerDependency of missingPeerDependencies) { virtualizedPackage.dependencies.delete(missingPeerDependency); } }); } for (const fn of [...firstPass, ...secondPass]) fn(); let stable; do { stable = true; for (const [physicalLocator, virtualDescriptor, virtualPackage] of newVirtualInstances) { if (!allPackages.has(virtualPackage.locatorHash)) continue; const otherVirtualInstances = miscUtils.getMapWithDefault(allVirtualInstances, physicalLocator.locatorHash); // We take all the dependencies from the new virtual instance and // generate a hash from it. By checking if this hash is already // registered, we know whether we can trim the new version. const dependencyHash = hashUtils.makeHash(...[...virtualPackage.dependencies.values()].map(descriptor => { const resolution = descriptor.range !== `missing:` ? allResolutions.get(descriptor.descriptorHash) : `missing:`; if (typeof resolution === `undefined`) throw new Error(`Assertion failed: Expected the resolution for ${structUtils.prettyDescriptor(project.configuration, descriptor)} to have been registered`); return resolution; }), // We use the identHash to disambiguate between virtual descriptors // with different base idents being resolved to the same virtual package. // Note: We don't use the descriptorHash because the whole point of duplicate // virtual descriptors is that they have different `virtual:` ranges. // This causes the virtual descriptors with different base idents // to be preserved, while the virtual package they resolve to gets deduped. virtualDescriptor.identHash); const masterDescriptor = otherVirtualInstances.get(dependencyHash); if (typeof masterDescriptor === `undefined`) { otherVirtualInstances.set(dependencyHash, virtualDescriptor); continue; } // Since we're applying multiple pass, we might have already registered // ourselves as the "master" descriptor in the previous pass. if (masterDescriptor === virtualDescriptor) continue; stable = false; allPackages.delete(virtualPackage.locatorHash); allDescriptors.delete(virtualDescriptor.descriptorHash); allResolutions.delete(virtualDescriptor.descriptorHash); accessibleLocators.delete(virtualPackage.locatorHash); const dependents = allVirtualDependents.get(virtualDescriptor.descriptorHash) || []; const allDependents = [parentPackage.locatorHash, ...dependents]; allVirtualDependents.delete(virtualDescriptor.descriptorHash); for (const dependent of allDependents) { const pkg = allPackages.get(dependent); if (typeof pkg === `undefined`) continue; pkg.dependencies.set(virtualDescriptor.identHash, masterDescriptor); } } } while (!stable); for (const fn of [...thirdPass, ...fourthPass]) { fn(); } }; for (const workspace of project.workspaces) { volatileDescriptors.delete(workspace.anchoredDescriptor.descriptorHash); resolvePeerDependencies(workspace.anchoredLocator, new Map(), { first: true, optional: false }); } let WarningType; (function (WarningType) { WarningType[WarningType["NotProvided"] = 0] = "NotProvided"; WarningType[WarningType["NotCompatible"] = 1] = "NotCompatible"; })(WarningType || (WarningType = {})); const warnings = []; for (const [rootHash, dependents] of peerDependencyDependents) { const root = allPackages.get(rootHash); if (typeof root === `undefined`) throw new Error(`Assertion failed: Expected the root to be registered`); // We retrieve the set of packages that provide complementary peer // dependencies to the one already offered by our root package, and to // whom other package. // // We simply skip if the record doesn't exist because a package may not // have any records if it didn't contribute any new peer (it only exists // if the package has at least one peer that isn't listed by its parent // packages). // const rootLinks = peerDependencyLinks.get(rootHash); if (typeof rootLinks === `undefined`) continue; for (const dependentHash of dependents) { const dependent = allPackages.get(dependentHash); // The package may have been pruned during a deduplication if (typeof dependent === `undefined`) continue; for (const [identStr, linkHashes] of rootLinks) { const ident = structUtils.parseIdent(identStr); // This dependent may have a peer dep itself, in which case it's not // the true root, and we can ignore it if (dependent.peerDependencies.has(ident.identHash)) continue; const hash = `p${hashUtils.makeHash(dependentHash, identStr, rootHash).slice(0, 5)}`; peerRequirements.set(hash, { subject: dependentHash, requested: ident, rootRequester: rootHash, allRequesters: linkHashes, }); // Note: this can be undefined when the peer dependency isn't provided at all const resolvedDescriptor = root.dependencies.get(ident.identHash); if (typeof resolvedDescriptor !== `undefined`) { const peerResolution = getPackageFromDescriptor(resolvedDescriptor); const peerVersion = (_a = peerResolution.version) !== null && _a !== void 0 ? _a : `0.0.0`; const ranges = new Set(); for (const linkHash of linkHashes) { const link = allPackages.get(linkHash); if (typeof link === `undefined`) throw new Error(`Assertion failed: Expected the link to be registered`); const peerDependency = link.peerDependencies.get(ident.identHash); if (typeof peerDependency === `undefined`) throw new Error(`Assertion failed: Expected the ident to be registered`); ranges.add(peerDependency.range); } const satisfiesAll = [...ranges].every(range => { return semverUtils.satisfiesWithPrereleases(peerVersion, range); }); if (!satisfiesAll) { warnings.push({ type: WarningType.NotCompatible, subject: dependent, requested: ident, requester: root, version: peerVersion, hash, requirementCount: linkHashes.length, }); } } else { const peerDependencyMeta = root.peerDependenciesMeta.get(identStr); if (!(peerDependencyMeta === null || peerDependencyMeta === void 0 ? void 0 : peerDependencyMeta.optional)) { warnings.push({ type: WarningType.NotProvided, subject: dependent, requested: ident, requester: root, hash, }); } } } } } const warningSortCriterias = [ warning => structUtils.prettyLocatorNoColors(warning.subject), warning => structUtils.stringifyIdent(warning.requested), warning => `${warning.type}`, ]; for (const warning of miscUtils.sortMap(warnings, warningSortCriterias)) { switch (warning.type) { case WarningType.NotProvided: { report === null || report === void 0 ? void 0 : report.reportWarning(MessageName_1.MessageName.MISSING_PEER_DEPENDENCY, `${structUtils.prettyLocator(project.configuration, warning.subject)} doesn't provide ${structUtils.prettyIdent(project.configuration, warning.requested)} (${formatUtils.pretty(project.configuration, warning.hash, formatUtils.Type.CODE)}), requested by ${structUtils.prettyIdent(project.configuration, warning.requester)}`); } break; case WarningType.NotCompatible: { const andDescendants = warning.requirementCount > 1 ? `and some of its descendants request` : `requests`; report === null || report === void 0 ? void 0 : report.reportWarning(MessageName_1.MessageName.INCOMPATIBLE_PEER_DEPENDENCY, `${structUtils.prettyLocator(project.configuration, warning.subject)} provides ${structUtils.prettyIdent(project.configuration, warning.requested)} (${formatUtils.pretty(project.configuration, warning.hash, formatUtils.Type.CODE)}) with version ${structUtils.prettyReference(project.configuration, warning.version)}, which doesn't satisfy what ${structUtils.prettyIdent(project.configuration, warning.requester)} ${andDescendants}`); } break; } } if (warnings.length > 0) { report === null || report === void 0 ? void 0 : report.reportWarning(MessageName_1.MessageName.UNNAMED, `Some peer dependencies are incorrectly met; run ${formatUtils.pretty(project.configuration, `yarn explain peer-requirements `, formatUtils.Type.CODE)} for details, where ${formatUtils.pretty(project.configuration, ``, formatUtils.Type.CODE)} is the six-letter p-prefixed code`); } } /***/ }), /***/ 6729: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProtocolResolver = exports.TAG_REGEXP = void 0; const tslib_1 = __webpack_require__(70655); const semver_1 = tslib_1.__importDefault(__webpack_require__(74451)); const semverUtils = tslib_1.__importStar(__webpack_require__(51201)); const structUtils = tslib_1.__importStar(__webpack_require__(34103)); exports.TAG_REGEXP = /^(?!v)[a-z0-9-.]+$/i; class ProtocolResolver { supportsDescriptor(descriptor, opts) { if (semverUtils.validRange(descriptor.range)) return true; if (exports.TAG_REGEXP.test(descriptor.range)) return true; return false; } supportsLocator(locator, opts) { if (semver_1.default.valid(locator.reference)) return true; if (exports.TAG_REGEXP.test(locator.reference)) return true; return false; } shouldPersistResolution(locator, opts) { return opts.resolver.shouldPersistResolution(this.forwardLocator(locator, opts), opts); } bindDescriptor(descriptor, fromLocator, opts) { return opts.resolver.bindDescriptor(this.forwardDescriptor(descriptor, opts), fromLocator, opts); } getResolutionDependencies(descriptor, opts) { return opts.resolver.getResolutionDependencies(this.forwardDescriptor(descriptor, opts), opts); } async getCandidates(descriptor, dependencies, opts) { return await opts.resolver.getCandidates(this.forwardDescriptor(descriptor, opts), dependencies, opts); } async getSatisfying(descriptor, references, opts) { return await opts.resolver.getSatisfying(this.forwardDescriptor(descriptor, opts), references, opts); } async resolve(locator, opts) { const pkg = await opts.resolver.resolve(this.forwardLocator(locator, opts), opts); return structUtils.renamePackage(pkg, locator); } forwardDescriptor(descriptor, opts) { return structUtils.makeDescriptor(descriptor, `${opts.project.configuration.get(`defaultProtocol`)}${descriptor.range}`); } forwardLocator(locator, opts) { return structUtils.makeLocator(locator, `${opts.project.configuration.get(`defaultProtocol`)}${locator.reference}`); } } exports.ProtocolResolver = ProtocolResolver; /***/ }), /***/ 50334: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Report = exports.isReportError = exports.ReportError = void 0; const stream_1 = __webpack_require__(12781); const string_decoder_1 = __webpack_require__(71576); const MessageName_1 = __webpack_require__(62755); class ReportError extends Error { constructor(code, message, reportExtra) { super(message); this.reportExtra = reportExtra; this.reportCode = code; } } exports.ReportError = ReportError; function isReportError(error) { return typeof error.reportCode !== `undefined`; } exports.isReportError = isReportError; class Report { constructor() { this.reportedInfos = new Set(); this.reportedWarnings = new Set(); this.reportedErrors = new Set(); } static progressViaCounter(max) { let current = 0; let unlock; let lock = new Promise(resolve => { unlock = resolve; }); const set = (n) => { const thisUnlock = unlock; lock = new Promise(resolve => { unlock = resolve; }); current = n; thisUnlock(); }; const tick = (n = 0) => { set(current + 1); }; const gen = (async function* () { while (current < max) { await lock; yield { progress: current / max, }; } })(); return { [Symbol.asyncIterator]() { return gen; }, set, tick, }; } reportInfoOnce(name, text, opts) { const key = opts && opts.key ? opts.key : text; if (!this.reportedInfos.has(key)) { this.reportedInfos.add(key); this.reportInfo(name, text); } } reportWarningOnce(name, text, opts) { const key = opts && opts.key ? opts.key : text; if (!this.reportedWarnings.has(key)) { this.reportedWarnings.add(key); this.reportWarning(name, text); } } reportErrorOnce(name, text, opts) { var _a; const key = opts && opts.key ? opts.key : text; if (!this.reportedErrors.has(key)) { this.reportedErrors.add(key); this.reportError(name, text); (_a = opts === null || opts === void 0 ? void 0 : opts.reportExtra) === null || _a === void 0 ? void 0 : _a.call(opts, this); } } reportExceptionOnce(error) { if (isReportError(error)) { this.reportErrorOnce(error.reportCode, error.message, { key: error, reportExtra: error.reportExtra }); } else { this.reportErrorOnce(MessageName_1.MessageName.EXCEPTION, error.stack || error.message, { key: error }); } } createStreamReporter(prefix = null) { const stream = new stream_1.PassThrough(); const decoder = new string_decoder_1.StringDecoder(); let buffer = ``; stream.on(`data`, chunk => { let chunkStr = decoder.write(chunk); let lineIndex; do { lineIndex = chunkStr.indexOf(`\n`); if (lineIndex !== -1) { const line = buffer + chunkStr.substr(0, lineIndex); chunkStr = chunkStr.substr(lineIndex + 1); buffer = ``; if (prefix !== null) { this.reportInfo(null, `${prefix} ${line}`); } else { this.reportInfo(null, line); } } } while (lineIndex !== -1); buffer += chunkStr; }); stream.on(`end`, () => { const last = decoder.end(); if (last !== ``) { if (prefix !== null) { this.reportInfo(null, `${prefix} ${last}`); } else { this.reportInfo(null, last); } } }); return stream; } } exports.Report = Report; /***/ }), /***/ 30460: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RunInstallPleaseResolver = void 0; const MessageName_1 = __webpack_require__(62755); const Report_1 = __webpack_require__(50334); class RunInstallPleaseResolver { constructor(resolver) { this.resolver = resolver; } supportsDescriptor(descriptor, opts) { return this.resolver.supportsDescriptor(descriptor, opts); } supportsLocator(locator, opts) { return this.resolver.supportsLocator(locator, opts); } shouldPersistResolution(locator, opts) { return this.resolver.shouldPersistResolution(locator, opts); } bindDescriptor(descriptor, fromLocator, opts) { return this.resolver.bindDescriptor(descriptor, fromLocator, opts); } getResolutionDependencies(descriptor, opts) { return this.resolver.getResolutionDependencies(descriptor, opts); } async getCandidates(descriptor, dependencies, opts) { throw new Report_1.ReportError(MessageName_1.MessageName.MISSING_LOCKFILE_ENTRY, `This package doesn't seem to be present in your lockfile; try to make an install to update your resolutions`); } async getSatisfying(descriptor, references, opts) { throw new Report_1.ReportError(MessageName_1.MessageName.MISSING_LOCKFILE_ENTRY, `This package doesn't seem to be present in your lockfile; try to make an install to update your resolutions`); } async resolve(locator, opts) { throw new Report_1.ReportError(MessageName_1.MessageName.MISSING_LOCKFILE_ENTRY, `This package doesn't seem to be present in your lockfile; try to make an install to update your resolutions`); } } exports.RunInstallPleaseResolver = RunInstallPleaseResolver; /***/ }), /***/ 73759: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.StreamReport = exports.formatNameWithHyperlink = exports.formatName = void 0; const tslib_1 = __webpack_require__(70655); const slice_ansi_1 = tslib_1.__importDefault(__webpack_require__(28231)); const MessageName_1 = __webpack_require__(62755); const Report_1 = __webpack_require__(50334); const formatUtils = tslib_1.__importStar(__webpack_require__(23821)); const PROGRESS_FRAMES = [`⠋`, `⠙`, `⠹`, `⠸`, `⠼`, `⠴`, `⠦`, `⠧`, `⠇`, `⠏`]; const PROGRESS_INTERVAL = 80; const BASE_FORGETTABLE_NAMES = new Set([MessageName_1.MessageName.FETCH_NOT_CACHED, MessageName_1.MessageName.UNUSED_CACHE_ENTRY]); const BASE_FORGETTABLE_BUFFER_SIZE = 5; const GROUP = process.env.GITHUB_ACTIONS ? { start: (what) => `::group::${what}\n`, end: (what) => `::endgroup::\n` } : process.env.TRAVIS ? { start: (what) => `travis_fold:start:${what}\n`, end: (what) => `travis_fold:end:${what}\n` } : process.env.GITLAB_CI ? { start: (what) => `section_start:${Math.floor(Date.now() / 1000)}:${what.toLowerCase().replace(/\W+/g, `_`)}\r\x1b[0K${what}\n`, end: (what) => `section_end:${Math.floor(Date.now() / 1000)}:${what.toLowerCase().replace(/\W+/g, `_`)}\r\x1b[0K` } : null; const now = new Date(); // We only want to support environments that will out-of-the-box accept the // characters we want to use. Others can enforce the style from the project // configuration. const supportsEmojis = [`iTerm.app`, `Apple_Terminal`].includes(process.env.TERM_PROGRAM) || !!process.env.WT_SESSION; const makeRecord = (obj) => obj; const PROGRESS_STYLES = makeRecord({ patrick: { date: [17, 3], chars: [`🍀`, `🌱`], size: 40, }, simba: { date: [19, 7], chars: [`🦁`, `🌴`], size: 40, }, jack: { date: [31, 10], chars: [`🎃`, `🦇`], size: 40, }, hogsfather: { date: [31, 12], chars: [`🎉`, `🎄`], size: 40, }, default: { chars: [`=`, `-`], size: 80, }, }); const defaultStyle = (supportsEmojis && Object.keys(PROGRESS_STYLES).find(name => { const style = PROGRESS_STYLES[name]; if (style.date && (style.date[0] !== now.getDate() || style.date[1] !== now.getMonth() + 1)) return false; return true; })) || `default`; function formatName(name, { configuration, json }) { const num = name === null ? 0 : name; const label = MessageName_1.stringifyMessageName(num); if (!json && name === null) { return formatUtils.pretty(configuration, label, `grey`); } else { return label; } } exports.formatName = formatName; function formatNameWithHyperlink(name, { configuration, json }) { const code = formatName(name, { configuration, json }); // Only print hyperlinks if allowed per configuration if (!configuration.get(`enableHyperlinks`)) return code; // Don't print hyperlinks for the generic messages if (name === null || name === MessageName_1.MessageName.UNNAMED) return code; const desc = MessageName_1.MessageName[name]; const href = `https://yarnpkg.com/advanced/error-codes#${code}---${desc}`.toLowerCase(); // We use BELL as ST because it seems that iTerm doesn't properly support // the \x1b\\ sequence described in the reference document // https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda#the-escape-sequence return `\u001b]8;;${href}\u0007${code}\u001b]8;;\u0007`; } exports.formatNameWithHyperlink = formatNameWithHyperlink; class StreamReport extends Report_1.Report { constructor({ configuration, stdout, json = false, includeFooter = true, includeLogs = !json, includeInfos = includeLogs, includeWarnings = includeLogs, forgettableBufferSize = BASE_FORGETTABLE_BUFFER_SIZE, forgettableNames = new Set(), }) { super(); this.uncommitted = new Set(); this.cacheHitCount = 0; this.cacheMissCount = 0; this.warningCount = 0; this.errorCount = 0; this.startTime = Date.now(); this.indent = 0; this.progress = new Map(); this.progressTime = 0; this.progressFrame = 0; this.progressTimeout = null; this.forgettableLines = []; formatUtils.addLogFilterSupport(this, { configuration }); this.configuration = configuration; this.forgettableBufferSize = forgettableBufferSize; this.forgettableNames = new Set([...forgettableNames, ...BASE_FORGETTABLE_NAMES]); this.includeFooter = includeFooter; this.includeInfos = includeInfos; this.includeWarnings = includeWarnings; this.json = json; this.stdout = stdout; const styleName = this.configuration.get(`progressBarStyle`) || defaultStyle; if (!Object.prototype.hasOwnProperty.call(PROGRESS_STYLES, styleName)) throw new Error(`Assertion failed: Invalid progress bar style`); this.progressStyle = PROGRESS_STYLES[styleName]; const PAD_LEFT = `➤ YN0000: ┌ `.length; const maxWidth = Math.max(0, Math.min(process.stdout.columns - PAD_LEFT, 80)); this.progressMaxScaledSize = Math.floor(this.progressStyle.size * maxWidth / 80); } static async start(opts, cb) { const report = new this(opts); const emitWarning = process.emitWarning; process.emitWarning = (message, name) => { if (typeof message !== `string`) { const error = message; message = error.message; name = name !== null && name !== void 0 ? name : error.name; } const fullMessage = typeof name !== `undefined` ? `${name}: ${message}` : message; report.reportWarning(MessageName_1.MessageName.UNNAMED, fullMessage); }; try { await cb(report); } catch (error) { report.reportExceptionOnce(error); } finally { await report.finalize(); process.emitWarning = emitWarning; } return report; } hasErrors() { return this.errorCount > 0; } exitCode() { return this.hasErrors() ? 1 : 0; } reportCacheHit(locator) { this.cacheHitCount += 1; } reportCacheMiss(locator, message) { this.cacheMissCount += 1; if (typeof message !== `undefined` && !this.configuration.get(`preferAggregateCacheInfo`)) { this.reportInfo(MessageName_1.MessageName.FETCH_NOT_CACHED, message); } } startTimerSync(what, opts, cb) { const realOpts = typeof opts === `function` ? {} : opts; const realCb = typeof opts === `function` ? opts : cb; const mark = { committed: false, action: () => { this.reportInfo(null, `┌ ${what}`); this.indent += 1; if (GROUP !== null) { this.stdout.write(GROUP.start(what)); } } }; if (realOpts.skipIfEmpty) { this.uncommitted.add(mark); } else { mark.action(); mark.committed = true; } const before = Date.now(); try { return realCb(); } catch (error) { this.reportExceptionOnce(error); throw error; } finally { const after = Date.now(); this.uncommitted.delete(mark); if (mark.committed) { this.indent -= 1; if (GROUP !== null) this.stdout.write(GROUP.end(what)); if (this.configuration.get(`enableTimers`) && after - before > 200) { this.reportInfo(null, `└ Completed in ${formatUtils.pretty(this.configuration, after - before, formatUtils.Type.DURATION)}`); } else { this.reportInfo(null, `└ Completed`); } } } } async startTimerPromise(what, opts, cb) { const realOpts = typeof opts === `function` ? {} : opts; const realCb = typeof opts === `function` ? opts : cb; const mark = { committed: false, action: () => { this.reportInfo(null, `┌ ${what}`); this.indent += 1; if (GROUP !== null) { this.stdout.write(GROUP.start(what)); } } }; if (realOpts.skipIfEmpty) { this.uncommitted.add(mark); } else { mark.action(); mark.committed = true; } const before = Date.now(); try { return await realCb(); } catch (error) { this.reportExceptionOnce(error); throw error; } finally { const after = Date.now(); this.uncommitted.delete(mark); if (mark.committed) { this.indent -= 1; if (GROUP !== null) this.stdout.write(GROUP.end(what)); if (this.configuration.get(`enableTimers`) && after - before > 200) { this.reportInfo(null, `└ Completed in ${formatUtils.pretty(this.configuration, after - before, formatUtils.Type.DURATION)}`); } else { this.reportInfo(null, `└ Completed`); } } } } async startCacheReport(cb) { const cacheInfo = this.configuration.get(`preferAggregateCacheInfo`) ? { cacheHitCount: this.cacheHitCount, cacheMissCount: this.cacheMissCount } : null; try { return await cb(); } catch (error) { this.reportExceptionOnce(error); throw error; } finally { if (cacheInfo !== null) { this.reportCacheChanges(cacheInfo); } } } reportSeparator() { if (this.indent === 0) { this.writeLineWithForgettableReset(``); } else { this.reportInfo(null, ``); } } reportInfo(name, text) { if (!this.includeInfos) return; this.commit(); const message = `${formatUtils.pretty(this.configuration, `➤`, `blueBright`)} ${this.formatNameWithHyperlink(name)}: ${this.formatIndent()}${text}`; if (!this.json) { if (this.forgettableNames.has(name)) { this.forgettableLines.push(message); if (this.forgettableLines.length > this.forgettableBufferSize) { while (this.forgettableLines.length > this.forgettableBufferSize) this.forgettableLines.shift(); this.writeLines(this.forgettableLines, { truncate: true }); } else { this.writeLine(message, { truncate: true }); } } else { this.writeLineWithForgettableReset(message); } } else { this.reportJson({ type: `info`, name, displayName: this.formatName(name), indent: this.formatIndent(), data: text }); } } reportWarning(name, text) { this.warningCount += 1; if (!this.includeWarnings) return; this.commit(); if (!this.json) { this.writeLineWithForgettableReset(`${formatUtils.pretty(this.configuration, `➤`, `yellowBright`)} ${this.formatNameWithHyperlink(name)}: ${this.formatIndent()}${text}`); } else { this.reportJson({ type: `warning`, name, displayName: this.formatName(name), indent: this.formatIndent(), data: text }); } } reportError(name, text) { this.errorCount += 1; this.commit(); if (!this.json) { this.writeLineWithForgettableReset(`${formatUtils.pretty(this.configuration, `➤`, `redBright`)} ${this.formatNameWithHyperlink(name)}: ${this.formatIndent()}${text}`, { truncate: false }); } else { this.reportJson({ type: `error`, name, displayName: this.formatName(name), indent: this.formatIndent(), data: text }); } } reportProgress(progressIt) { let stopped = false; const promise = Promise.resolve().then(async () => { const progressDefinition = { progress: 0, title: undefined, }; this.progress.set(progressIt, { definition: progressDefinition, lastScaledSize: -1, }); this.refreshProgress(-1); for await (const { progress, title } of progressIt) { if (stopped) continue; if (progressDefinition.progress === progress && progressDefinition.title === title) continue; progressDefinition.progress = progress; progressDefinition.title = title; this.refreshProgress(); } stop(); }); const stop = () => { if (stopped) return; stopped = true; this.progress.delete(progressIt); this.refreshProgress(+1); }; return { ...promise, stop }; } reportJson(data) { if (this.json) { this.writeLineWithForgettableReset(`${JSON.stringify(data)}`); } } async finalize() { if (!this.includeFooter) return; let installStatus = ``; if (this.errorCount > 0) installStatus = `Failed with errors`; else if (this.warningCount > 0) installStatus = `Done with warnings`; else installStatus = `Done`; const timing = formatUtils.pretty(this.configuration, Date.now() - this.startTime, formatUtils.Type.DURATION); const message = this.configuration.get(`enableTimers`) ? `${installStatus} in ${timing}` : installStatus; if (this.errorCount > 0) { this.reportError(MessageName_1.MessageName.UNNAMED, message); } else if (this.warningCount > 0) { this.reportWarning(MessageName_1.MessageName.UNNAMED, message); } else { this.reportInfo(MessageName_1.MessageName.UNNAMED, message); } } writeLine(str, { truncate } = {}) { this.clearProgress({ clear: true }); this.stdout.write(`${this.truncate(str, { truncate })}\n`); this.writeProgress(); } writeLineWithForgettableReset(str, { truncate } = {}) { this.forgettableLines = []; this.writeLine(str, { truncate }); } writeLines(lines, { truncate } = {}) { this.clearProgress({ delta: lines.length }); for (const line of lines) this.stdout.write(`${this.truncate(line, { truncate })}\n`); this.writeProgress(); } reportCacheChanges({ cacheHitCount, cacheMissCount }) { const cacheHitDelta = this.cacheHitCount - cacheHitCount; const cacheMissDelta = this.cacheMissCount - cacheMissCount; if (cacheHitDelta === 0 && cacheMissDelta === 0) return; let fetchStatus = ``; if (this.cacheHitCount > 1) fetchStatus += `${this.cacheHitCount} packages were already cached`; else if (this.cacheHitCount === 1) fetchStatus += ` - one package was already cached`; else fetchStatus += `No packages were cached`; if (this.cacheHitCount > 0) { if (this.cacheMissCount > 1) { fetchStatus += `, ${this.cacheMissCount} had to be fetched`; } else if (this.cacheMissCount === 1) { fetchStatus += `, one had to be fetched`; } } else { if (this.cacheMissCount > 1) { fetchStatus += ` - ${this.cacheMissCount} packages had to be fetched`; } else if (this.cacheMissCount === 1) { fetchStatus += ` - one package had to be fetched`; } } this.reportInfo(MessageName_1.MessageName.FETCH_NOT_CACHED, fetchStatus); } commit() { const marks = this.uncommitted; this.uncommitted = new Set(); for (const mark of marks) { mark.committed = true; mark.action(); } } clearProgress({ delta = 0, clear = false }) { if (!this.configuration.get(`enableProgressBars`) || this.json) return; if (this.progress.size + delta > 0) { this.stdout.write(`\x1b[${this.progress.size + delta}A`); if (delta > 0 || clear) { this.stdout.write(`\x1b[0J`); } } } writeProgress() { if (!this.configuration.get(`enableProgressBars`) || this.json) return; if (this.progressTimeout !== null) clearTimeout(this.progressTimeout); this.progressTimeout = null; if (this.progress.size === 0) return; const now = Date.now(); if (now - this.progressTime > PROGRESS_INTERVAL) { this.progressFrame = (this.progressFrame + 1) % PROGRESS_FRAMES.length; this.progressTime = now; } const spinner = PROGRESS_FRAMES[this.progressFrame]; for (const progress of this.progress.values()) { const ok = this.progressStyle.chars[0].repeat(progress.lastScaledSize); const ko = this.progressStyle.chars[1].repeat(this.progressMaxScaledSize - progress.lastScaledSize); this.stdout.write(`${formatUtils.pretty(this.configuration, `➤`, `blueBright`)} ${this.formatName(null)}: ${spinner} ${ok}${ko}\n`); } this.progressTimeout = setTimeout(() => { this.refreshProgress(); }, PROGRESS_INTERVAL); } refreshProgress(delta = 0) { let needsUpdate = false; if (this.progress.size === 0) { needsUpdate = true; } else { for (const progress of this.progress.values()) { const refreshedScaledSize = Math.trunc(this.progressMaxScaledSize * progress.definition.progress); const previousScaledSize = progress.lastScaledSize; progress.lastScaledSize = refreshedScaledSize; if (refreshedScaledSize !== previousScaledSize) { needsUpdate = true; break; } } } if (needsUpdate) { this.clearProgress({ delta }); this.writeProgress(); } } truncate(str, { truncate } = {}) { if (!this.configuration.get(`enableProgressBars`)) truncate = false; if (typeof truncate === `undefined`) truncate = this.configuration.get(`preferTruncatedLines`); // The -1 is to account for terminals that would wrap after // the last column rather before the first overwrite if (truncate) str = slice_ansi_1.default(str, 0, process.stdout.columns - 1); return str; } formatName(name) { return formatName(name, { configuration: this.configuration, json: this.json, }); } formatNameWithHyperlink(name) { return formatNameWithHyperlink(name, { configuration: this.configuration, json: this.json, }); } formatIndent() { return `│ `.repeat(this.indent); } } exports.StreamReport = StreamReport; /***/ }), /***/ 58166: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TelemetryManager = exports.MetricName = void 0; const tslib_1 = __webpack_require__(70655); const fslib_1 = __webpack_require__(91794); const httpUtils = tslib_1.__importStar(__webpack_require__(57392)); const miscUtils = tslib_1.__importStar(__webpack_require__(63111)); var MetricName; (function (MetricName) { MetricName["VERSION"] = "version"; MetricName["COMMAND_NAME"] = "commandName"; MetricName["PLUGIN_NAME"] = "pluginName"; MetricName["INSTALL_COUNT"] = "installCount"; MetricName["PROJECT_COUNT"] = "projectCount"; MetricName["WORKSPACE_COUNT"] = "workspaceCount"; MetricName["DEPENDENCY_COUNT"] = "dependencyCount"; MetricName["EXTENSION"] = "packageExtension"; })(MetricName = exports.MetricName || (exports.MetricName = {})); class TelemetryManager { constructor(configuration, accountId) { this.values = new Map(); this.hits = new Map(); this.enumerators = new Map(); this.configuration = configuration; const registryFile = this.getRegistryPath(); this.isNew = !fslib_1.xfs.existsSync(registryFile); this.sendReport(accountId); this.startBuffer(); } reportVersion(value) { this.reportValue(MetricName.VERSION, value); } reportCommandName(value) { this.reportValue(MetricName.COMMAND_NAME, value || ``); } reportPluginName(value) { this.reportValue(MetricName.PLUGIN_NAME, value); } reportProject(cwd) { this.reportEnumerator(MetricName.PROJECT_COUNT, cwd); } reportInstall(nodeLinker) { this.reportHit(MetricName.INSTALL_COUNT, nodeLinker); } reportPackageExtension(value) { this.reportValue(MetricName.EXTENSION, value); } reportWorkspaceCount(count) { this.reportValue(MetricName.WORKSPACE_COUNT, String(count)); } reportDependencyCount(count) { this.reportValue(MetricName.DEPENDENCY_COUNT, String(count)); } reportValue(metric, value) { miscUtils.getSetWithDefault(this.values, metric).add(value); } reportEnumerator(metric, value) { miscUtils.getSetWithDefault(this.enumerators, metric).add(value); } reportHit(metric, extra = `*`) { const ns = miscUtils.getMapWithDefault(this.hits, metric); const current = miscUtils.getFactoryWithDefault(ns, extra, () => 0); ns.set(extra, current + 1); } getRegistryPath() { const registryFile = this.configuration.get(`globalFolder`); return fslib_1.ppath.join(registryFile, `telemetry.json`); } sendReport(accountId) { var _a, _b, _c; const registryFile = this.getRegistryPath(); let content; try { content = fslib_1.xfs.readJsonSync(registryFile); } catch (_d) { content = {}; } const now = Date.now(); const interval = this.configuration.get(`telemetryInterval`) * 24 * 60 * 60 * 1000; const lastUpdate = (_a = content.lastUpdate) !== null && _a !== void 0 ? _a : now + interval + Math.floor(interval * Math.random()); const nextUpdate = lastUpdate + interval; if (nextUpdate > now && content.lastUpdate != null) return; try { fslib_1.xfs.mkdirSync(fslib_1.ppath.dirname(registryFile), { recursive: true }); fslib_1.xfs.writeJsonSync(registryFile, { lastUpdate: now }); } catch (_e) { // In some cases this location is read-only. Too bad 🤷‍♀️ return; } if (nextUpdate > now) return; if (!content.blocks) return; for (const [userId, block] of Object.entries((_b = content.blocks) !== null && _b !== void 0 ? _b : {})) { if (Object.keys(block).length === 0) continue; const upload = block; upload.userId = userId; for (const key of Object.keys((_c = upload.enumerators) !== null && _c !== void 0 ? _c : {})) upload.enumerators[key] = upload.enumerators[key].length; const rawUrl = `https://browser-http-intake.logs.datadoghq.eu/v1/input/${accountId}?ddsource=yarn`; httpUtils.post(rawUrl, upload, { configuration: this.configuration, }).catch(() => { // Nothing we can do }); } } applyChanges() { var _a, _b, _c, _d, _e, _f, _g, _h, _j; const registryFile = this.getRegistryPath(); let content; try { content = fslib_1.xfs.readJsonSync(registryFile); } catch (_k) { content = {}; } const userId = (_a = this.configuration.get(`telemetryUserId`)) !== null && _a !== void 0 ? _a : `*`; const blocks = content.blocks = (_b = content.blocks) !== null && _b !== void 0 ? _b : {}; const block = blocks[userId] = (_c = blocks[userId]) !== null && _c !== void 0 ? _c : {}; for (const key of this.hits.keys()) { const store = block.hits = (_d = block.hits) !== null && _d !== void 0 ? _d : {}; const ns = store[key] = (_e = store[key]) !== null && _e !== void 0 ? _e : {}; for (const [extra, value] of this.hits.get(key)) { ns[extra] = ((_f = ns[extra]) !== null && _f !== void 0 ? _f : 0) + value; } } for (const field of [`values`, `enumerators`]) { for (const key of this[field].keys()) { const store = block[field] = (_g = block[field]) !== null && _g !== void 0 ? _g : {}; store[key] = [...new Set([ ...(_h = store[key]) !== null && _h !== void 0 ? _h : [], ...(_j = this[field].get(key)) !== null && _j !== void 0 ? _j : [], ])]; } } fslib_1.xfs.mkdirSync(fslib_1.ppath.dirname(registryFile), { recursive: true }); fslib_1.xfs.writeJsonSync(registryFile, content); } startBuffer() { process.on(`exit`, () => { try { this.applyChanges(); } catch (_a) { // Explicitly ignore errors } }); } } exports.TelemetryManager = TelemetryManager; /***/ }), /***/ 6059: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ThrowReport = void 0; const Report_1 = __webpack_require__(50334); class ThrowReport extends Report_1.Report { reportCacheHit(locator) { } reportCacheMiss(locator) { } startTimerSync(what, opts, cb) { const realCb = typeof opts === `function` ? opts : cb; return realCb(); } async startTimerPromise(what, opts, cb) { const realCb = typeof opts === `function` ? opts : cb; return await realCb(); } async startCacheReport(cb) { return await cb(); } reportSeparator() { } reportInfo(name, text) { } reportWarning(name, text) { } reportError(name, text) { } reportProgress(progress) { const promise = Promise.resolve().then(async () => { // eslint-disable-next-line no-empty-pattern for await (const {} of progress) { // No need to do anything; we just want to consume the progress events } }); const stop = () => { // Nothing to stop }; return { ...promise, stop }; } reportJson(data) { // Just ignore the json output } async finalize() { } } exports.ThrowReport = ThrowReport; /***/ }), /***/ 7100: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.VirtualFetcher = void 0; const tslib_1 = __webpack_require__(70655); const fslib_1 = __webpack_require__(91794); const structUtils = tslib_1.__importStar(__webpack_require__(34103)); class VirtualFetcher { supports(locator) { if (!locator.reference.startsWith(`virtual:`)) return false; return true; } getLocalPath(locator, opts) { const splitPoint = locator.reference.indexOf(`#`); if (splitPoint === -1) throw new Error(`Invalid virtual package reference`); const nextReference = locator.reference.slice(splitPoint + 1); const nextLocator = structUtils.makeLocator(locator, nextReference); return opts.fetcher.getLocalPath(nextLocator, opts); } async fetch(locator, opts) { const splitPoint = locator.reference.indexOf(`#`); if (splitPoint === -1) throw new Error(`Invalid virtual package reference`); const nextReference = locator.reference.slice(splitPoint + 1); const nextLocator = structUtils.makeLocator(locator, nextReference); const parentFetch = await opts.fetcher.fetch(nextLocator, opts); return await this.ensureVirtualLink(locator, parentFetch, opts); } getLocatorFilename(locator) { return structUtils.slugifyLocator(locator); } async ensureVirtualLink(locator, sourceFetch, opts) { const to = sourceFetch.packageFs.getRealPath(); const virtualFolder = opts.project.configuration.get(`virtualFolder`); const virtualName = this.getLocatorFilename(locator); const virtualPath = fslib_1.VirtualFS.makeVirtualPath(virtualFolder, virtualName, to); // We then use an alias to tell anyone that asks us that we're operating within the virtual folder, while still using the same old fs const aliasFs = new fslib_1.AliasFS(virtualPath, { baseFs: sourceFetch.packageFs, pathUtils: fslib_1.ppath }); return { ...sourceFetch, packageFs: aliasFs }; } } exports.VirtualFetcher = VirtualFetcher; /***/ }), /***/ 55605: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.VirtualResolver = void 0; class VirtualResolver { static isVirtualDescriptor(descriptor) { if (!descriptor.range.startsWith(VirtualResolver.protocol)) return false; return true; } static isVirtualLocator(locator) { if (!locator.reference.startsWith(VirtualResolver.protocol)) return false; return true; } supportsDescriptor(descriptor, opts) { return VirtualResolver.isVirtualDescriptor(descriptor); } supportsLocator(locator, opts) { return VirtualResolver.isVirtualLocator(locator); } shouldPersistResolution(locator, opts) { return false; } bindDescriptor(descriptor, locator, opts) { // It's unsupported because packages inside the dependency tree should // only become virtual AFTER they have all been resolved, by which point // you shouldn't need to call `bindDescriptor` anymore. throw new Error(`Assertion failed: calling "bindDescriptor" on a virtual descriptor is unsupported`); } getResolutionDependencies(descriptor, opts) { // It's unsupported because packages inside the dependency tree should // only become virtual AFTER they have all been resolved, by which point // you shouldn't need to call `bindDescriptor` anymore. throw new Error(`Assertion failed: calling "getResolutionDependencies" on a virtual descriptor is unsupported`); } async getCandidates(descriptor, dependencies, opts) { // It's unsupported because packages inside the dependency tree should // only become virtual AFTER they have all been resolved, by which point // you shouldn't need to call `getCandidates` anymore. throw new Error(`Assertion failed: calling "getCandidates" on a virtual descriptor is unsupported`); } async getSatisfying(descriptor, candidates, opts) { // It's unsupported because packages inside the dependency tree should // only become virtual AFTER they have all been resolved, by which point // you shouldn't need to call `getSatisfying` anymore. throw new Error(`Assertion failed: calling "getSatisfying" on a virtual descriptor is unsupported`); } async resolve(locator, opts) { // It's unsupported because packages inside the dependency tree should // only become virtual AFTER they have all been resolved, by which point // you shouldn't need to call `resolve` anymore. throw new Error(`Assertion failed: calling "resolve" on a virtual locator is unsupported`); } } exports.VirtualResolver = VirtualResolver; VirtualResolver.protocol = `virtual:`; /***/ }), /***/ 2234: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Workspace = void 0; const tslib_1 = __webpack_require__(70655); const fslib_1 = __webpack_require__(91794); const globby_1 = tslib_1.__importDefault(__webpack_require__(25839)); const semver_1 = tslib_1.__importDefault(__webpack_require__(74451)); const Manifest_1 = __webpack_require__(11658); const WorkspaceResolver_1 = __webpack_require__(83740); const hashUtils = tslib_1.__importStar(__webpack_require__(73279)); const structUtils = tslib_1.__importStar(__webpack_require__(34103)); class Workspace { constructor(workspaceCwd, { project }) { this.workspacesCwds = new Set(); // Generated at resolution; basically dependencies + devDependencies + child workspaces this.dependencies = new Map(); this.project = project; this.cwd = workspaceCwd; } async setup() { // @ts-expect-error: It's ok to initialize it now this.manifest = fslib_1.xfs.existsSync(fslib_1.ppath.join(this.cwd, Manifest_1.Manifest.fileName)) ? await Manifest_1.Manifest.find(this.cwd) : new Manifest_1.Manifest(); // We use ppath.relative to guarantee that the default hash will be consistent even if the project is installed on different OS / path // @ts-expect-error: It's ok to initialize it now, even if it's readonly (setup is called right after construction) this.relativeCwd = fslib_1.ppath.relative(this.project.cwd, this.cwd) || fslib_1.PortablePath.dot; const ident = this.manifest.name ? this.manifest.name : structUtils.makeIdent(null, `${this.computeCandidateName()}-${hashUtils.makeHash(this.relativeCwd).substr(0, 6)}`); const reference = this.manifest.version ? this.manifest.version : `0.0.0`; // @ts-expect-error: It's ok to initialize it now, even if it's readonly (setup is called right after construction) this.locator = structUtils.makeLocator(ident, reference); // @ts-expect-error: It's ok to initialize it now, even if it's readonly (setup is called right after construction) this.anchoredDescriptor = structUtils.makeDescriptor(this.locator, `${WorkspaceResolver_1.WorkspaceResolver.protocol}${this.relativeCwd}`); // @ts-expect-error: It's ok to initialize it now, even if it's readonly (setup is called right after construction) this.anchoredLocator = structUtils.makeLocator(this.locator, `${WorkspaceResolver_1.WorkspaceResolver.protocol}${this.relativeCwd}`); const patterns = this.manifest.workspaceDefinitions.map(({ pattern }) => pattern); const relativeCwds = await globby_1.default(patterns, { absolute: true, cwd: fslib_1.npath.fromPortablePath(this.cwd), expandDirectories: false, onlyDirectories: true, onlyFiles: false, ignore: [`**/node_modules`, `**/.git`, `**/.yarn`], }); // It seems that the return value of globby isn't in any guaranteed order - not even the directory listing order relativeCwds.sort(); for (const relativeCwd of relativeCwds) { const candidateCwd = fslib_1.ppath.resolve(this.cwd, fslib_1.npath.toPortablePath(relativeCwd)); if (fslib_1.xfs.existsSync(fslib_1.ppath.join(candidateCwd, `package.json`))) { this.workspacesCwds.add(candidateCwd); } } } accepts(range) { const protocolIndex = range.indexOf(`:`); const protocol = protocolIndex !== -1 ? range.slice(0, protocolIndex + 1) : null; const pathname = protocolIndex !== -1 ? range.slice(protocolIndex + 1) : range; if (protocol === WorkspaceResolver_1.WorkspaceResolver.protocol && fslib_1.ppath.normalize(pathname) === this.relativeCwd) return true; if (protocol === WorkspaceResolver_1.WorkspaceResolver.protocol && pathname === `*`) return true; if (!semver_1.default.validRange(pathname)) return false; if (protocol === WorkspaceResolver_1.WorkspaceResolver.protocol) return semver_1.default.satisfies(this.manifest.version !== null ? this.manifest.version : `0.0.0`, pathname); if (!this.project.configuration.get(`enableTransparentWorkspaces`)) return false; if (this.manifest.version !== null) return semver_1.default.satisfies(this.manifest.version, pathname); return false; } computeCandidateName() { if (this.cwd === this.project.cwd) { return `root-workspace`; } else { return `${fslib_1.ppath.basename(this.cwd)}` || `unnamed-workspace`; } } async persistManifest() { const data = {}; this.manifest.exportTo(data); const path = fslib_1.ppath.join(this.cwd, Manifest_1.Manifest.fileName); const content = `${JSON.stringify(data, null, this.manifest.indent)}\n`; await fslib_1.xfs.changeFilePromise(path, content, { automaticNewlines: true, }); } } exports.Workspace = Workspace; /***/ }), /***/ 2925: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WorkspaceFetcher = void 0; const fslib_1 = __webpack_require__(91794); const WorkspaceResolver_1 = __webpack_require__(83740); class WorkspaceFetcher { supports(locator) { if (!locator.reference.startsWith(WorkspaceResolver_1.WorkspaceResolver.protocol)) return false; return true; } getLocalPath(locator, opts) { return this.getWorkspace(locator, opts).cwd; } async fetch(locator, opts) { const sourcePath = this.getWorkspace(locator, opts).cwd; return { packageFs: new fslib_1.CwdFS(sourcePath), prefixPath: fslib_1.PortablePath.dot, localPath: sourcePath }; } getWorkspace(locator, opts) { return opts.project.getWorkspaceByCwd(locator.reference.slice(WorkspaceResolver_1.WorkspaceResolver.protocol.length)); } } exports.WorkspaceFetcher = WorkspaceFetcher; /***/ }), /***/ 83740: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WorkspaceResolver = void 0; const types_1 = __webpack_require__(79588); class WorkspaceResolver { supportsDescriptor(descriptor, opts) { if (descriptor.range.startsWith(WorkspaceResolver.protocol)) return true; const workspace = opts.project.tryWorkspaceByDescriptor(descriptor); if (workspace !== null) return true; return false; } supportsLocator(locator, opts) { if (!locator.reference.startsWith(WorkspaceResolver.protocol)) return false; return true; } shouldPersistResolution(locator, opts) { return false; } bindDescriptor(descriptor, fromLocator, opts) { return descriptor; } getResolutionDependencies(descriptor, opts) { return []; } async getCandidates(descriptor, dependencies, opts) { const workspace = opts.project.getWorkspaceByDescriptor(descriptor); return [workspace.anchoredLocator]; } async getSatisfying(descriptor, references, opts) { return null; } async resolve(locator, opts) { const workspace = opts.project.getWorkspaceByCwd(locator.reference.slice(WorkspaceResolver.protocol.length)); return { ...locator, version: workspace.manifest.version || `0.0.0`, languageName: `unknown`, linkType: types_1.LinkType.SOFT, dependencies: new Map([...workspace.manifest.dependencies, ...workspace.manifest.devDependencies]), peerDependencies: new Map([...workspace.manifest.peerDependencies]), dependenciesMeta: workspace.manifest.dependenciesMeta, peerDependenciesMeta: workspace.manifest.peerDependenciesMeta, bin: workspace.manifest.bin, }; } } exports.WorkspaceResolver = WorkspaceResolver; WorkspaceResolver.protocol = `workspace:`; /***/ }), /***/ 71774: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.YarnVersion = void 0; exports.YarnVersion = typeof YARN_VERSION !== `undefined` ? YARN_VERSION : null; /***/ }), /***/ 12915: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.execvp = exports.pipevp = exports.EndStrategy = void 0; const tslib_1 = __webpack_require__(70655); const fslib_1 = __webpack_require__(91794); const cross_spawn_1 = tslib_1.__importDefault(__webpack_require__(19789)); var EndStrategy; (function (EndStrategy) { EndStrategy[EndStrategy["Never"] = 0] = "Never"; EndStrategy[EndStrategy["ErrorCode"] = 1] = "ErrorCode"; EndStrategy[EndStrategy["Always"] = 2] = "Always"; })(EndStrategy = exports.EndStrategy || (exports.EndStrategy = {})); function hasFd(stream) { // @ts-expect-error: Not sure how to typecheck this field return stream !== null && typeof stream.fd === `number`; } function sigintHandler() { // We don't want SIGINT to kill our process; we want it to kill the // innermost process, whose end will cause our own to exit. } // Rather than attaching one SIGINT handler for each process, we // attach a single one and use a refcount to detect once it's no // longer needed. let sigintRefCount = 0; async function pipevp(fileName, args, { cwd, env = process.env, strict = false, stdin = null, stdout, stderr, end = EndStrategy.Always }) { const stdio = [`pipe`, `pipe`, `pipe`]; if (stdin === null) stdio[0] = `ignore`; else if (hasFd(stdin)) stdio[0] = stdin; if (hasFd(stdout)) stdio[1] = stdout; if (hasFd(stderr)) stdio[2] = stderr; if (sigintRefCount++ === 0) process.on(`SIGINT`, sigintHandler); const child = cross_spawn_1.default(fileName, args, { cwd: fslib_1.npath.fromPortablePath(cwd), env: { ...env, PWD: fslib_1.npath.fromPortablePath(cwd), }, stdio, }); if (!hasFd(stdin) && stdin !== null) stdin.pipe(child.stdin); if (!hasFd(stdout)) child.stdout.pipe(stdout, { end: false }); if (!hasFd(stderr)) child.stderr.pipe(stderr, { end: false }); const closeStreams = () => { for (const stream of new Set([stdout, stderr])) { if (!hasFd(stream)) { stream.end(); } } }; return new Promise((resolve, reject) => { child.on(`error`, error => { if (--sigintRefCount === 0) process.off(`SIGINT`, sigintHandler); if (end === EndStrategy.Always || end === EndStrategy.ErrorCode) closeStreams(); reject(error); }); child.on(`close`, (code, sig) => { if (--sigintRefCount === 0) process.off(`SIGINT`, sigintHandler); if (end === EndStrategy.Always || (end === EndStrategy.ErrorCode && code > 0)) closeStreams(); if (code === 0 || !strict) { resolve({ code: getExitCode(code, sig) }); } else if (code !== null) { reject(new Error(`Child "${fileName}" exited with exit code ${code}`)); } else { reject(new Error(`Child "${fileName}" exited with signal ${sig}`)); } }); }); } exports.pipevp = pipevp; async function execvp(fileName, args, { cwd, env = process.env, encoding = `utf8`, strict = false }) { const stdio = [`ignore`, `pipe`, `pipe`]; const stdoutChunks = []; const stderrChunks = []; const nativeCwd = fslib_1.npath.fromPortablePath(cwd); if (typeof env.PWD !== `undefined`) env = { ...env, PWD: nativeCwd }; const subprocess = cross_spawn_1.default(fileName, args, { cwd: nativeCwd, env, stdio, }); subprocess.stdout.on(`data`, (chunk) => { stdoutChunks.push(chunk); }); subprocess.stderr.on(`data`, (chunk) => { stderrChunks.push(chunk); }); return await new Promise((resolve, reject) => { subprocess.on(`error`, reject); subprocess.on(`close`, (code, signal) => { const stdout = encoding === `buffer` ? Buffer.concat(stdoutChunks) : Buffer.concat(stdoutChunks).toString(encoding); const stderr = encoding === `buffer` ? Buffer.concat(stderrChunks) : Buffer.concat(stderrChunks).toString(encoding); if (code === 0 || !strict) { resolve({ code: getExitCode(code, signal), stdout, stderr, }); } else { reject(Object.assign(new Error(`Child "${fileName}" exited with exit code ${code}\n\n${stderr}`), { code: getExitCode(code, signal), stdout, stderr, })); } }); }); } exports.execvp = execvp; const signalToCodeMap = new Map([ [`SIGINT`, 2], [`SIGQUIT`, 3], [`SIGKILL`, 9], [`SIGTERM`, 15], ]); function getExitCode(code, signal) { const signalCode = signalToCodeMap.get(signal); if (typeof signalCode !== `undefined`) { return 128 + signalCode; } else { return code !== null && code !== void 0 ? code : 1; } } /***/ }), /***/ 13061: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isFolderInside = exports.getHomeFolder = exports.getDefaultGlobalFolder = void 0; const fslib_1 = __webpack_require__(91794); const os_1 = __webpack_require__(22037); function getDefaultGlobalFolder() { if (process.platform === `win32`) { const base = fslib_1.npath.toPortablePath(process.env.LOCALAPPDATA || fslib_1.npath.join(os_1.homedir(), `AppData`, `Local`)); return fslib_1.ppath.resolve(base, `Yarn/Berry`); } if (process.env.XDG_DATA_HOME) { const base = fslib_1.npath.toPortablePath(process.env.XDG_DATA_HOME); return fslib_1.ppath.resolve(base, `yarn/berry`); } return fslib_1.ppath.resolve(getHomeFolder(), `.yarn/berry`); } exports.getDefaultGlobalFolder = getDefaultGlobalFolder; function getHomeFolder() { return fslib_1.npath.toPortablePath(os_1.homedir() || `/usr/local/share`); } exports.getHomeFolder = getHomeFolder; function isFolderInside(target, parent) { const relative = fslib_1.ppath.relative(parent, target); return relative && !relative.startsWith(`..`) && !fslib_1.ppath.isAbsolute(relative); } exports.isFolderInside = isFolderInside; /***/ }), /***/ 23821: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.addLogFilterSupport = exports.LogLevel = exports.mark = exports.json = exports.prettyList = exports.pretty = exports.applyColor = exports.applyStyle = exports.tuple = exports.supportsHyperlinks = exports.supportsColor = exports.Style = exports.Type = void 0; const tslib_1 = __webpack_require__(70655); const fslib_1 = __webpack_require__(91794); const chalk_1 = tslib_1.__importDefault(__webpack_require__(59084)); const MessageName_1 = __webpack_require__(62755); const miscUtils = tslib_1.__importStar(__webpack_require__(63111)); const structUtils = tslib_1.__importStar(__webpack_require__(34103)); const types_1 = __webpack_require__(79588); var Type; (function (Type) { Type["NO_HINT"] = "NO_HINT"; Type["NULL"] = "NULL"; Type["SCOPE"] = "SCOPE"; Type["NAME"] = "NAME"; Type["RANGE"] = "RANGE"; Type["REFERENCE"] = "REFERENCE"; Type["NUMBER"] = "NUMBER"; Type["PATH"] = "PATH"; Type["URL"] = "URL"; Type["ADDED"] = "ADDED"; Type["REMOVED"] = "REMOVED"; Type["CODE"] = "CODE"; Type["DURATION"] = "DURATION"; Type["SIZE"] = "SIZE"; Type["IDENT"] = "IDENT"; Type["DESCRIPTOR"] = "DESCRIPTOR"; Type["LOCATOR"] = "LOCATOR"; Type["RESOLUTION"] = "RESOLUTION"; Type["DEPENDENT"] = "DEPENDENT"; Type["PACKAGE_EXTENSION"] = "PACKAGE_EXTENSION"; })(Type = exports.Type || (exports.Type = {})); var Style; (function (Style) { Style[Style["BOLD"] = 2] = "BOLD"; })(Style = exports.Style || (exports.Style = {})); const chalkOptions = process.env.GITHUB_ACTIONS ? { level: 2 } : chalk_1.default.supportsColor ? { level: chalk_1.default.supportsColor.level } : { level: 0 }; exports.supportsColor = chalkOptions.level !== 0; exports.supportsHyperlinks = exports.supportsColor && !process.env.GITHUB_ACTIONS; const chalkInstance = new chalk_1.default.Instance(chalkOptions); const colors = new Map([ [Type.NO_HINT, null], [Type.NULL, [`#a853b5`, 129]], [Type.SCOPE, [`#d75f00`, 166]], [Type.NAME, [`#d7875f`, 173]], [Type.RANGE, [`#00afaf`, 37]], [Type.REFERENCE, [`#87afff`, 111]], [Type.NUMBER, [`#ffd700`, 220]], [Type.PATH, [`#d75fd7`, 170]], [Type.URL, [`#d75fd7`, 170]], [Type.ADDED, [`#5faf00`, 70]], [Type.REMOVED, [`#d70000`, 160]], [Type.CODE, [`#87afff`, 111]], [Type.SIZE, [`#ffd700`, 220]], ]); // Just to make sure that the individual fields of the transform map have // compatible parameter types, without upcasting the map to a too generic type // // We also take the opportunity to downcast the configuration into `any`, // otherwise TypeScript will detect a circular reference and won't allow us to // properly type the `format` method from Configuration. Since transforms are // internal to this file, it should be fine. const validateTransform = (spec) => spec; const transforms = { [Type.NUMBER]: validateTransform({ pretty: (configuration, value) => { return `${value}`; }, json: (value) => { return value; }, }), [Type.IDENT]: validateTransform({ pretty: (configuration, ident) => { return structUtils.prettyIdent(configuration, ident); }, json: (ident) => { return structUtils.stringifyIdent(ident); }, }), [Type.LOCATOR]: validateTransform({ pretty: (configuration, locator) => { return structUtils.prettyLocator(configuration, locator); }, json: (locator) => { return structUtils.stringifyLocator(locator); }, }), [Type.DESCRIPTOR]: validateTransform({ pretty: (configuration, descriptor) => { return structUtils.prettyDescriptor(configuration, descriptor); }, json: (descriptor) => { return structUtils.stringifyDescriptor(descriptor); }, }), [Type.RESOLUTION]: validateTransform({ pretty: (configuration, { descriptor, locator }) => { return structUtils.prettyResolution(configuration, descriptor, locator); }, json: ({ descriptor, locator }) => { return { descriptor: structUtils.stringifyDescriptor(descriptor), locator: locator !== null ? structUtils.stringifyLocator(locator) : null, }; }, }), [Type.DEPENDENT]: validateTransform({ pretty: (configuration, { locator, descriptor }) => { return structUtils.prettyDependent(configuration, locator, descriptor); }, json: ({ locator, descriptor }) => { return { locator: structUtils.stringifyLocator(locator), descriptor: structUtils.stringifyDescriptor(descriptor), }; }, }), [Type.PACKAGE_EXTENSION]: validateTransform({ pretty: (configuration, packageExtension) => { switch (packageExtension.type) { case types_1.PackageExtensionType.Dependency: return `${structUtils.prettyIdent(configuration, packageExtension.parentDescriptor)} ➤ ${applyColor(configuration, `dependencies`, Type.CODE)} ➤ ${structUtils.prettyIdent(configuration, packageExtension.descriptor)}`; case types_1.PackageExtensionType.PeerDependency: return `${structUtils.prettyIdent(configuration, packageExtension.parentDescriptor)} ➤ ${applyColor(configuration, `peerDependencies`, Type.CODE)} ➤ ${structUtils.prettyIdent(configuration, packageExtension.descriptor)}`; case types_1.PackageExtensionType.PeerDependencyMeta: return `${structUtils.prettyIdent(configuration, packageExtension.parentDescriptor)} ➤ ${applyColor(configuration, `peerDependenciesMeta`, Type.CODE)} ➤ ${structUtils.prettyIdent(configuration, structUtils.parseIdent(packageExtension.selector))} ➤ ${applyColor(configuration, packageExtension.key, Type.CODE)}`; default: throw new Error(`Assertion failed: Unsupported package extension type: ${packageExtension.type}`); } }, json: (packageExtension) => { switch (packageExtension.type) { case types_1.PackageExtensionType.Dependency: return `${structUtils.stringifyIdent(packageExtension.parentDescriptor)} > ${structUtils.stringifyIdent(packageExtension.descriptor)}`; case types_1.PackageExtensionType.PeerDependency: return `${structUtils.stringifyIdent(packageExtension.parentDescriptor)} >> ${structUtils.stringifyIdent(packageExtension.descriptor)}`; case types_1.PackageExtensionType.PeerDependencyMeta: return `${structUtils.stringifyIdent(packageExtension.parentDescriptor)} >> ${packageExtension.selector} / ${packageExtension.key}`; default: throw new Error(`Assertion failed: Unsupported package extension type: ${packageExtension.type}`); } }, }), [Type.DURATION]: validateTransform({ pretty: (configuration, duration) => { if (duration > 1000 * 60) { const minutes = Math.floor(duration / 1000 / 60); const seconds = Math.ceil((duration - minutes * 60 * 1000) / 1000); return seconds === 0 ? `${minutes}m` : `${minutes}m ${seconds}s`; } else { const seconds = Math.floor(duration / 1000); const milliseconds = duration - seconds * 1000; return milliseconds === 0 ? `${seconds}s` : `${seconds}s ${milliseconds}ms`; } }, json: (duration) => { return duration; }, }), [Type.SIZE]: validateTransform({ pretty: (configuration, size) => { const thresholds = [`KB`, `MB`, `GB`, `TB`]; let power = thresholds.length; while (power > 1 && size < 1024 ** power) power -= 1; const factor = 1024 ** power; const value = Math.floor(size * 100 / factor) / 100; return applyColor(configuration, `${value} ${thresholds[power - 1]}`, Type.NUMBER); }, json: (size) => { return size; }, }), [Type.PATH]: validateTransform({ pretty: (configuration, filePath) => { return applyColor(configuration, fslib_1.npath.fromPortablePath(filePath), Type.PATH); }, json: (filePath) => { return fslib_1.npath.fromPortablePath(filePath); }, }), }; function tuple(formatType, value) { return [value, formatType]; } exports.tuple = tuple; function applyStyle(configuration, text, flags) { if (!configuration.get(`enableColors`)) return text; if (flags & Style.BOLD) text = chalk_1.default.bold(text); return text; } exports.applyStyle = applyStyle; function applyColor(configuration, value, formatType) { if (!configuration.get(`enableColors`)) return value; const colorSpec = colors.get(formatType); if (colorSpec === null) return value; const color = typeof colorSpec === `undefined` ? formatType : chalkOptions.level >= 3 ? colorSpec[0] : colorSpec[1]; const fn = typeof color === `number` ? chalkInstance.ansi256(color) : color.startsWith(`#`) ? chalkInstance.hex(color) : chalkInstance[color]; if (typeof fn !== `function`) throw new Error(`Invalid format type ${color}`); return fn(value); } exports.applyColor = applyColor; function pretty(configuration, value, formatType) { if (value === null) return applyColor(configuration, `null`, Type.NULL); if (Object.prototype.hasOwnProperty.call(transforms, formatType)) { const transform = transforms[formatType]; const typedTransform = transform; return typedTransform.pretty(configuration, value); } if (typeof value !== `string`) throw new Error(`Assertion failed: Expected the value to be a string, got ${typeof value}`); return applyColor(configuration, value, formatType); } exports.pretty = pretty; function prettyList(configuration, values, formatType, { separator = `, ` } = {}) { return [...values].map(value => pretty(configuration, value, formatType)).join(separator); } exports.prettyList = prettyList; function json(value, formatType) { if (value === null) return null; if (Object.prototype.hasOwnProperty.call(transforms, formatType)) { miscUtils.overrideType(formatType); return transforms[formatType].json(value); } if (typeof value !== `string`) throw new Error(`Assertion failed: Expected the value to be a string, got ${typeof value}`); return value; } exports.json = json; function mark(configuration) { return { Check: applyColor(configuration, `✓`, `green`), Cross: applyColor(configuration, `✘`, `red`), Question: applyColor(configuration, `?`, `cyan`), }; } exports.mark = mark; var LogLevel; (function (LogLevel) { LogLevel["Error"] = "error"; LogLevel["Warning"] = "warning"; LogLevel["Info"] = "info"; LogLevel["Discard"] = "discard"; })(LogLevel = exports.LogLevel || (exports.LogLevel = {})); /** * Add support support for the `logFilters` setting to the specified Report * instance. */ function addLogFilterSupport(report, { configuration }) { const logFilters = configuration.get(`logFilters`); const logFiltersByCode = new Map(); const logFiltersByText = new Map(); for (const filter of logFilters) { const level = filter.get(`level`); if (typeof level === `undefined`) continue; const code = filter.get(`code`); if (typeof code !== `undefined`) logFiltersByCode.set(code, level); const text = filter.get(`text`); if (typeof text !== `undefined`) { logFiltersByText.set(text, level); } } const findLogLevel = (name, text, defaultLevel) => { if (name === null || name === MessageName_1.MessageName.UNNAMED) return defaultLevel; if (logFiltersByText.size > 0) { const level = logFiltersByText.get(chalk_1.default.reset(text)); if (typeof level !== `undefined`) { return level !== null && level !== void 0 ? level : defaultLevel; } } if (logFiltersByCode.size > 0) { const level = logFiltersByCode.get(MessageName_1.stringifyMessageName(name)); if (typeof level !== `undefined`) { return level !== null && level !== void 0 ? level : defaultLevel; } } return defaultLevel; }; const reportInfo = report.reportInfo; const reportWarning = report.reportWarning; const reportError = report.reportError; const routeMessage = function (report, name, text, level) { switch (findLogLevel(name, text, level)) { case LogLevel.Info: { reportInfo.call(report, name, text); } break; case LogLevel.Warning: { reportWarning.call(report, name !== null && name !== void 0 ? name : MessageName_1.MessageName.UNNAMED, text); } break; case LogLevel.Error: { reportError.call(report, name !== null && name !== void 0 ? name : MessageName_1.MessageName.UNNAMED, text); } break; } }; report.reportInfo = function (...args) { return routeMessage(this, ...args, LogLevel.Info); }; report.reportWarning = function (...args) { return routeMessage(this, ...args, LogLevel.Warning); }; report.reportError = function (...args) { return routeMessage(this, ...args, LogLevel.Error); }; } exports.addLogFilterSupport = addLogFilterSupport; /***/ }), /***/ 73279: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.checksumPattern = exports.checksumFile = exports.makeHash = void 0; const tslib_1 = __webpack_require__(70655); const fslib_1 = __webpack_require__(91794); const crypto_1 = __webpack_require__(6113); const globby_1 = tslib_1.__importDefault(__webpack_require__(25839)); function makeHash(...args) { const hash = crypto_1.createHash(`sha512`); for (const arg of args) hash.update(arg ? arg : ``); return hash.digest(`hex`); } exports.makeHash = makeHash; function checksumFile(path) { return new Promise((resolve, reject) => { const hash = crypto_1.createHash(`sha512`); const stream = fslib_1.xfs.createReadStream(path); stream.on(`data`, chunk => { hash.update(chunk); }); stream.on(`error`, error => { reject(error); }); stream.on(`end`, () => { resolve(hash.digest(`hex`)); }); }); } exports.checksumFile = checksumFile; async function checksumPattern(pattern, { cwd }) { // Note: We use a two-pass glob instead of using the expandDirectories option // from globby, because the native implementation is broken. // // Ref: https://github.com/sindresorhus/globby/issues/147 const dirListing = await globby_1.default(pattern, { cwd: fslib_1.npath.fromPortablePath(cwd), expandDirectories: false, onlyDirectories: true, unique: true, }); const dirPatterns = dirListing.map(entry => { return `${entry}/**/*`; }); const listing = await globby_1.default([pattern, ...dirPatterns], { cwd: fslib_1.npath.fromPortablePath(cwd), expandDirectories: false, onlyFiles: false, unique: true, }); listing.sort(); const hashes = await Promise.all(listing.map(async (entry) => { const parts = [Buffer.from(entry)]; const p = fslib_1.npath.toPortablePath(entry); const stat = await fslib_1.xfs.lstatPromise(p); if (stat.isSymbolicLink()) parts.push(Buffer.from(await fslib_1.xfs.readlinkPromise(p))); else if (stat.isFile()) parts.push(await fslib_1.xfs.readFilePromise(p)); return parts.join(`\u0000`); })); const hash = crypto_1.createHash(`sha512`); for (const sub of hashes) hash.update(sub); return hash.digest(`hex`); } exports.checksumPattern = checksumPattern; /***/ }), /***/ 57392: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.del = exports.post = exports.put = exports.get = exports.request = exports.Method = exports.getNetworkSettings = void 0; const tslib_1 = __webpack_require__(70655); const fslib_1 = __webpack_require__(91794); const https_1 = __webpack_require__(95687); const http_1 = __webpack_require__(13685); const micromatch_1 = tslib_1.__importDefault(__webpack_require__(70850)); const tunnel_1 = tslib_1.__importDefault(__webpack_require__(6149)); const url_1 = __webpack_require__(57310); const cache = new Map(); const certCache = new Map(); const globalHttpAgent = new http_1.Agent({ keepAlive: true }); const globalHttpsAgent = new https_1.Agent({ keepAlive: true }); function parseProxy(specifier) { const url = new url_1.URL(specifier); const proxy = { host: url.hostname, headers: {} }; if (url.port) proxy.port = Number(url.port); return { proxy }; } async function getCachedCertificate(caFilePath) { let certificate = certCache.get(caFilePath); if (!certificate) { certificate = fslib_1.xfs.readFilePromise(caFilePath).then(cert => { certCache.set(caFilePath, cert); return cert; }); certCache.set(caFilePath, certificate); } return certificate; } /** * Searches through networkSettings and returns the most specific match */ function getNetworkSettings(target, opts) { // Sort the config by key length to match on the most specific pattern const networkSettings = [...opts.configuration.get(`networkSettings`)].sort(([keyA], [keyB]) => { return keyB.length - keyA.length; }); const mergedNetworkSettings = { enableNetwork: undefined, caFilePath: undefined, httpProxy: undefined, httpsProxy: undefined, }; const mergableKeys = Object.keys(mergedNetworkSettings); const url = new url_1.URL(target); for (const [glob, config] of networkSettings) { if (micromatch_1.default.isMatch(url.hostname, glob)) { for (const key of mergableKeys) { const setting = config.get(key); if (setting !== null && typeof mergedNetworkSettings[key] === `undefined`) { mergedNetworkSettings[key] = setting; } } } } // Apply defaults for (const key of mergableKeys) { if (typeof mergedNetworkSettings[key] === `undefined`) { mergedNetworkSettings[key] = opts.configuration.get(key); } } return mergedNetworkSettings; } exports.getNetworkSettings = getNetworkSettings; var Method; (function (Method) { Method["GET"] = "GET"; Method["PUT"] = "PUT"; Method["POST"] = "POST"; Method["DELETE"] = "DELETE"; })(Method = exports.Method || (exports.Method = {})); async function request(target, body, { configuration, headers, json, jsonRequest = json, jsonResponse = json, method = Method.GET }) { const networkConfig = getNetworkSettings(target, { configuration }); if (networkConfig.enableNetwork === false) throw new Error(`Request to '${target}' has been blocked because of your configuration settings`); const url = new url_1.URL(target); if (url.protocol === `http:` && !micromatch_1.default.isMatch(url.hostname, configuration.get(`unsafeHttpWhitelist`))) throw new Error(`Unsafe http requests must be explicitly whitelisted in your configuration (${url.hostname})`); const agent = { http: networkConfig.httpProxy ? tunnel_1.default.httpOverHttp(parseProxy(networkConfig.httpProxy)) : globalHttpAgent, https: networkConfig.httpsProxy ? tunnel_1.default.httpsOverHttp(parseProxy(networkConfig.httpsProxy)) : globalHttpsAgent, }; const gotOptions = { agent, headers, method }; gotOptions.responseType = jsonResponse ? `json` : `buffer`; if (body !== null) { if (Buffer.isBuffer(body) || (!jsonRequest && typeof body === `string`)) { gotOptions.body = body; } else { // @ts-expect-error: The got types only allow an object, but got can stringify any valid JSON gotOptions.json = body; } } const socketTimeout = configuration.get(`httpTimeout`); const retry = configuration.get(`httpRetry`); const rejectUnauthorized = configuration.get(`enableStrictSsl`); const caFilePath = networkConfig.caFilePath; const { default: got } = await Promise.resolve().then(() => tslib_1.__importStar(__webpack_require__(12210))); const certificateAuthority = caFilePath ? await getCachedCertificate(caFilePath) : undefined; const gotClient = got.extend({ timeout: { socket: socketTimeout, }, retry, https: { rejectUnauthorized, certificateAuthority, }, ...gotOptions, }); return configuration.getLimit(`networkConcurrency`)(() => { return gotClient(target); }); } exports.request = request; async function get(target, { configuration, json, jsonResponse = json, ...rest }) { let entry = cache.get(target); if (!entry) { entry = request(target, null, { configuration, ...rest }).then(response => { cache.set(target, response.body); return response.body; }); cache.set(target, entry); } if (Buffer.isBuffer(entry) === false) entry = await entry; if (jsonResponse) { return JSON.parse(entry.toString()); } else { return entry; } } exports.get = get; async function put(target, body, options) { const response = await request(target, body, { ...options, method: Method.PUT }); return response.body; } exports.put = put; async function post(target, body, options) { const response = await request(target, body, { ...options, method: Method.POST }); return response.body; } exports.post = post; async function del(target, options) { const response = await request(target, null, { ...options, method: Method.DELETE }); return response.body; } exports.del = del; /***/ }), /***/ 74876: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.treeUtils = exports.tgzUtils = exports.structUtils = exports.semverUtils = exports.scriptUtils = exports.miscUtils = exports.formatUtils = exports.folderUtils = exports.execUtils = exports.httpUtils = exports.hashUtils = exports.PackageExtensionStatus = exports.PackageExtensionType = exports.LinkType = exports.YarnVersion = exports.Workspace = exports.WorkspaceResolver = exports.VirtualFetcher = exports.ThrowReport = exports.TelemetryManager = exports.StreamReport = exports.Report = exports.ReportError = exports.TAG_REGEXP = exports.Project = exports.MessageName = exports.Manifest = exports.LightReport = exports.BuildType = exports.SettingsType = exports.ProjectLookup = exports.FormatType = exports.Configuration = exports.DEFAULT_LOCK_FILENAME = exports.DEFAULT_RC_FILENAME = exports.Cache = void 0; const tslib_1 = __webpack_require__(70655); const execUtils = tslib_1.__importStar(__webpack_require__(12915)); exports.execUtils = execUtils; const folderUtils = tslib_1.__importStar(__webpack_require__(13061)); exports.folderUtils = folderUtils; const formatUtils = tslib_1.__importStar(__webpack_require__(23821)); exports.formatUtils = formatUtils; const hashUtils = tslib_1.__importStar(__webpack_require__(73279)); exports.hashUtils = hashUtils; const httpUtils = tslib_1.__importStar(__webpack_require__(57392)); exports.httpUtils = httpUtils; const miscUtils = tslib_1.__importStar(__webpack_require__(63111)); exports.miscUtils = miscUtils; const scriptUtils = tslib_1.__importStar(__webpack_require__(50888)); exports.scriptUtils = scriptUtils; const semverUtils = tslib_1.__importStar(__webpack_require__(51201)); exports.semverUtils = semverUtils; const structUtils = tslib_1.__importStar(__webpack_require__(34103)); exports.structUtils = structUtils; const tgzUtils = tslib_1.__importStar(__webpack_require__(83607)); exports.tgzUtils = tgzUtils; const treeUtils = tslib_1.__importStar(__webpack_require__(55024)); exports.treeUtils = treeUtils; var Cache_1 = __webpack_require__(19552); Object.defineProperty(exports, "Cache", ({ enumerable: true, get: function () { return Cache_1.Cache; } })); var Configuration_1 = __webpack_require__(62889); Object.defineProperty(exports, "DEFAULT_RC_FILENAME", ({ enumerable: true, get: function () { return Configuration_1.DEFAULT_RC_FILENAME; } })); Object.defineProperty(exports, "DEFAULT_LOCK_FILENAME", ({ enumerable: true, get: function () { return Configuration_1.DEFAULT_LOCK_FILENAME; } })); var Configuration_2 = __webpack_require__(62889); Object.defineProperty(exports, "Configuration", ({ enumerable: true, get: function () { return Configuration_2.Configuration; } })); Object.defineProperty(exports, "FormatType", ({ enumerable: true, get: function () { return Configuration_2.FormatType; } })); Object.defineProperty(exports, "ProjectLookup", ({ enumerable: true, get: function () { return Configuration_2.ProjectLookup; } })); Object.defineProperty(exports, "SettingsType", ({ enumerable: true, get: function () { return Configuration_2.SettingsType; } })); var Installer_1 = __webpack_require__(45006); Object.defineProperty(exports, "BuildType", ({ enumerable: true, get: function () { return Installer_1.BuildType; } })); var LightReport_1 = __webpack_require__(60613); Object.defineProperty(exports, "LightReport", ({ enumerable: true, get: function () { return LightReport_1.LightReport; } })); var Manifest_1 = __webpack_require__(11658); Object.defineProperty(exports, "Manifest", ({ enumerable: true, get: function () { return Manifest_1.Manifest; } })); var MessageName_1 = __webpack_require__(62755); Object.defineProperty(exports, "MessageName", ({ enumerable: true, get: function () { return MessageName_1.MessageName; } })); var Project_1 = __webpack_require__(49015); Object.defineProperty(exports, "Project", ({ enumerable: true, get: function () { return Project_1.Project; } })); var ProtocolResolver_1 = __webpack_require__(6729); Object.defineProperty(exports, "TAG_REGEXP", ({ enumerable: true, get: function () { return ProtocolResolver_1.TAG_REGEXP; } })); var Report_1 = __webpack_require__(50334); Object.defineProperty(exports, "ReportError", ({ enumerable: true, get: function () { return Report_1.ReportError; } })); Object.defineProperty(exports, "Report", ({ enumerable: true, get: function () { return Report_1.Report; } })); var StreamReport_1 = __webpack_require__(73759); Object.defineProperty(exports, "StreamReport", ({ enumerable: true, get: function () { return StreamReport_1.StreamReport; } })); var TelemetryManager_1 = __webpack_require__(58166); Object.defineProperty(exports, "TelemetryManager", ({ enumerable: true, get: function () { return TelemetryManager_1.TelemetryManager; } })); var ThrowReport_1 = __webpack_require__(6059); Object.defineProperty(exports, "ThrowReport", ({ enumerable: true, get: function () { return ThrowReport_1.ThrowReport; } })); var VirtualFetcher_1 = __webpack_require__(7100); Object.defineProperty(exports, "VirtualFetcher", ({ enumerable: true, get: function () { return VirtualFetcher_1.VirtualFetcher; } })); var WorkspaceResolver_1 = __webpack_require__(83740); Object.defineProperty(exports, "WorkspaceResolver", ({ enumerable: true, get: function () { return WorkspaceResolver_1.WorkspaceResolver; } })); var Workspace_1 = __webpack_require__(2234); Object.defineProperty(exports, "Workspace", ({ enumerable: true, get: function () { return Workspace_1.Workspace; } })); var YarnVersion_1 = __webpack_require__(71774); Object.defineProperty(exports, "YarnVersion", ({ enumerable: true, get: function () { return YarnVersion_1.YarnVersion; } })); var types_1 = __webpack_require__(79588); Object.defineProperty(exports, "LinkType", ({ enumerable: true, get: function () { return types_1.LinkType; } })); Object.defineProperty(exports, "PackageExtensionType", ({ enumerable: true, get: function () { return types_1.PackageExtensionType; } })); Object.defineProperty(exports, "PackageExtensionStatus", ({ enumerable: true, get: function () { return types_1.PackageExtensionStatus; } })); /***/ }), /***/ 63111: /***/ ((module, exports, __webpack_require__) => { "use strict"; /* module decorator */ module = __webpack_require__.nmd(module); Object.defineProperty(exports, "__esModule", ({ value: true })); exports.tryParseOptionalBoolean = exports.parseOptionalBoolean = exports.parseBoolean = exports.replaceEnvVariables = exports.buildIgnorePattern = exports.sortMap = exports.dynamicRequireNoCache = exports.dynamicRequire = exports.DefaultStream = exports.BufferStream = exports.bufferStream = exports.prettifySyncErrors = exports.prettifyAsyncErrors = exports.releaseAfterUseAsync = exports.getMapWithDefault = exports.getSetWithDefault = exports.getArrayWithDefault = exports.getFactoryWithDefault = exports.convertMapsToIndexableObjects = exports.isIndexableObject = exports.mapAndFind = exports.mapAndFilter = exports.validateEnum = exports.assertNever = exports.overrideType = exports.escapeRegExp = void 0; const tslib_1 = __webpack_require__(70655); const fslib_1 = __webpack_require__(91794); const clipanion_1 = __webpack_require__(87730); const micromatch_1 = tslib_1.__importDefault(__webpack_require__(70850)); const stream_1 = __webpack_require__(12781); function escapeRegExp(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, `\\$&`); } exports.escapeRegExp = escapeRegExp; function overrideType(val) { } exports.overrideType = overrideType; function assertNever(arg) { throw new Error(`Assertion failed: Unexpected object '${arg}'`); } exports.assertNever = assertNever; function validateEnum(def, value) { if (!Object.values(def).includes(value)) throw new Error(`Assertion failed: Invalid value for enumeration`); return value; } exports.validateEnum = validateEnum; function mapAndFilter(iterable, cb) { const output = []; for (const value of iterable) { const out = cb(value); if (out !== mapAndFilterSkip) { output.push(out); } } return output; } exports.mapAndFilter = mapAndFilter; const mapAndFilterSkip = Symbol(); mapAndFilter.skip = mapAndFilterSkip; function mapAndFind(iterable, cb) { for (const value of iterable) { const out = cb(value); if (out !== mapAndFindSkip) { return out; } } return undefined; } exports.mapAndFind = mapAndFind; const mapAndFindSkip = Symbol(); mapAndFind.skip = mapAndFindSkip; function isIndexableObject(value) { return typeof value === `object` && value !== null; } exports.isIndexableObject = isIndexableObject; /** * Converts Maps to indexable objects recursively. */ function convertMapsToIndexableObjects(arg) { if (arg instanceof Map) arg = Object.fromEntries(arg); if (isIndexableObject(arg)) { for (const key of Object.keys(arg)) { const value = arg[key]; if (isIndexableObject(value)) { // @ts-expect-error: Apparently nothing in this world can be used to index type 'T & { [key: string]: unknown; }' arg[key] = convertMapsToIndexableObjects(value); } } } return arg; } exports.convertMapsToIndexableObjects = convertMapsToIndexableObjects; function getFactoryWithDefault(map, key, factory) { let value = map.get(key); if (typeof value === `undefined`) map.set(key, value = factory()); return value; } exports.getFactoryWithDefault = getFactoryWithDefault; function getArrayWithDefault(map, key) { let value = map.get(key); if (typeof value === `undefined`) map.set(key, value = []); return value; } exports.getArrayWithDefault = getArrayWithDefault; function getSetWithDefault(map, key) { let value = map.get(key); if (typeof value === `undefined`) map.set(key, value = new Set()); return value; } exports.getSetWithDefault = getSetWithDefault; function getMapWithDefault(map, key) { let value = map.get(key); if (typeof value === `undefined`) map.set(key, value = new Map()); return value; } exports.getMapWithDefault = getMapWithDefault; // Executes a chunk of code and calls a cleanup function once it returns (even // if it throws an exception) async function releaseAfterUseAsync(fn, cleanup) { if (cleanup == null) return await fn(); try { return await fn(); } finally { await cleanup(); } } exports.releaseAfterUseAsync = releaseAfterUseAsync; // Executes a chunk of code but slightly modify its exception message if it // throws something async function prettifyAsyncErrors(fn, update) { try { return await fn(); } catch (error) { error.message = update(error.message); throw error; } } exports.prettifyAsyncErrors = prettifyAsyncErrors; // Same thing but synchronous function prettifySyncErrors(fn, update) { try { return fn(); } catch (error) { error.message = update(error.message); throw error; } } exports.prettifySyncErrors = prettifySyncErrors; // Converts a Node stream into a Buffer instance async function bufferStream(stream) { return await new Promise((resolve, reject) => { const chunks = []; stream.on(`error`, error => { reject(error); }); stream.on(`data`, chunk => { chunks.push(chunk); }); stream.on(`end`, () => { resolve(Buffer.concat(chunks)); }); }); } exports.bufferStream = bufferStream; // A stream implementation that buffers a stream to send it all at once class BufferStream extends stream_1.Transform { constructor() { super(...arguments); this.chunks = []; } _transform(chunk, encoding, cb) { if (encoding !== `buffer` || !Buffer.isBuffer(chunk)) throw new Error(`Assertion failed: BufferStream only accept buffers`); this.chunks.push(chunk); cb(null, null); } _flush(cb) { cb(null, Buffer.concat(this.chunks)); } } exports.BufferStream = BufferStream; // A stream implementation that prints a message if nothing was output class DefaultStream extends stream_1.Transform { constructor(ifEmpty = Buffer.alloc(0)) { super(); this.active = true; this.ifEmpty = ifEmpty; } _transform(chunk, encoding, cb) { if (encoding !== `buffer` || !Buffer.isBuffer(chunk)) throw new Error(`Assertion failed: DefaultStream only accept buffers`); this.active = false; cb(null, chunk); } _flush(cb) { if (this.active && this.ifEmpty.length > 0) { cb(null, this.ifEmpty); } } } exports.DefaultStream = DefaultStream; // Webpack has this annoying tendency to replace dynamic requires by a stub // code that simply throws when called. It's all fine and dandy in the context // of a web application, but is quite annoying when working with Node projects! function dynamicRequire(path) { // @ts-expect-error if (typeof require !== `undefined`) { // @ts-expect-error return require(path); } else { return __webpack_require__(61452)(path); } } exports.dynamicRequire = dynamicRequire; function dynamicRequireNoCache(path) { const physicalPath = fslib_1.npath.fromPortablePath(path); const currentCacheEntry = __webpack_require__.c[physicalPath]; delete __webpack_require__.c[physicalPath]; let result; try { result = dynamicRequire(physicalPath); const freshCacheEntry = __webpack_require__.c[physicalPath]; const freshCacheIndex = module.children.indexOf(freshCacheEntry); if (freshCacheIndex !== -1) { module.children.splice(freshCacheIndex, 1); } } finally { __webpack_require__.c[physicalPath] = currentCacheEntry; } return result; } exports.dynamicRequireNoCache = dynamicRequireNoCache; // This function transforms an iterable into an array and sorts it according to // the mapper functions provided as parameter. The mappers are expected to take // each element from the iterable and generate a string from it, that will then // be used to compare the entries. // // Using sortMap is more efficient than kinda reimplementing the logic in a sort // predicate because sortMap caches the result of the mappers in such a way that // they are guaranteed to be executed exactly once for each element. function sortMap(values, mappers) { const asArray = Array.from(values); if (!Array.isArray(mappers)) mappers = [mappers]; const stringified = []; for (const mapper of mappers) stringified.push(asArray.map(value => mapper(value))); const indices = asArray.map((_, index) => index); indices.sort((a, b) => { for (const layer of stringified) { const comparison = layer[a] < layer[b] ? -1 : layer[a] > layer[b] ? +1 : 0; if (comparison !== 0) { return comparison; } } return 0; }); return indices.map(index => { return asArray[index]; }); } exports.sortMap = sortMap; /** * Combines an Array of glob patterns into a regular expression. * * @param ignorePatterns An array of glob patterns * * @returns A `string` representing a regular expression or `null` if no glob patterns are provided */ function buildIgnorePattern(ignorePatterns) { if (ignorePatterns.length === 0) return null; return ignorePatterns.map(pattern => { return `(${micromatch_1.default.makeRe(pattern, { windows: false, }).source})`; }).join(`|`); } exports.buildIgnorePattern = buildIgnorePattern; function replaceEnvVariables(value, { env }) { const regex = /\${(?[\d\w_]+)(?:)?(?:-(?[^}]*))?}/g; return value.replace(regex, (...args) => { const { variableName, colon, fallback } = args[args.length - 1]; const variableExist = Object.prototype.hasOwnProperty.call(env, variableName); const variableValue = env[variableName]; if (variableValue) return variableValue; if (variableExist && !colon) return variableValue; if (fallback != null) return fallback; throw new clipanion_1.UsageError(`Environment variable not found (${variableName})`); }); } exports.replaceEnvVariables = replaceEnvVariables; function parseBoolean(value) { switch (value) { case `true`: case `1`: case 1: case true: { return true; } case `false`: case `0`: case 0: case false: { return false; } default: { throw new Error(`Couldn't parse "${value}" as a boolean`); } } } exports.parseBoolean = parseBoolean; function parseOptionalBoolean(value) { if (typeof value === `undefined`) return value; return parseBoolean(value); } exports.parseOptionalBoolean = parseOptionalBoolean; function tryParseOptionalBoolean(value) { try { return parseOptionalBoolean(value); } catch (_a) { return null; } } exports.tryParseOptionalBoolean = tryParseOptionalBoolean; /***/ }), /***/ 83825: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.builtinModules = exports.dynamicRequire = void 0; const tslib_1 = __webpack_require__(70655); const module_1 = tslib_1.__importDefault(__webpack_require__(98188)); function dynamicRequire(request) { const req = typeof require !== `undefined` ? require : __webpack_require__(61452); return req(request); } exports.dynamicRequire = dynamicRequire; function builtinModules() { // @ts-expect-error return new Set(module_1.default.builtinModules || Object.keys(process.binding(`natives`))); } exports.builtinModules = builtinModules; /***/ }), /***/ 50888: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.executeWorkspaceAccessibleBinary = exports.executePackageAccessibleBinary = exports.getWorkspaceAccessibleBinaries = exports.getPackageAccessibleBinaries = exports.maybeExecuteWorkspaceLifecycleScript = exports.executeWorkspaceLifecycleScript = exports.hasWorkspaceScript = exports.executeWorkspaceScript = exports.executePackageShellcode = exports.executePackageScript = exports.hasPackageScript = exports.prepareExternalProject = exports.makeScriptEnv = void 0; const tslib_1 = __webpack_require__(70655); const fslib_1 = __webpack_require__(91794); const fslib_2 = __webpack_require__(91794); const libzip_1 = __webpack_require__(40364); const shell_1 = __webpack_require__(56096); const binjumper_1 = __webpack_require__(94372); const capitalize_1 = tslib_1.__importDefault(__webpack_require__(48403)); const p_limit_1 = tslib_1.__importDefault(__webpack_require__(93743)); const stream_1 = __webpack_require__(12781); const Manifest_1 = __webpack_require__(11658); const MessageName_1 = __webpack_require__(62755); const Report_1 = __webpack_require__(50334); const StreamReport_1 = __webpack_require__(73759); const YarnVersion_1 = __webpack_require__(71774); const execUtils = tslib_1.__importStar(__webpack_require__(12915)); const formatUtils = tslib_1.__importStar(__webpack_require__(23821)); const miscUtils = tslib_1.__importStar(__webpack_require__(63111)); const structUtils = tslib_1.__importStar(__webpack_require__(34103)); var PackageManager; (function (PackageManager) { PackageManager["Yarn1"] = "Yarn Classic"; PackageManager["Yarn2"] = "Yarn"; PackageManager["Npm"] = "npm"; PackageManager["Pnpm"] = "pnpm"; })(PackageManager || (PackageManager = {})); async function makePathWrapper(location, name, argv0, args = []) { if (process.platform === `win32`) { await Promise.all([ fslib_2.xfs.writeFilePromise(fslib_2.ppath.format({ dir: location, name, ext: `.exe` }), binjumper_1.getBinjumper()), fslib_2.xfs.writeFilePromise(fslib_2.ppath.format({ dir: location, name, ext: `.exe.info` }), [argv0, ...args].join(`\n`)), fslib_2.xfs.writeFilePromise(fslib_2.ppath.format({ dir: location, name, ext: `.cmd` }), `@"${argv0}" ${args.map(arg => `"${arg.replace(`"`, `""`)}"`).join(` `)} %*\n`), ]); } await fslib_2.xfs.writeFilePromise(fslib_2.ppath.join(location, name), `#!/bin/sh\nexec "${argv0}" ${args.map(arg => `'${arg.replace(/'/g, `'"'"'`)}'`).join(` `)} "$@"\n`); await fslib_2.xfs.chmodPromise(fslib_2.ppath.join(location, name), 0o755); } async function detectPackageManager(location) { let yarnLock = null; try { yarnLock = await fslib_2.xfs.readFilePromise(fslib_2.ppath.join(location, fslib_1.Filename.lockfile), `utf8`); } catch (_a) { } if (yarnLock !== null) { if (yarnLock.match(/^__metadata:$/m)) { return PackageManager.Yarn2; } else { return PackageManager.Yarn1; } } if (fslib_2.xfs.existsSync(fslib_2.ppath.join(location, `package-lock.json`))) return PackageManager.Npm; if (fslib_2.xfs.existsSync(fslib_2.ppath.join(location, `pnpm-lock.yaml`))) return PackageManager.Pnpm; return null; } async function makeScriptEnv({ project, binFolder, lifecycleScript }) { const scriptEnv = {}; for (const [key, value] of Object.entries(process.env)) if (typeof value !== `undefined`) scriptEnv[key.toLowerCase() !== `path` ? key : `PATH`] = value; const nBinFolder = fslib_2.npath.fromPortablePath(binFolder); // We expose the base folder in the environment so that we can later add the // binaries for the dependencies of the active package scriptEnv.BERRY_BIN_FOLDER = fslib_2.npath.fromPortablePath(nBinFolder); // Register some binaries that must be made available in all subprocesses // spawned by Yarn (we thus ensure that they always use the right version) await makePathWrapper(binFolder, `node`, process.execPath); if (YarnVersion_1.YarnVersion !== null) { await makePathWrapper(binFolder, `run`, process.execPath, [process.argv[1], `run`]); await makePathWrapper(binFolder, `yarn`, process.execPath, [process.argv[1]]); await makePathWrapper(binFolder, `yarnpkg`, process.execPath, [process.argv[1]]); await makePathWrapper(binFolder, `node-gyp`, process.execPath, [process.argv[1], `run`, `--top-level`, `node-gyp`]); } if (project) scriptEnv.INIT_CWD = fslib_2.npath.fromPortablePath(project.configuration.startingCwd); scriptEnv.PATH = scriptEnv.PATH ? `${nBinFolder}${fslib_2.npath.delimiter}${scriptEnv.PATH}` : `${nBinFolder}`; scriptEnv.npm_execpath = `${nBinFolder}${fslib_2.npath.sep}yarn`; scriptEnv.npm_node_execpath = `${nBinFolder}${fslib_2.npath.sep}node`; const version = YarnVersion_1.YarnVersion !== null ? `yarn/${YarnVersion_1.YarnVersion}` : `yarn/${miscUtils.dynamicRequire(`@yarnpkg/core`).version}-core`; scriptEnv.npm_config_user_agent = `${version} npm/? node/${process.versions.node} ${process.platform} ${process.arch}`; if (lifecycleScript) scriptEnv.npm_lifecycle_event = lifecycleScript; if (project) { await project.configuration.triggerHook(hook => hook.setupScriptEnvironment, project, scriptEnv, async (name, argv0, args) => { return await makePathWrapper(binFolder, fslib_2.toFilename(name), argv0, args); }); } return scriptEnv; } exports.makeScriptEnv = makeScriptEnv; /** * Given a folder, prepares this project for use. Runs `yarn install` then * `yarn build` if a `package.json` is found. */ const MAX_PREPARE_CONCURRENCY = 2; const prepareLimit = p_limit_1.default(MAX_PREPARE_CONCURRENCY); async function prepareExternalProject(cwd, outputPath, { configuration, report, workspace = null }) { await prepareLimit(async () => { await fslib_2.xfs.mktempPromise(async (logDir) => { const logFile = fslib_2.ppath.join(logDir, `pack.log`); const stdin = null; const { stdout, stderr } = configuration.getSubprocessStreams(logFile, { prefix: cwd, report }); const packageManager = await detectPackageManager(cwd); let effectivePackageManager; if (packageManager !== null) { stdout.write(`Installing the project using ${packageManager}\n\n`); effectivePackageManager = packageManager; } else { stdout.write(`No package manager detected; defaulting to Yarn\n\n`); effectivePackageManager = PackageManager.Yarn2; } await fslib_2.xfs.mktempPromise(async (binFolder) => { const env = await makeScriptEnv({ binFolder }); const workflows = new Map([ [PackageManager.Yarn1, async () => { const workspaceCli = workspace !== null ? [`workspace`, workspace] : []; // Makes sure that we'll be using Yarn 1.x const version = await execUtils.pipevp(`yarn`, [`set`, `version`, `classic`, `--only-if-needed`], { cwd, env, stdin, stdout, stderr, end: execUtils.EndStrategy.ErrorCode }); if (version.code !== 0) return version.code; // Otherwise Yarn 1 will pack the .yarn directory :( await fslib_2.xfs.appendFilePromise(fslib_2.ppath.join(cwd, `.npmignore`), `/.yarn\n`); stdout.write(`\n`); // Run an install; we can't avoid it unless we inspect the // package.json, which I don't want to do to keep the codebase // clean (even if it has a slight perf cost when cloning v1 repos) const install = await execUtils.pipevp(`yarn`, [`install`], { cwd, env, stdin, stdout, stderr, end: execUtils.EndStrategy.ErrorCode }); if (install.code !== 0) return install.code; stdout.write(`\n`); const pack = await execUtils.pipevp(`yarn`, [...workspaceCli, `pack`, `--filename`, fslib_2.npath.fromPortablePath(outputPath)], { cwd, env, stdin, stdout, stderr }); if (pack.code !== 0) return pack.code; return 0; }], [PackageManager.Yarn2, async () => { const workspaceCli = workspace !== null ? [`workspace`, workspace] : []; // We enable inline builds, because nobody wants to // read a logfile telling them to open another logfile env.YARN_ENABLE_INLINE_BUILDS = `1`; // If a lockfile doesn't exist we create a empty one to // prevent the project root detection from thinking it's in an // undeclared workspace when the user has a lockfile in their home // directory on Windows const lockfilePath = fslib_2.ppath.join(cwd, fslib_1.Filename.lockfile); if (!(await fslib_2.xfs.existsPromise(lockfilePath))) await fslib_2.xfs.writeFilePromise(lockfilePath, ``); // Yarn 2 supports doing the install and the pack in a single command, // so we leverage that. We also don't need the "set version" call since // we're already operating within a Yarn 2 context (plus people should // really check-in their Yarn versions anyway). const pack = await execUtils.pipevp(`yarn`, [...workspaceCli, `pack`, `--install-if-needed`, `--filename`, fslib_2.npath.fromPortablePath(outputPath)], { cwd, env, stdin, stdout, stderr }); if (pack.code !== 0) return pack.code; return 0; }], [PackageManager.Npm, async () => { if (workspace !== null) throw new Error(`Workspaces aren't supported by npm, which has been detected as the primary package manager for ${cwd}`); // Otherwise npm won't properly set the user agent, using the Yarn // one instead delete env.npm_config_user_agent; // We can't use `npm ci` because some projects don't have npm // lockfiles that are up-to-date. Hopefully npm won't decide // to change the versions randomly. const install = await execUtils.pipevp(`npm`, [`install`], { cwd, env, stdin, stdout, stderr, end: execUtils.EndStrategy.ErrorCode }); if (install.code !== 0) return install.code; const packStream = new stream_1.PassThrough(); const packPromise = miscUtils.bufferStream(packStream); packStream.pipe(stdout); // It seems that npm doesn't support specifying the pack output path, // so we have to extract the stdout on top of forking it to the logs. const pack = await execUtils.pipevp(`npm`, [`pack`, `--silent`], { cwd, env, stdin, stdout: packStream, stderr }); if (pack.code !== 0) return pack.code; const packOutput = (await packPromise).toString().trim(); const packTarget = fslib_2.ppath.resolve(cwd, fslib_2.npath.toPortablePath(packOutput)); // Only then can we move the pack to its rightful location await fslib_2.xfs.renamePromise(packTarget, outputPath); return 0; }], ]); const workflow = workflows.get(effectivePackageManager); if (typeof workflow === `undefined`) throw new Error(`Assertion failed: Unsupported workflow`); const code = await workflow(); if (code === 0 || typeof code === `undefined`) return; fslib_2.xfs.detachTemp(logDir); throw new Report_1.ReportError(MessageName_1.MessageName.PACKAGE_PREPARATION_FAILED, `Packing the package failed (exit code ${code}, logs can be found here: ${logFile})`); }); }); }); } exports.prepareExternalProject = prepareExternalProject; async function hasPackageScript(locator, scriptName, { project }) { const pkg = project.storedPackages.get(locator.locatorHash); if (!pkg) throw new Error(`Package for ${structUtils.prettyLocator(project.configuration, locator)} not found in the project`); return await fslib_1.ZipOpenFS.openPromise(async (zipOpenFs) => { const configuration = project.configuration; const linkers = project.configuration.getLinkers(); const linkerOptions = { project, report: new StreamReport_1.StreamReport({ stdout: new stream_1.PassThrough(), configuration }) }; const linker = linkers.find(linker => linker.supportsPackage(pkg, linkerOptions)); if (!linker) throw new Error(`The package ${structUtils.prettyLocator(project.configuration, pkg)} isn't supported by any of the available linkers`); const packageLocation = await linker.findPackageLocation(pkg, linkerOptions); const packageFs = new fslib_1.CwdFS(packageLocation, { baseFs: zipOpenFs }); const manifest = await Manifest_1.Manifest.find(fslib_1.PortablePath.dot, { baseFs: packageFs }); return manifest.scripts.has(scriptName); }, { libzip: await libzip_1.getLibzipPromise(), }); } exports.hasPackageScript = hasPackageScript; async function executePackageScript(locator, scriptName, args, { cwd, project, stdin, stdout, stderr }) { return await fslib_2.xfs.mktempPromise(async (binFolder) => { const { manifest, env, cwd: realCwd } = await initializePackageEnvironment(locator, { project, binFolder, cwd, lifecycleScript: scriptName }); const script = manifest.scripts.get(scriptName); if (typeof script === `undefined`) return 1; const realExecutor = async () => { return await shell_1.execute(script, args, { cwd: realCwd, env, stdin, stdout, stderr }); }; const executor = await project.configuration.reduceHook(hooks => { return hooks.wrapScriptExecution; }, realExecutor, project, locator, scriptName, { script, args, cwd: realCwd, env, stdin, stdout, stderr, }); return await executor(); }); } exports.executePackageScript = executePackageScript; async function executePackageShellcode(locator, command, args, { cwd, project, stdin, stdout, stderr }) { return await fslib_2.xfs.mktempPromise(async (binFolder) => { const { env, cwd: realCwd } = await initializePackageEnvironment(locator, { project, binFolder, cwd }); return await shell_1.execute(command, args, { cwd: realCwd, env, stdin, stdout, stderr }); }); } exports.executePackageShellcode = executePackageShellcode; async function initializePackageEnvironment(locator, { project, binFolder, cwd, lifecycleScript }) { const pkg = project.storedPackages.get(locator.locatorHash); if (!pkg) throw new Error(`Package for ${structUtils.prettyLocator(project.configuration, locator)} not found in the project`); return await fslib_1.ZipOpenFS.openPromise(async (zipOpenFs) => { const configuration = project.configuration; const linkers = project.configuration.getLinkers(); const linkerOptions = { project, report: new StreamReport_1.StreamReport({ stdout: new stream_1.PassThrough(), configuration }) }; const linker = linkers.find(linker => linker.supportsPackage(pkg, linkerOptions)); if (!linker) throw new Error(`The package ${structUtils.prettyLocator(project.configuration, pkg)} isn't supported by any of the available linkers`); const env = await makeScriptEnv({ project, binFolder, lifecycleScript }); await Promise.all(Array.from(await getPackageAccessibleBinaries(locator, { project }), ([binaryName, [, binaryPath]]) => makePathWrapper(binFolder, fslib_2.toFilename(binaryName), process.execPath, [binaryPath]))); const packageLocation = await linker.findPackageLocation(pkg, linkerOptions); const packageFs = new fslib_1.CwdFS(packageLocation, { baseFs: zipOpenFs }); const manifest = await Manifest_1.Manifest.find(fslib_1.PortablePath.dot, { baseFs: packageFs }); if (typeof cwd === `undefined`) cwd = packageLocation; return { manifest, binFolder, env, cwd }; }, { libzip: await libzip_1.getLibzipPromise(), }); } async function executeWorkspaceScript(workspace, scriptName, args, { cwd, stdin, stdout, stderr }) { return await executePackageScript(workspace.anchoredLocator, scriptName, args, { cwd, project: workspace.project, stdin, stdout, stderr }); } exports.executeWorkspaceScript = executeWorkspaceScript; function hasWorkspaceScript(workspace, scriptName) { return workspace.manifest.scripts.has(scriptName); } exports.hasWorkspaceScript = hasWorkspaceScript; async function executeWorkspaceLifecycleScript(workspace, lifecycleScriptName, { cwd, report }) { const { configuration } = workspace.project; const stdin = null; await fslib_2.xfs.mktempPromise(async (logDir) => { const logFile = fslib_2.ppath.join(logDir, `${lifecycleScriptName}.log`); const header = `# This file contains the result of Yarn calling the "${lifecycleScriptName}" lifecycle script inside a workspace ("${workspace.cwd}")\n`; const { stdout, stderr } = configuration.getSubprocessStreams(logFile, { report, prefix: structUtils.prettyLocator(configuration, workspace.anchoredLocator), header, }); report.reportInfo(MessageName_1.MessageName.LIFECYCLE_SCRIPT, `Calling the "${lifecycleScriptName}" lifecycle script`); const exitCode = await executeWorkspaceScript(workspace, lifecycleScriptName, [], { cwd, stdin, stdout, stderr }); stdout.end(); stderr.end(); if (exitCode !== 0) { fslib_2.xfs.detachTemp(logDir); throw new Report_1.ReportError(MessageName_1.MessageName.LIFECYCLE_SCRIPT, `${capitalize_1.default(lifecycleScriptName)} script failed (exit code ${formatUtils.pretty(configuration, exitCode, formatUtils.Type.NUMBER)}, logs can be found here: ${formatUtils.pretty(configuration, logFile, formatUtils.Type.PATH)}); run ${formatUtils.pretty(configuration, `yarn ${lifecycleScriptName}`, formatUtils.Type.CODE)} to investigate`); } }); } exports.executeWorkspaceLifecycleScript = executeWorkspaceLifecycleScript; async function maybeExecuteWorkspaceLifecycleScript(workspace, lifecycleScriptName, opts) { if (hasWorkspaceScript(workspace, lifecycleScriptName)) { await executeWorkspaceLifecycleScript(workspace, lifecycleScriptName, opts); } } exports.maybeExecuteWorkspaceLifecycleScript = maybeExecuteWorkspaceLifecycleScript; /** * Return the binaries that can be accessed by the specified package * * @param locator The queried package * @param project The project owning the package */ async function getPackageAccessibleBinaries(locator, { project }) { const configuration = project.configuration; const binaries = new Map(); const pkg = project.storedPackages.get(locator.locatorHash); if (!pkg) throw new Error(`Package for ${structUtils.prettyLocator(configuration, locator)} not found in the project`); const stdout = new stream_1.Writable(); const linkers = configuration.getLinkers(); const linkerOptions = { project, report: new StreamReport_1.StreamReport({ configuration, stdout }) }; const visibleLocators = new Set([locator.locatorHash]); for (const descriptor of pkg.dependencies.values()) { const resolution = project.storedResolutions.get(descriptor.descriptorHash); if (!resolution) throw new Error(`Assertion failed: The resolution (${structUtils.prettyDescriptor(configuration, descriptor)}) should have been registered`); visibleLocators.add(resolution); } for (const locatorHash of visibleLocators) { const dependency = project.storedPackages.get(locatorHash); if (!dependency) throw new Error(`Assertion failed: The package (${locatorHash}) should have been registered`); if (dependency.bin.size === 0) continue; const linker = linkers.find(linker => linker.supportsPackage(dependency, linkerOptions)); if (!linker) continue; let packageLocation = null; try { packageLocation = await linker.findPackageLocation(dependency, linkerOptions); } catch (err) { // Some packages may not be installed when they are incompatible // with the current system. if (err.code === `LOCATOR_NOT_INSTALLED`) { continue; } else { throw err; } } for (const [name, target] of dependency.bin) { binaries.set(name, [dependency, fslib_2.npath.fromPortablePath(fslib_2.ppath.resolve(packageLocation, target))]); } } return binaries; } exports.getPackageAccessibleBinaries = getPackageAccessibleBinaries; /** * Return the binaries that can be accessed by the specified workspace * * @param workspace The queried workspace */ async function getWorkspaceAccessibleBinaries(workspace) { return await getPackageAccessibleBinaries(workspace.anchoredLocator, { project: workspace.project }); } exports.getWorkspaceAccessibleBinaries = getWorkspaceAccessibleBinaries; /** * Execute a binary from the specified package. * * Note that "binary" in this sense means "a Javascript file". Actual native * binaries cannot be executed this way, because we use Node in order to * transparently read from the archives. * * @param locator The queried package * @param binaryName The name of the binary file to execute * @param args The arguments to pass to the file */ async function executePackageAccessibleBinary(locator, binaryName, args, { cwd, project, stdin, stdout, stderr, nodeArgs = [] }) { const packageAccessibleBinaries = await getPackageAccessibleBinaries(locator, { project }); const binary = packageAccessibleBinaries.get(binaryName); if (!binary) throw new Error(`Binary not found (${binaryName}) for ${structUtils.prettyLocator(project.configuration, locator)}`); return await fslib_2.xfs.mktempPromise(async (binFolder) => { const [, binaryPath] = binary; const env = await makeScriptEnv({ project, binFolder }); await Promise.all(Array.from(packageAccessibleBinaries, ([binaryName, [, binaryPath]]) => makePathWrapper(env.BERRY_BIN_FOLDER, fslib_2.toFilename(binaryName), process.execPath, [binaryPath]))); let result; try { result = await execUtils.pipevp(process.execPath, [...nodeArgs, binaryPath, ...args], { cwd, env, stdin, stdout, stderr }); } finally { await fslib_2.xfs.removePromise(env.BERRY_BIN_FOLDER); } return result.code; }); } exports.executePackageAccessibleBinary = executePackageAccessibleBinary; /** * Execute a binary from the specified workspace * * @param workspace The queried package * @param binaryName The name of the binary file to execute * @param args The arguments to pass to the file */ async function executeWorkspaceAccessibleBinary(workspace, binaryName, args, { cwd, stdin, stdout, stderr }) { return await executePackageAccessibleBinary(workspace.anchoredLocator, binaryName, args, { project: workspace.project, cwd, stdin, stdout, stderr }); } exports.executeWorkspaceAccessibleBinary = executeWorkspaceAccessibleBinary; /***/ }), /***/ 51201: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.validRange = exports.satisfiesWithPrereleases = void 0; const tslib_1 = __webpack_require__(70655); const semver_1 = tslib_1.__importDefault(__webpack_require__(74451)); /** * Returns whether the given semver version satisfies the given range. Notably * this supports prerelease versions so that "2.0.0-rc.0" satisfies the range * ">=1.0.0", for example. * * This function exists because the semver.satisfies method does not include * pre releases. This means ranges such as * would not satisfy 1.0.0-rc. The * includePrerelease flag has a weird behavior and cannot be used (if you want * to try it out, just run the `semverUtils` testsuite using this flag instead * of our own implementation, and you'll see the failing cases). * * See https://github.com/yarnpkg/berry/issues/575 for more context. */ function satisfiesWithPrereleases(version, range, loose = false) { let semverRange; try { semverRange = new semver_1.default.Range(range, { includePrerelease: true, loose }); } catch (err) { return false; } if (!version) return false; let semverVersion; try { semverVersion = new semver_1.default.SemVer(version, semverRange); if (semverVersion.prerelease) { semverVersion.prerelease = []; } } catch (err) { return false; } // A range has multiple sets of comparators. A version must satisfy all // comparators in a set and at least one set to satisfy the range. return semverRange.set.some(comparatorSet => { for (const comparator of comparatorSet) if (comparator.semver.prerelease) comparator.semver.prerelease = []; return comparatorSet.every(comparator => { return comparator.test(semverVersion); }); }); } exports.satisfiesWithPrereleases = satisfiesWithPrereleases; const rangesCache = new Map(); /** * A cached version of `new semver.Range(potentialRange)` that returns `null` on invalid ranges */ function validRange(potentialRange) { if (potentialRange.indexOf(`:`) !== -1) return null; let range = rangesCache.get(potentialRange); if (typeof range !== `undefined`) return range; try { range = new semver_1.default.Range(potentialRange); } catch (_a) { range = null; } rangesCache.set(potentialRange, range); return range; } exports.validRange = validRange; /***/ }), /***/ 34103: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getIdentVendorPath = exports.prettyDependent = exports.prettyResolution = exports.prettyWorkspace = exports.sortDescriptors = exports.prettyLocatorNoColors = exports.prettyLocator = exports.prettyReference = exports.prettyDescriptor = exports.prettyRange = exports.prettyIdent = exports.slugifyLocator = exports.slugifyIdent = exports.stringifyLocator = exports.stringifyDescriptor = exports.stringifyIdent = exports.requirableIdent = exports.convertToManifestRange = exports.makeRange = exports.parseFileStyleRange = exports.parseRange = exports.tryParseLocator = exports.parseLocator = exports.tryParseDescriptor = exports.parseDescriptor = exports.tryParseIdent = exports.parseIdent = exports.areVirtualPackagesEquivalent = exports.areLocatorsEqual = exports.areDescriptorsEqual = exports.areIdentsEqual = exports.bindLocator = exports.bindDescriptor = exports.devirtualizeLocator = exports.devirtualizeDescriptor = exports.isVirtualLocator = exports.isVirtualDescriptor = exports.virtualizePackage = exports.virtualizeDescriptor = exports.copyPackage = exports.renamePackage = exports.convertPackageToLocator = exports.convertLocatorToDescriptor = exports.convertDescriptorToLocator = exports.convertToIdent = exports.makeLocator = exports.makeDescriptor = exports.makeIdent = void 0; const tslib_1 = __webpack_require__(70655); const fslib_1 = __webpack_require__(91794); const querystring_1 = tslib_1.__importDefault(__webpack_require__(63477)); const semver_1 = tslib_1.__importDefault(__webpack_require__(74451)); const formatUtils = tslib_1.__importStar(__webpack_require__(23821)); const hashUtils = tslib_1.__importStar(__webpack_require__(73279)); const miscUtils = tslib_1.__importStar(__webpack_require__(63111)); const structUtils = tslib_1.__importStar(__webpack_require__(34103)); const VIRTUAL_PROTOCOL = `virtual:`; const VIRTUAL_ABBREVIATE = 5; /** * Creates a package ident. * * @param scope The package scope without the `@` prefix (eg. `types`) * @param name The name of the package */ function makeIdent(scope, name) { if (scope === null || scope === void 0 ? void 0 : scope.startsWith(`@`)) throw new Error(`Invalid scope: don't prefix it with '@'`); return { identHash: hashUtils.makeHash(scope, name), scope, name }; } exports.makeIdent = makeIdent; /** * Creates a package descriptor. * * @param ident The base ident (see `makeIdent`) * @param range The range to attach (eg. `^1.0.0`) */ function makeDescriptor(ident, range) { return { identHash: ident.identHash, scope: ident.scope, name: ident.name, descriptorHash: hashUtils.makeHash(ident.identHash, range), range }; } exports.makeDescriptor = makeDescriptor; /** * Creates a package locator. * * @param ident The base ident (see `makeIdent`) * @param range The reference to attach (eg. `1.0.0`) */ function makeLocator(ident, reference) { return { identHash: ident.identHash, scope: ident.scope, name: ident.name, locatorHash: hashUtils.makeHash(ident.identHash, reference), reference }; } exports.makeLocator = makeLocator; /** * Turns a compatible source to an ident. You won't really have to use this * function since by virtue of structural inheritance all descriptors and * locators are already valid idents. * * This function is only useful if you absolutely need to remove the non-ident * fields from a structure before storing it somewhere. * * @param source The data structure to convert into an ident. */ function convertToIdent(source) { return { identHash: source.identHash, scope: source.scope, name: source.name }; } exports.convertToIdent = convertToIdent; /** * Turns a descriptor into a locator. * * Note that this process may be unsafe, as descriptors may reference multiple * packages, putting them at odd with locators' expected semantic. Only makes * sense when used with single-resolution protocols, for instance `file:`. * * @param descriptor The descriptor to convert into a locator. */ function convertDescriptorToLocator(descriptor) { return { identHash: descriptor.identHash, scope: descriptor.scope, name: descriptor.name, locatorHash: descriptor.descriptorHash, reference: descriptor.range }; } exports.convertDescriptorToLocator = convertDescriptorToLocator; /** * Turns a locator into a descriptor. * * This should be safe to do regardless of the locator, since all locator * references are expected to be valid descriptor ranges. * * @param locator The locator to convert into a descriptor. */ function convertLocatorToDescriptor(locator) { return { identHash: locator.identHash, scope: locator.scope, name: locator.name, descriptorHash: locator.locatorHash, range: locator.reference }; } exports.convertLocatorToDescriptor = convertLocatorToDescriptor; /** * Turns a package structure into a simple locator. You won't often need to * call this function since packages are already valid locators by virtue of * structural inheritance. * * This function is only useful if you absolutely need to remove the * non-locator fields from a structure before storing it somewhere. * * @param pkg The package to convert into a locator. */ function convertPackageToLocator(pkg) { return { identHash: pkg.identHash, scope: pkg.scope, name: pkg.name, locatorHash: pkg.locatorHash, reference: pkg.reference }; } exports.convertPackageToLocator = convertPackageToLocator; /** * Deep copies a package then change its locator to something else. * * @param pkg The source package * @param locator Its new new locator */ function renamePackage(pkg, locator) { return { identHash: locator.identHash, scope: locator.scope, name: locator.name, locatorHash: locator.locatorHash, reference: locator.reference, version: pkg.version, languageName: pkg.languageName, linkType: pkg.linkType, dependencies: new Map(pkg.dependencies), peerDependencies: new Map(pkg.peerDependencies), dependenciesMeta: new Map(pkg.dependenciesMeta), peerDependenciesMeta: new Map(pkg.peerDependenciesMeta), bin: new Map(pkg.bin), }; } exports.renamePackage = renamePackage; /** * Deep copies a package. The copy will share the same locator as the original. * * @param pkg The source package */ function copyPackage(pkg) { return renamePackage(pkg, pkg); } exports.copyPackage = copyPackage; /** * Creates a new virtual descriptor from a non virtual one. * * @param descriptor The descriptor to virtualize * @param entropy A hash that provides uniqueness to this virtualized descriptor (normally a locator hash) */ function virtualizeDescriptor(descriptor, entropy) { if (entropy.includes(`#`)) throw new Error(`Invalid entropy`); return makeDescriptor(descriptor, `virtual:${entropy}#${descriptor.range}`); } exports.virtualizeDescriptor = virtualizeDescriptor; /** * Creates a new virtual package from a non virtual one. * * @param pkg The package to virtualize * @param entropy A hash that provides uniqueness to this virtualized package (normally a locator hash) */ function virtualizePackage(pkg, entropy) { if (entropy.includes(`#`)) throw new Error(`Invalid entropy`); return renamePackage(pkg, makeLocator(pkg, `virtual:${entropy}#${pkg.reference}`)); } exports.virtualizePackage = virtualizePackage; /** * Returns `true` if the descriptor is virtual. */ function isVirtualDescriptor(descriptor) { return descriptor.range.startsWith(VIRTUAL_PROTOCOL); } exports.isVirtualDescriptor = isVirtualDescriptor; /** * Returns `true` if the locator is virtual. */ function isVirtualLocator(locator) { return locator.reference.startsWith(VIRTUAL_PROTOCOL); } exports.isVirtualLocator = isVirtualLocator; /** * Returns a new devirtualized descriptor based on a virtualized descriptor */ function devirtualizeDescriptor(descriptor) { if (!isVirtualDescriptor(descriptor)) throw new Error(`Not a virtual descriptor`); return makeDescriptor(descriptor, descriptor.range.replace(/^[^#]*#/, ``)); } exports.devirtualizeDescriptor = devirtualizeDescriptor; /** * Returns a new devirtualized locator based on a virtualized locator * @param locator the locator */ function devirtualizeLocator(locator) { if (!isVirtualLocator(locator)) throw new Error(`Not a virtual descriptor`); return makeLocator(locator, locator.reference.replace(/^[^#]*#/, ``)); } exports.devirtualizeLocator = devirtualizeLocator; /** * Some descriptors only make sense when bound with some internal state. For * instance that would be the case for the `file:` ranges, which require to * be bound to their parent packages in order to resolve relative paths from * the right location. * * This function will apply the specified parameters onto the requested * descriptor, but only if it didn't get bound before (important to handle the * case where we replace a descriptor by another, since when that happens the * replacement has probably been already bound). * * @param descriptor The original descriptor * @param params The parameters to encode in the range */ function bindDescriptor(descriptor, params) { if (descriptor.range.includes(`::`)) return descriptor; return makeDescriptor(descriptor, `${descriptor.range}::${querystring_1.default.stringify(params)}`); } exports.bindDescriptor = bindDescriptor; /** * Some locators only make sense when bound with some internal state. For * instance that would be the case for the `file:` references, which require to * be bound to their parent packages in order to resolve relative paths from * the right location. * * This function will apply the specified parameters onto the requested * locator, but only if it didn't get bound before (important to handle the * case where we replace a locator by another, since when that happens the * replacement has probably been already bound). * * @param locator The original locator * @param params The parameters to encode in the reference */ function bindLocator(locator, params) { if (locator.reference.includes(`::`)) return locator; return makeLocator(locator, `${locator.reference}::${querystring_1.default.stringify(params)}`); } exports.bindLocator = bindLocator; /** * Returns `true` if the idents are equal */ function areIdentsEqual(a, b) { return a.identHash === b.identHash; } exports.areIdentsEqual = areIdentsEqual; /** * Returns `true` if the descriptors are equal */ function areDescriptorsEqual(a, b) { return a.descriptorHash === b.descriptorHash; } exports.areDescriptorsEqual = areDescriptorsEqual; /** * Returns `true` if the locators are equal */ function areLocatorsEqual(a, b) { return a.locatorHash === b.locatorHash; } exports.areLocatorsEqual = areLocatorsEqual; /** * Virtual packages are considered equivalent when they belong to the same * package identity and have the same dependencies. Note that equivalence * is not the same as equality, as the references may be different. */ function areVirtualPackagesEquivalent(a, b) { if (!isVirtualLocator(a)) throw new Error(`Invalid package type`); if (!isVirtualLocator(b)) throw new Error(`Invalid package type`); if (!areIdentsEqual(a, b)) return false; if (a.dependencies.size !== b.dependencies.size) return false; for (const dependencyDescriptorA of a.dependencies.values()) { const dependencyDescriptorB = b.dependencies.get(dependencyDescriptorA.identHash); if (!dependencyDescriptorB) return false; if (!areDescriptorsEqual(dependencyDescriptorA, dependencyDescriptorB)) { return false; } } return true; } exports.areVirtualPackagesEquivalent = areVirtualPackagesEquivalent; /** * Parses a string into an ident. * * Throws an error if the ident cannot be parsed. * * @param string The ident string (eg. `@types/lodash`) */ function parseIdent(string) { const ident = tryParseIdent(string); if (!ident) throw new Error(`Invalid ident (${string})`); return ident; } exports.parseIdent = parseIdent; /** * Parses a string into an ident. * * Returns `null` if the ident cannot be parsed. * * @param string The ident string (eg. `@types/lodash`) */ function tryParseIdent(string) { const match = string.match(/^(?:@([^/]+?)\/)?([^/]+)$/); if (!match) return null; const [, scope, name] = match; const realScope = typeof scope !== `undefined` ? scope : null; return makeIdent(realScope, name); } exports.tryParseIdent = tryParseIdent; /** * Parses a `string` into a descriptor * * Throws an error if the descriptor cannot be parsed. * * @param string The descriptor string (eg. `lodash@^1.0.0`) * @param strict If `false`, the range is optional (`unknown` will be used as fallback) */ function parseDescriptor(string, strict = false) { const descriptor = tryParseDescriptor(string, strict); if (!descriptor) throw new Error(`Invalid descriptor (${string})`); return descriptor; } exports.parseDescriptor = parseDescriptor; /** * Parses a `string` into a descriptor * * Returns `null` if the descriptor cannot be parsed. * * @param string The descriptor string (eg. `lodash@^1.0.0`) * @param strict If `false`, the range is optional (`unknown` will be used as fallback) */ function tryParseDescriptor(string, strict = false) { const match = strict ? string.match(/^(?:@([^/]+?)\/)?([^/]+?)(?:@(.+))$/) : string.match(/^(?:@([^/]+?)\/)?([^/]+?)(?:@(.+))?$/); if (!match) return null; const [, scope, name, range] = match; if (range === `unknown`) throw new Error(`Invalid range (${string})`); const realScope = typeof scope !== `undefined` ? scope : null; const realRange = typeof range !== `undefined` ? range : `unknown`; return makeDescriptor(makeIdent(realScope, name), realRange); } exports.tryParseDescriptor = tryParseDescriptor; /** * Parses a `string` into a locator * * Throws an error if the locator cannot be parsed. * * @param string The locator `string` (eg. `lodash@1.0.0`) * @param strict If `false`, the reference is optional (`unknown` will be used as fallback) */ function parseLocator(string, strict = false) { const locator = tryParseLocator(string, strict); if (!locator) throw new Error(`Invalid locator (${string})`); return locator; } exports.parseLocator = parseLocator; /** * Parses a `string` into a locator * * Returns `null` if the locator cannot be parsed. * * @param string The locator string (eg. `lodash@1.0.0`) * @param strict If `false`, the reference is optional (`unknown` will be used as fallback) */ function tryParseLocator(string, strict = false) { const match = strict ? string.match(/^(?:@([^/]+?)\/)?([^/]+?)(?:@(.+))$/) : string.match(/^(?:@([^/]+?)\/)?([^/]+?)(?:@(.+))?$/); if (!match) return null; const [, scope, name, reference] = match; if (reference === `unknown`) throw new Error(`Invalid reference (${string})`); const realScope = typeof scope !== `undefined` ? scope : null; const realReference = typeof reference !== `undefined` ? reference : `unknown`; return makeLocator(makeIdent(realScope, name), realReference); } exports.tryParseLocator = tryParseLocator; /** * Parses a range into its constituents. Ranges typically follow these forms, * with both `protocol` and `bindings` being optionals: * * ::: * :#:: * * The selector is intended to "refine" the source, and is required. The source * itself is optional (for instance we don't need it for npm packages, but we * do for git dependencies). */ function parseRange(range, opts) { const match = range.match(/^([^#:]*:)?((?:(?!::)[^#])*)(?:#((?:(?!::).)*))?(?:::(.*))?$/); if (match === null) throw new Error(`Invalid range (${range})`); const protocol = typeof match[1] !== `undefined` ? match[1] : null; if (typeof (opts === null || opts === void 0 ? void 0 : opts.requireProtocol) === `string` && protocol !== opts.requireProtocol) throw new Error(`Invalid protocol (${protocol})`); else if ((opts === null || opts === void 0 ? void 0 : opts.requireProtocol) && protocol === null) throw new Error(`Missing protocol (${protocol})`); const source = typeof match[3] !== `undefined` ? decodeURIComponent(match[2]) : null; if ((opts === null || opts === void 0 ? void 0 : opts.requireSource) && source === null) throw new Error(`Missing source (${range})`); const rawSelector = typeof match[3] !== `undefined` ? decodeURIComponent(match[3]) : decodeURIComponent(match[2]); const selector = (opts === null || opts === void 0 ? void 0 : opts.parseSelector) ? querystring_1.default.parse(rawSelector) : rawSelector; const params = typeof match[4] !== `undefined` ? querystring_1.default.parse(match[4]) : null; return { // @ts-expect-error protocol, // @ts-expect-error source, // @ts-expect-error selector, // @ts-expect-error params, }; } exports.parseRange = parseRange; /** * File-style ranges are bound to a parent locators that we need in order to * resolve relative paths to the location of their parent packages. This * function wraps `parseRange` to automatically extract the parent locator * from the bindings and return it along with the selector. */ function parseFileStyleRange(range, { protocol }) { const { selector, params } = parseRange(range, { requireProtocol: protocol, requireBindings: true, }); if (typeof params.locator !== `string`) throw new Error(`Assertion failed: Invalid bindings for ${range}`); const parentLocator = parseLocator(params.locator, true); const path = selector; return { parentLocator, path }; } exports.parseFileStyleRange = parseFileStyleRange; function encodeUnsafeCharacters(str) { str = str.replace(/%/g, `%25`); str = str.replace(/:/g, `%3A`); str = str.replace(/#/g, `%23`); return str; } function hasParams(params) { if (params === null) return false; return Object.entries(params).length > 0; } /** * Turn the components returned by `parseRange` back into a string. Check * `parseRange` for more details. */ function makeRange({ protocol, source, selector, params }) { let range = ``; if (protocol !== null) range += `${protocol}`; if (source !== null) range += `${encodeUnsafeCharacters(source)}#`; range += encodeUnsafeCharacters(selector); if (hasParams(params)) range += `::${querystring_1.default.stringify(params)}`; return range; } exports.makeRange = makeRange; /** * Some bindings are internal-only and not meant to be displayed anywhere (for * instance that's the case with the parent locator bound to the `file:` ranges). * * this function strips them from a range. */ function convertToManifestRange(range) { const { params, protocol, source, selector } = parseRange(range); for (const name in params) if (name.startsWith(`__`)) delete params[name]; return makeRange({ protocol, source, params, selector }); } exports.convertToManifestRange = convertToManifestRange; /** * @deprecated Prefer using `stringifyIdent` */ function requirableIdent(ident) { if (ident.scope) { return `@${ident.scope}/${ident.name}`; } else { return `${ident.name}`; } } exports.requirableIdent = requirableIdent; /** * Returns a string from an ident (eg. `@types/lodash`). */ function stringifyIdent(ident) { if (ident.scope) { return `@${ident.scope}/${ident.name}`; } else { return `${ident.name}`; } } exports.stringifyIdent = stringifyIdent; /** * Returns a string from a descriptor (eg. `@types/lodash@^1.0.0`). */ function stringifyDescriptor(descriptor) { if (descriptor.scope) { return `@${descriptor.scope}/${descriptor.name}@${descriptor.range}`; } else { return `${descriptor.name}@${descriptor.range}`; } } exports.stringifyDescriptor = stringifyDescriptor; /** * Returns a string from a descriptor (eg. `@types/lodash@1.0.0`). */ function stringifyLocator(locator) { if (locator.scope) { return `@${locator.scope}/${locator.name}@${locator.reference}`; } else { return `${locator.name}@${locator.reference}`; } } exports.stringifyLocator = stringifyLocator; /** * Returns a string from an ident, formatted as a slug (eg. `@types-lodash`). */ function slugifyIdent(ident) { if (ident.scope !== null) { return `@${ident.scope}-${ident.name}`; } else { return ident.name; } } exports.slugifyIdent = slugifyIdent; /** * Returns a string from a locator, formatted as a slug (eg. `@types-lodash-npm-1.0.0-abcdef1234`). */ function slugifyLocator(locator) { const { protocol, selector } = parseRange(locator.reference); const humanProtocol = protocol !== null ? protocol.replace(/:$/, ``) : `exotic`; const humanVersion = semver_1.default.valid(selector); const humanReference = humanVersion !== null ? `${humanProtocol}-${humanVersion}` : `${humanProtocol}`; // 10 hex characters means that 47 different entries have 10^-9 chances of // causing a hash collision. Since this hash is joined with the package name // (making it highly unlikely you'll have more than a handful of instances // of any single package), this should provide a good enough guard in most // cases. // // Also note that eCryptfs eats some bytes, so the theoretical maximum for a // file size is around 140 bytes (but we don't need as much, as explained). const hashTruncate = 10; const slug = locator.scope ? `${slugifyIdent(locator)}-${humanReference}-${locator.locatorHash.slice(0, hashTruncate)}` : `${slugifyIdent(locator)}-${humanReference}-${locator.locatorHash.slice(0, hashTruncate)}`; return fslib_1.toFilename(slug); } exports.slugifyLocator = slugifyLocator; /** * Returns a string that is suitable to be printed to stdout. Based on the * configuration it may include color sequences. * * @param configuration Reference configuration * @param ident The ident to pretty print */ function prettyIdent(configuration, ident) { if (ident.scope) { return `${formatUtils.pretty(configuration, `@${ident.scope}/`, formatUtils.Type.SCOPE)}${formatUtils.pretty(configuration, ident.name, formatUtils.Type.NAME)}`; } else { return `${formatUtils.pretty(configuration, ident.name, formatUtils.Type.NAME)}`; } } exports.prettyIdent = prettyIdent; function prettyRangeNoColors(range) { if (range.startsWith(VIRTUAL_PROTOCOL)) { const nested = prettyRangeNoColors(range.substr(range.indexOf(`#`) + 1)); const abbrev = range.substr(VIRTUAL_PROTOCOL.length, VIRTUAL_ABBREVIATE); // I'm not satisfied of how the virtual packages appear in the output // eslint-disable-next-line no-constant-condition return false ? 0 : `${nested} [${abbrev}]`; } else { return range.replace(/\?.*/, `?[...]`); } } /** * Returns a string that is suitable to be printed to stdout. Based on the * configuration it may include color sequences. * * @param configuration Reference configuration * @param ident The range to pretty print */ function prettyRange(configuration, range) { return `${formatUtils.pretty(configuration, prettyRangeNoColors(range), formatUtils.Type.RANGE)}`; } exports.prettyRange = prettyRange; /** * Returns a string that is suitable to be printed to stdout. Based on the * configuration it may include color sequences. * * @param configuration Reference configuration * @param descriptor The descriptor to pretty print */ function prettyDescriptor(configuration, descriptor) { return `${prettyIdent(configuration, descriptor)}${formatUtils.pretty(configuration, `@`, formatUtils.Type.RANGE)}${prettyRange(configuration, descriptor.range)}`; } exports.prettyDescriptor = prettyDescriptor; /** * Returns a string that is suitable to be printed to stdout. Based on the * configuration it may include color sequences. * * @param configuration Reference configuration * @param reference The reference to pretty print */ function prettyReference(configuration, reference) { return `${formatUtils.pretty(configuration, prettyRangeNoColors(reference), formatUtils.Type.REFERENCE)}`; } exports.prettyReference = prettyReference; /** * Returns a string that is suitable to be printed to stdout. Based on the * configuration it may include color sequences. * * @param configuration Reference configuration * @param locator The locator to pretty print */ function prettyLocator(configuration, locator) { return `${prettyIdent(configuration, locator)}${formatUtils.pretty(configuration, `@`, formatUtils.Type.REFERENCE)}${prettyReference(configuration, locator.reference)}`; } exports.prettyLocator = prettyLocator; /** * Returns a string that is suitable to be printed to stdout. It will never * be colored. * * @param locator The locator to pretty print */ function prettyLocatorNoColors(locator) { return `${stringifyIdent(locator)}@${prettyRangeNoColors(locator.reference)}`; } exports.prettyLocatorNoColors = prettyLocatorNoColors; /** * Sorts a list of descriptors, first by their idents then by their ranges. */ function sortDescriptors(descriptors) { return miscUtils.sortMap(descriptors, [ descriptor => stringifyIdent(descriptor), descriptor => descriptor.range, ]); } exports.sortDescriptors = sortDescriptors; /** * Returns a string that is suitable to be printed to stdout. Based on the * configuration it may include color sequences. * * @param configuration Reference configuration * @param workspace The workspace to pretty print */ function prettyWorkspace(configuration, workspace) { return prettyIdent(configuration, workspace.locator); } exports.prettyWorkspace = prettyWorkspace; /** * Returns a string that is suitable to be printed to stdout. Based on the * configuration it may include color sequences. * * @param configuration Reference configuration * @param descriptor The descriptor to pretty print * @param locator The locator is resolves to */ function prettyResolution(configuration, descriptor, locator) { const devirtualizedDescriptor = isVirtualDescriptor(descriptor) ? devirtualizeDescriptor(descriptor) : descriptor; if (locator === null) { return `${structUtils.prettyDescriptor(configuration, devirtualizedDescriptor)} → ${formatUtils.mark(configuration).Cross}`; } else if (devirtualizedDescriptor.identHash === locator.identHash) { return `${structUtils.prettyDescriptor(configuration, devirtualizedDescriptor)} → ${prettyReference(configuration, locator.reference)}`; } else { return `${structUtils.prettyDescriptor(configuration, devirtualizedDescriptor)} → ${prettyLocator(configuration, locator)}`; } } exports.prettyResolution = prettyResolution; /** * Returns a string that is suitable to be printed to stdout. Based on the * configuration it may include color sequences. * * @param configuration Reference configuration * @param locator The locator to pretty print * @param descriptor The descriptor that depends on it */ function prettyDependent(configuration, locator, descriptor) { if (descriptor === null) { return `${prettyLocator(configuration, locator)}`; } else { return `${prettyLocator(configuration, locator)} (via ${structUtils.prettyRange(configuration, descriptor.range)})`; } } exports.prettyDependent = prettyDependent; /** * The presence of a `node_modules` directory in the path is extremely common * in the JavaScript ecosystem to denote whether a path belongs to a vendor * or not. I considered using a more generic path for packages that aren't * always JS-only (such as when using the Git fetcher), but that unfortunately * caused various JS apps to start showing errors when working with git repos. * * As a result, all packages from all languages will follow this convention. At * least it'll be consistent, and linkers will always have the ability to remap * them to a different location if that's a critical requirement. */ function getIdentVendorPath(ident) { return `node_modules/${requirableIdent(ident)}`; } exports.getIdentVendorPath = getIdentVendorPath; /***/ }), /***/ 83607: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.extractArchiveTo = exports.convertToZip = exports.makeArchiveFromDirectory = void 0; const tslib_1 = __webpack_require__(70655); const fslib_1 = __webpack_require__(91794); const libzip_1 = __webpack_require__(40364); const tar_stream_1 = tslib_1.__importDefault(__webpack_require__(53871)); const util_1 = __webpack_require__(73837); const zlib_1 = tslib_1.__importDefault(__webpack_require__(59796)); const gunzip = util_1.promisify(zlib_1.default.gunzip); async function makeArchiveFromDirectory(source, { baseFs = new fslib_1.NodeFS(), prefixPath = fslib_1.PortablePath.root, compressionLevel, inMemory = false } = {}) { const libzip = await libzip_1.getLibzipPromise(); let zipFs; if (inMemory) { zipFs = new fslib_1.ZipFS(null, { libzip, level: compressionLevel }); } else { const tmpFolder = await fslib_1.xfs.mktempPromise(); const tmpFile = fslib_1.ppath.join(tmpFolder, `archive.zip`); zipFs = new fslib_1.ZipFS(tmpFile, { create: true, libzip, level: compressionLevel }); } const target = fslib_1.ppath.resolve(fslib_1.PortablePath.root, prefixPath); await zipFs.copyPromise(target, source, { baseFs, stableTime: true, stableSort: true }); return zipFs; } exports.makeArchiveFromDirectory = makeArchiveFromDirectory; async function convertToZip(tgz, opts) { const tmpFolder = await fslib_1.xfs.mktempPromise(); const tmpFile = fslib_1.ppath.join(tmpFolder, `archive.zip`); const { compressionLevel, ...bufferOpts } = opts; return await extractArchiveTo(tgz, new fslib_1.ZipFS(tmpFile, { create: true, libzip: await libzip_1.getLibzipPromise(), level: compressionLevel }), bufferOpts); } exports.convertToZip = convertToZip; async function extractArchiveTo(tgz, targetFs, { stripComponents = 0, prefixPath = fslib_1.PortablePath.dot } = {}) { // 1980-01-01, like Fedora const defaultTime = 315532800; const parser = tar_stream_1.default.extract(); function ignore(entry) { // Disallow absolute paths; might be malicious (ex: /etc/passwd) if (entry.name[0] === `/`) return true; const parts = entry.name.split(/\//g); // We also ignore paths that could lead to escaping outside the archive if (parts.some((part) => part === `..`)) return true; if (parts.length <= stripComponents) return true; return false; } parser.on(`entry`, (header, stream, next) => { var _a, _b; if (ignore(header)) { next(); return; } const parts = fslib_1.ppath.normalize(fslib_1.npath.toPortablePath(header.name)).replace(/\/$/, ``).split(/\//g); if (parts.length <= stripComponents) { stream.resume(); next(); return; } const slicePath = parts.slice(stripComponents).join(`/`); const mappedPath = fslib_1.ppath.join(prefixPath, slicePath); let mode = 0o644; // If a single executable bit is set, normalize so that all are if (header.type === `directory` || (((_a = header.mode) !== null && _a !== void 0 ? _a : 0) & 0o111) !== 0) mode |= 0o111; switch (header.type) { case `directory`: { targetFs.mkdirpSync(fslib_1.ppath.dirname(mappedPath), { chmod: 0o755, utimes: [defaultTime, defaultTime] }); targetFs.mkdirSync(mappedPath); targetFs.chmodSync(mappedPath, mode); targetFs.utimesSync(mappedPath, defaultTime, defaultTime); next(); } break; case `file`: { targetFs.mkdirpSync(fslib_1.ppath.dirname(mappedPath), { chmod: 0o755, utimes: [defaultTime, defaultTime] }); const chunks = []; stream.on(`data`, (chunk) => chunks.push(chunk)); stream.on(`end`, () => { targetFs.writeFileSync(mappedPath, Buffer.concat(chunks)); targetFs.chmodSync(mappedPath, mode); targetFs.utimesSync(mappedPath, defaultTime, defaultTime); next(); }); } break; case `symlink`: { targetFs.mkdirpSync(fslib_1.ppath.dirname(mappedPath), { chmod: 0o755, utimes: [defaultTime, defaultTime] }); targetFs.symlinkSync(header.linkname, mappedPath); (_b = targetFs.lutimesSync) === null || _b === void 0 ? void 0 : _b.call(targetFs, mappedPath, defaultTime, defaultTime); next(); } break; default: { stream.resume(); next(); } } }); const gunzipped = await gunzip(tgz); return await new Promise((resolve, reject) => { parser.on(`error`, (error) => { reject(error); }); parser.on(`finish`, () => { resolve(targetFs); }); parser.end(gunzipped); }); } exports.extractArchiveTo = extractArchiveTo; /***/ }), /***/ 55024: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.emitTree = exports.emitList = exports.treeNodeToJson = exports.treeNodeToTreeify = void 0; const tslib_1 = __webpack_require__(70655); const treeify_1 = __webpack_require__(99269); const formatUtils = tslib_1.__importStar(__webpack_require__(23821)); function treeNodeToTreeify(printTree, { configuration }) { const target = {}; const copyTree = (printNode, targetNode) => { const iterator = Array.isArray(printNode) ? printNode.entries() : Object.entries(printNode); for (const [key, { label, value, children }] of iterator) { const finalParts = []; if (typeof label !== `undefined`) finalParts.push(formatUtils.applyStyle(configuration, label, formatUtils.Style.BOLD)); if (typeof value !== `undefined`) finalParts.push(formatUtils.pretty(configuration, value[0], value[1])); if (finalParts.length === 0) finalParts.push(formatUtils.applyStyle(configuration, `${key}`, formatUtils.Style.BOLD)); const finalLabel = finalParts.join(`: `); const createdNode = targetNode[finalLabel] = {}; if (typeof children !== `undefined`) { copyTree(children, createdNode); } } }; if (typeof printTree.children === `undefined`) throw new Error(`The root node must only contain children`); copyTree(printTree.children, target); return target; } exports.treeNodeToTreeify = treeNodeToTreeify; function treeNodeToJson(printTree) { const copyTree = (printNode) => { var _a; if (typeof printNode.children === `undefined`) { if (typeof printNode.value === `undefined`) throw new Error(`Assertion failed: Expected a value to be set if the children are missing`); return formatUtils.json(printNode.value[0], printNode.value[1]); } const iterator = Array.isArray(printNode.children) ? printNode.children.entries() : Object.entries((_a = printNode.children) !== null && _a !== void 0 ? _a : {}); const targetChildren = Array.isArray(printNode.children) ? [] : {}; for (const [key, child] of iterator) targetChildren[key] = copyTree(child); if (typeof printNode.value === `undefined`) return targetChildren; return { value: formatUtils.json(printNode.value[0], printNode.value[1]), children: targetChildren, }; }; return copyTree(printTree); } exports.treeNodeToJson = treeNodeToJson; function emitList(values, { configuration, stdout, json }) { const children = values.map(value => ({ value })); emitTree({ children }, { configuration, stdout, json }); } exports.emitList = emitList; function emitTree(tree, { configuration, stdout, json, separators = 0 }) { var _a; if (json) { const iterator = Array.isArray(tree.children) ? tree.children.values() : Object.values((_a = tree.children) !== null && _a !== void 0 ? _a : {}); for (const child of iterator) stdout.write(`${JSON.stringify(treeNodeToJson(child))}\n`); return; } let treeOutput = treeify_1.asTree(treeNodeToTreeify(tree, { configuration }), false, false); // A slight hack to add line returns between two top-level entries if (separators >= 1) treeOutput = treeOutput.replace(/^([├└]─)/gm, `│\n$1`).replace(/^│\n/, ``); // Another one for the second level fields. We run it twice because in some pathological cases the regex matches would if (separators >= 2) for (let t = 0; t < 2; ++t) treeOutput = treeOutput.replace(/^([│ ].{2}[├│ ].{2}[^\n]+\n)(([│ ]).{2}[├└].{2}[^\n]*\n[│ ].{2}[│ ].{2}[├└]─)/gm, `$1$3 │\n$2`).replace(/^│\n/, ``); if (separators >= 3) throw new Error(`Only the first two levels are accepted by treeUtils.emitTree`); stdout.write(treeOutput); } exports.emitTree = emitTree; /***/ }), /***/ 79588: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PackageExtensionStatus = exports.PackageExtensionType = exports.LinkType = void 0; /** * Describes in which capacity the linkers can manipulate the package sources. */ var LinkType; (function (LinkType) { /** * The package manager owns the location (typically things within the cache) * and can transform it at will (for instance the PnP linker may decide to * unplug those packages). */ LinkType["HARD"] = "HARD"; /** * The package manager doesn't own the location (symlinks, workspaces, etc), * so the linkers aren't allowed to do anything with them except use them as * they are. */ LinkType["SOFT"] = "SOFT"; })(LinkType = exports.LinkType || (exports.LinkType = {})); var PackageExtensionType; (function (PackageExtensionType) { PackageExtensionType["Dependency"] = "Dependency"; PackageExtensionType["PeerDependency"] = "PeerDependency"; PackageExtensionType["PeerDependencyMeta"] = "PeerDependencyMeta"; })(PackageExtensionType = exports.PackageExtensionType || (exports.PackageExtensionType = {})); var PackageExtensionStatus; (function (PackageExtensionStatus) { PackageExtensionStatus["Inactive"] = "inactive"; PackageExtensionStatus["Redundant"] = "redundant"; PackageExtensionStatus["Active"] = "active"; })(PackageExtensionStatus = exports.PackageExtensionStatus || (exports.PackageExtensionStatus = {})); /***/ }), /***/ 14843: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* module decorator */ module = __webpack_require__.nmd(module); const wrapAnsi16 = (fn, offset) => (...args) => { const code = fn(...args); return `\u001B[${code + offset}m`; }; const wrapAnsi256 = (fn, offset) => (...args) => { const code = fn(...args); return `\u001B[${38 + offset};5;${code}m`; }; const wrapAnsi16m = (fn, offset) => (...args) => { const rgb = fn(...args); return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; }; const ansi2ansi = n => n; const rgb2rgb = (r, g, b) => [r, g, b]; const setLazyProperty = (object, property, get) => { Object.defineProperty(object, property, { get: () => { const value = get(); Object.defineProperty(object, property, { value, enumerable: true, configurable: true }); return value; }, enumerable: true, configurable: true }); }; /** @type {typeof import('color-convert')} */ let colorConvert; const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { if (colorConvert === undefined) { colorConvert = __webpack_require__(12581); } const offset = isBackground ? 10 : 0; const styles = {}; for (const [sourceSpace, suite] of Object.entries(colorConvert)) { const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; if (sourceSpace === targetSpace) { styles[name] = wrap(identity, offset); } else if (typeof suite === 'object') { styles[name] = wrap(suite[targetSpace], offset); } } return styles; }; function assembleStyles() { const codes = new Map(); const styles = { modifier: { reset: [0, 0], // 21 isn't widely supported and 22 does the same thing bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29] }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], // Bright color blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // Bright color bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } }; // Alias bright black as gray (and grey) styles.color.gray = styles.color.blackBright; styles.bgColor.bgGray = styles.bgColor.bgBlackBright; styles.color.grey = styles.color.blackBright; styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; for (const [groupName, group] of Object.entries(styles)) { for (const [styleName, style] of Object.entries(group)) { styles[styleName] = { open: `\u001B[${style[0]}m`, close: `\u001B[${style[1]}m` }; group[styleName] = styles[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles, groupName, { value: group, enumerable: false }); } Object.defineProperty(styles, 'codes', { value: codes, enumerable: false }); styles.color.close = '\u001B[39m'; styles.bgColor.close = '\u001B[49m'; setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); return styles; } // Make the export immutable Object.defineProperty(module, 'exports', { enumerable: true, get: assembleStyles }); /***/ }), /***/ 35399: /***/ ((module) => { "use strict"; const preserveCamelCase = string => { let isLastCharLower = false; let isLastCharUpper = false; let isLastLastCharUpper = false; for (let i = 0; i < string.length; i++) { const character = string[i]; if (isLastCharLower && /[a-zA-Z]/.test(character) && character.toUpperCase() === character) { string = string.slice(0, i) + '-' + string.slice(i); isLastCharLower = false; isLastLastCharUpper = isLastCharUpper; isLastCharUpper = true; i++; } else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(character) && character.toLowerCase() === character) { string = string.slice(0, i - 1) + '-' + string.slice(i - 1); isLastLastCharUpper = isLastCharUpper; isLastCharUpper = false; isLastCharLower = true; } else { isLastCharLower = character.toLowerCase() === character && character.toUpperCase() !== character; isLastLastCharUpper = isLastCharUpper; isLastCharUpper = character.toUpperCase() === character && character.toLowerCase() !== character; } } return string; }; const camelCase = (input, options) => { if (!(typeof input === 'string' || Array.isArray(input))) { throw new TypeError('Expected the input to be `string | string[]`'); } options = Object.assign({ pascalCase: false }, options); const postProcess = x => options.pascalCase ? x.charAt(0).toUpperCase() + x.slice(1) : x; if (Array.isArray(input)) { input = input.map(x => x.trim()) .filter(x => x.length) .join('-'); } else { input = input.trim(); } if (input.length === 0) { return ''; } if (input.length === 1) { return options.pascalCase ? input.toUpperCase() : input.toLowerCase(); } const hasUpperCase = input !== input.toLowerCase(); if (hasUpperCase) { input = preserveCamelCase(input); } input = input .replace(/^[_.\- ]+/, '') .toLowerCase() .replace(/[_.\- ]+(\w|$)/g, (_, p1) => p1.toUpperCase()) .replace(/\d+(\w|$)/g, m => m.toUpperCase()); return postProcess(input); }; module.exports = camelCase; // TODO: Remove this for the next major release module.exports["default"] = camelCase; /***/ }), /***/ 59084: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const ansiStyles = __webpack_require__(14843); const {stdout: stdoutColor, stderr: stderrColor} = __webpack_require__(58597); const { stringReplaceAll, stringEncaseCRLFWithFirstIndex } = __webpack_require__(6353); // `supportsColor.level` → `ansiStyles.color[name]` mapping const levelMapping = [ 'ansi', 'ansi', 'ansi256', 'ansi16m' ]; const styles = Object.create(null); const applyOptions = (object, options = {}) => { if (options.level > 3 || options.level < 0) { throw new Error('The `level` option should be an integer from 0 to 3'); } // Detect level if not set manually const colorLevel = stdoutColor ? stdoutColor.level : 0; object.level = options.level === undefined ? colorLevel : options.level; }; class ChalkClass { constructor(options) { return chalkFactory(options); } } const chalkFactory = options => { const chalk = {}; applyOptions(chalk, options); chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); Object.setPrototypeOf(chalk, Chalk.prototype); Object.setPrototypeOf(chalk.template, chalk); chalk.template.constructor = () => { throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); }; chalk.template.Instance = ChalkClass; return chalk.template; }; function Chalk(options) { return chalkFactory(options); } for (const [styleName, style] of Object.entries(ansiStyles)) { styles[styleName] = { get() { const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); Object.defineProperty(this, styleName, {value: builder}); return builder; } }; } styles.visible = { get() { const builder = createBuilder(this, this._styler, true); Object.defineProperty(this, 'visible', {value: builder}); return builder; } }; const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; for (const model of usedModels) { styles[model] = { get() { const {level} = this; return function (...arguments_) { const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler); return createBuilder(this, styler, this._isEmpty); }; } }; } for (const model of usedModels) { const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); styles[bgModel] = { get() { const {level} = this; return function (...arguments_) { const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler); return createBuilder(this, styler, this._isEmpty); }; } }; } const proto = Object.defineProperties(() => {}, { ...styles, level: { enumerable: true, get() { return this._generator.level; }, set(level) { this._generator.level = level; } } }); const createStyler = (open, close, parent) => { let openAll; let closeAll; if (parent === undefined) { openAll = open; closeAll = close; } else { openAll = parent.openAll + open; closeAll = close + parent.closeAll; } return { open, close, openAll, closeAll, parent }; }; const createBuilder = (self, _styler, _isEmpty) => { const builder = (...arguments_) => { // Single argument is hot path, implicit coercion is faster than anything // eslint-disable-next-line no-implicit-coercion return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); }; // `__proto__` is used because we must return a function, but there is // no way to create a function with a different prototype builder.__proto__ = proto; // eslint-disable-line no-proto builder._generator = self; builder._styler = _styler; builder._isEmpty = _isEmpty; return builder; }; const applyStyle = (self, string) => { if (self.level <= 0 || !string) { return self._isEmpty ? '' : string; } let styler = self._styler; if (styler === undefined) { return string; } const {openAll, closeAll} = styler; if (string.indexOf('\u001B') !== -1) { while (styler !== undefined) { // Replace any instances already present with a re-opening code // otherwise only the part of the string until said closing code // will be colored, and the rest will simply be 'plain'. string = stringReplaceAll(string, styler.close, styler.open); styler = styler.parent; } } // We can move both next actions out of loop, because remaining actions in loop won't have // any/visible effect on parts we add here. Close the styling before a linebreak and reopen // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 const lfIndex = string.indexOf('\n'); if (lfIndex !== -1) { string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); } return openAll + string + closeAll; }; let template; const chalkTag = (chalk, ...strings) => { const [firstString] = strings; if (!Array.isArray(firstString)) { // If chalk() was called by itself or with a string, // return the string itself as a string. return strings.join(' '); } const arguments_ = strings.slice(1); const parts = [firstString.raw[0]]; for (let i = 1; i < firstString.length; i++) { parts.push( String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), String(firstString.raw[i]) ); } if (template === undefined) { template = __webpack_require__(12754); } return template(chalk, parts.join('')); }; Object.defineProperties(Chalk.prototype, styles); const chalk = Chalk(); // eslint-disable-line new-cap chalk.supportsColor = stdoutColor; chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap chalk.stderr.supportsColor = stderrColor; // For TypeScript chalk.Level = { None: 0, Basic: 1, Ansi256: 2, TrueColor: 3, 0: 'None', 1: 'Basic', 2: 'Ansi256', 3: 'TrueColor' }; module.exports = chalk; /***/ }), /***/ 12754: /***/ ((module) => { "use strict"; const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.)|([^\\])/gi; const ESCAPES = new Map([ ['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007'] ]); function unescape(c) { const u = c[0] === 'u'; const bracket = c[1] === '{'; if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) { return String.fromCharCode(parseInt(c.slice(1), 16)); } if (u && bracket) { return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); } return ESCAPES.get(c) || c; } function parseArguments(name, arguments_) { const results = []; const chunks = arguments_.trim().split(/\s*,\s*/g); let matches; for (const chunk of chunks) { const number = Number(chunk); if (!Number.isNaN(number)) { results.push(number); } else if ((matches = chunk.match(STRING_REGEX))) { results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character)); } else { throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); } } return results; } function parseStyle(style) { STYLE_REGEX.lastIndex = 0; const results = []; let matches; while ((matches = STYLE_REGEX.exec(style)) !== null) { const name = matches[1]; if (matches[2]) { const args = parseArguments(name, matches[2]); results.push([name].concat(args)); } else { results.push([name]); } } return results; } function buildStyle(chalk, styles) { const enabled = {}; for (const layer of styles) { for (const style of layer.styles) { enabled[style[0]] = layer.inverse ? null : style.slice(1); } } let current = chalk; for (const [styleName, styles] of Object.entries(enabled)) { if (!Array.isArray(styles)) { continue; } if (!(styleName in current)) { throw new Error(`Unknown Chalk style: ${styleName}`); } current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; } return current; } module.exports = (chalk, temporary) => { const styles = []; const chunks = []; let chunk = []; // eslint-disable-next-line max-params temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => { if (escapeCharacter) { chunk.push(unescape(escapeCharacter)); } else if (style) { const string = chunk.join(''); chunk = []; chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string)); styles.push({inverse, styles: parseStyle(style)}); } else if (close) { if (styles.length === 0) { throw new Error('Found extraneous } in Chalk template literal'); } chunks.push(buildStyle(chalk, styles)(chunk.join(''))); chunk = []; styles.pop(); } else { chunk.push(character); } }); chunks.push(chunk.join('')); if (styles.length > 0) { const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; throw new Error(errMsg); } return chunks.join(''); }; /***/ }), /***/ 6353: /***/ ((module) => { "use strict"; const stringReplaceAll = (string, substring, replacer) => { let index = string.indexOf(substring); if (index === -1) { return string; } const substringLength = substring.length; let endIndex = 0; let returnValue = ''; do { returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; endIndex = index + substringLength; index = string.indexOf(substring, endIndex); } while (index !== -1); returnValue += string.substr(endIndex); return returnValue; }; const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => { let endIndex = 0; let returnValue = ''; do { const gotCR = string[index - 1] === '\r'; returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; endIndex = index + 1; index = string.indexOf('\n', endIndex); } while (index !== -1); returnValue += string.substr(endIndex); return returnValue; }; module.exports = { stringReplaceAll, stringEncaseCRLFWithFirstIndex }; /***/ }), /***/ 8288: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var vendors = __webpack_require__(58243) var env = process.env // Used for testing only Object.defineProperty(exports, "_vendors", ({ value: vendors.map(function (v) { return v.constant }) })) exports.name = null exports.isPR = null vendors.forEach(function (vendor) { var envs = Array.isArray(vendor.env) ? vendor.env : [vendor.env] var isCI = envs.every(function (obj) { return checkEnv(obj) }) exports[vendor.constant] = isCI if (isCI) { exports.name = vendor.name switch (typeof vendor.pr) { case 'string': // "pr": "CIRRUS_PR" exports.isPR = !!env[vendor.pr] break case 'object': if ('env' in vendor.pr) { // "pr": { "env": "BUILDKITE_PULL_REQUEST", "ne": "false" } exports.isPR = vendor.pr.env in env && env[vendor.pr.env] !== vendor.pr.ne } else if ('any' in vendor.pr) { // "pr": { "any": ["ghprbPullId", "CHANGE_ID"] } exports.isPR = vendor.pr.any.some(function (key) { return !!env[key] }) } else { // "pr": { "DRONE_BUILD_EVENT": "pull_request" } exports.isPR = checkEnv(vendor.pr) } break default: // PR detection not supported for this vendor exports.isPR = null } } }) exports.isCI = !!( env.CI || // Travis CI, CircleCI, Cirrus CI, Gitlab CI, Appveyor, CodeShip, dsari env.CONTINUOUS_INTEGRATION || // Travis CI, Cirrus CI env.BUILD_NUMBER || // Jenkins, TeamCity env.RUN_ID || // TaskCluster, dsari exports.name || false ) function checkEnv (obj) { if (typeof obj === 'string') return !!env[obj] return Object.keys(obj).every(function (k) { return env[k] === obj[k] }) } /***/ }), /***/ 24110: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /* MIT license */ /* eslint-disable no-mixed-operators */ const cssKeywords = __webpack_require__(24646); // NOTE: conversions should only return primitive values (i.e. arrays, or // values that give correct `typeof` results). // do not use box values types (i.e. Number(), String(), etc.) const reverseKeywords = {}; for (const key of Object.keys(cssKeywords)) { reverseKeywords[cssKeywords[key]] = key; } const convert = { rgb: {channels: 3, labels: 'rgb'}, hsl: {channels: 3, labels: 'hsl'}, hsv: {channels: 3, labels: 'hsv'}, hwb: {channels: 3, labels: 'hwb'}, cmyk: {channels: 4, labels: 'cmyk'}, xyz: {channels: 3, labels: 'xyz'}, lab: {channels: 3, labels: 'lab'}, lch: {channels: 3, labels: 'lch'}, hex: {channels: 1, labels: ['hex']}, keyword: {channels: 1, labels: ['keyword']}, ansi16: {channels: 1, labels: ['ansi16']}, ansi256: {channels: 1, labels: ['ansi256']}, hcg: {channels: 3, labels: ['h', 'c', 'g']}, apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, gray: {channels: 1, labels: ['gray']} }; module.exports = convert; // Hide .channels and .labels properties for (const model of Object.keys(convert)) { if (!('channels' in convert[model])) { throw new Error('missing channels property: ' + model); } if (!('labels' in convert[model])) { throw new Error('missing channel labels property: ' + model); } if (convert[model].labels.length !== convert[model].channels) { throw new Error('channel and label counts mismatch: ' + model); } const {channels, labels} = convert[model]; delete convert[model].channels; delete convert[model].labels; Object.defineProperty(convert[model], 'channels', {value: channels}); Object.defineProperty(convert[model], 'labels', {value: labels}); } convert.rgb.hsl = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const min = Math.min(r, g, b); const max = Math.max(r, g, b); const delta = max - min; let h; let s; if (max === min) { h = 0; } else if (r === max) { h = (g - b) / delta; } else if (g === max) { h = 2 + (b - r) / delta; } else if (b === max) { h = 4 + (r - g) / delta; } h = Math.min(h * 60, 360); if (h < 0) { h += 360; } const l = (min + max) / 2; if (max === min) { s = 0; } else if (l <= 0.5) { s = delta / (max + min); } else { s = delta / (2 - max - min); } return [h, s * 100, l * 100]; }; convert.rgb.hsv = function (rgb) { let rdif; let gdif; let bdif; let h; let s; const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const v = Math.max(r, g, b); const diff = v - Math.min(r, g, b); const diffc = function (c) { return (v - c) / 6 / diff + 1 / 2; }; if (diff === 0) { h = 0; s = 0; } else { s = diff / v; rdif = diffc(r); gdif = diffc(g); bdif = diffc(b); if (r === v) { h = bdif - gdif; } else if (g === v) { h = (1 / 3) + rdif - bdif; } else if (b === v) { h = (2 / 3) + gdif - rdif; } if (h < 0) { h += 1; } else if (h > 1) { h -= 1; } } return [ h * 360, s * 100, v * 100 ]; }; convert.rgb.hwb = function (rgb) { const r = rgb[0]; const g = rgb[1]; let b = rgb[2]; const h = convert.rgb.hsl(rgb)[0]; const w = 1 / 255 * Math.min(r, Math.min(g, b)); b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); return [h, w * 100, b * 100]; }; convert.rgb.cmyk = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const k = Math.min(1 - r, 1 - g, 1 - b); const c = (1 - r - k) / (1 - k) || 0; const m = (1 - g - k) / (1 - k) || 0; const y = (1 - b - k) / (1 - k) || 0; return [c * 100, m * 100, y * 100, k * 100]; }; function comparativeDistance(x, y) { /* See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance */ return ( ((x[0] - y[0]) ** 2) + ((x[1] - y[1]) ** 2) + ((x[2] - y[2]) ** 2) ); } convert.rgb.keyword = function (rgb) { const reversed = reverseKeywords[rgb]; if (reversed) { return reversed; } let currentClosestDistance = Infinity; let currentClosestKeyword; for (const keyword of Object.keys(cssKeywords)) { const value = cssKeywords[keyword]; // Compute comparative distance const distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest if (distance < currentClosestDistance) { currentClosestDistance = distance; currentClosestKeyword = keyword; } } return currentClosestKeyword; }; convert.keyword.rgb = function (keyword) { return cssKeywords[keyword]; }; convert.rgb.xyz = function (rgb) { let r = rgb[0] / 255; let g = rgb[1] / 255; let b = rgb[2] / 255; // Assume sRGB r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92); g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92); b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92); const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); return [x * 100, y * 100, z * 100]; }; convert.rgb.lab = function (rgb) { const xyz = convert.rgb.xyz(rgb); let x = xyz[0]; let y = xyz[1]; let z = xyz[2]; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); const l = (116 * y) - 16; const a = 500 * (x - y); const b = 200 * (y - z); return [l, a, b]; }; convert.hsl.rgb = function (hsl) { const h = hsl[0] / 360; const s = hsl[1] / 100; const l = hsl[2] / 100; let t2; let t3; let val; if (s === 0) { val = l * 255; return [val, val, val]; } if (l < 0.5) { t2 = l * (1 + s); } else { t2 = l + s - l * s; } const t1 = 2 * l - t2; const rgb = [0, 0, 0]; for (let i = 0; i < 3; i++) { t3 = h + 1 / 3 * -(i - 1); if (t3 < 0) { t3++; } if (t3 > 1) { t3--; } if (6 * t3 < 1) { val = t1 + (t2 - t1) * 6 * t3; } else if (2 * t3 < 1) { val = t2; } else if (3 * t3 < 2) { val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; } else { val = t1; } rgb[i] = val * 255; } return rgb; }; convert.hsl.hsv = function (hsl) { const h = hsl[0]; let s = hsl[1] / 100; let l = hsl[2] / 100; let smin = s; const lmin = Math.max(l, 0.01); l *= 2; s *= (l <= 1) ? l : 2 - l; smin *= lmin <= 1 ? lmin : 2 - lmin; const v = (l + s) / 2; const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); return [h, sv * 100, v * 100]; }; convert.hsv.rgb = function (hsv) { const h = hsv[0] / 60; const s = hsv[1] / 100; let v = hsv[2] / 100; const hi = Math.floor(h) % 6; const f = h - Math.floor(h); const p = 255 * v * (1 - s); const q = 255 * v * (1 - (s * f)); const t = 255 * v * (1 - (s * (1 - f))); v *= 255; switch (hi) { case 0: return [v, t, p]; case 1: return [q, v, p]; case 2: return [p, v, t]; case 3: return [p, q, v]; case 4: return [t, p, v]; case 5: return [v, p, q]; } }; convert.hsv.hsl = function (hsv) { const h = hsv[0]; const s = hsv[1] / 100; const v = hsv[2] / 100; const vmin = Math.max(v, 0.01); let sl; let l; l = (2 - s) * v; const lmin = (2 - s) * vmin; sl = s * vmin; sl /= (lmin <= 1) ? lmin : 2 - lmin; sl = sl || 0; l /= 2; return [h, sl * 100, l * 100]; }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb convert.hwb.rgb = function (hwb) { const h = hwb[0] / 360; let wh = hwb[1] / 100; let bl = hwb[2] / 100; const ratio = wh + bl; let f; // Wh + bl cant be > 1 if (ratio > 1) { wh /= ratio; bl /= ratio; } const i = Math.floor(6 * h); const v = 1 - bl; f = 6 * h - i; if ((i & 0x01) !== 0) { f = 1 - f; } const n = wh + f * (v - wh); // Linear interpolation let r; let g; let b; /* eslint-disable max-statements-per-line,no-multi-spaces */ switch (i) { default: case 6: case 0: r = v; g = n; b = wh; break; case 1: r = n; g = v; b = wh; break; case 2: r = wh; g = v; b = n; break; case 3: r = wh; g = n; b = v; break; case 4: r = n; g = wh; b = v; break; case 5: r = v; g = wh; b = n; break; } /* eslint-enable max-statements-per-line,no-multi-spaces */ return [r * 255, g * 255, b * 255]; }; convert.cmyk.rgb = function (cmyk) { const c = cmyk[0] / 100; const m = cmyk[1] / 100; const y = cmyk[2] / 100; const k = cmyk[3] / 100; const r = 1 - Math.min(1, c * (1 - k) + k); const g = 1 - Math.min(1, m * (1 - k) + k); const b = 1 - Math.min(1, y * (1 - k) + k); return [r * 255, g * 255, b * 255]; }; convert.xyz.rgb = function (xyz) { const x = xyz[0] / 100; const y = xyz[1] / 100; const z = xyz[2] / 100; let r; let g; let b; r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); // Assume sRGB r = r > 0.0031308 ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) : r * 12.92; g = g > 0.0031308 ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) : g * 12.92; b = b > 0.0031308 ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) : b * 12.92; r = Math.min(Math.max(0, r), 1); g = Math.min(Math.max(0, g), 1); b = Math.min(Math.max(0, b), 1); return [r * 255, g * 255, b * 255]; }; convert.xyz.lab = function (xyz) { let x = xyz[0]; let y = xyz[1]; let z = xyz[2]; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); const l = (116 * y) - 16; const a = 500 * (x - y); const b = 200 * (y - z); return [l, a, b]; }; convert.lab.xyz = function (lab) { const l = lab[0]; const a = lab[1]; const b = lab[2]; let x; let y; let z; y = (l + 16) / 116; x = a / 500 + y; z = y - b / 200; const y2 = y ** 3; const x2 = x ** 3; const z2 = z ** 3; y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; x *= 95.047; y *= 100; z *= 108.883; return [x, y, z]; }; convert.lab.lch = function (lab) { const l = lab[0]; const a = lab[1]; const b = lab[2]; let h; const hr = Math.atan2(b, a); h = hr * 360 / 2 / Math.PI; if (h < 0) { h += 360; } const c = Math.sqrt(a * a + b * b); return [l, c, h]; }; convert.lch.lab = function (lch) { const l = lch[0]; const c = lch[1]; const h = lch[2]; const hr = h / 360 * 2 * Math.PI; const a = c * Math.cos(hr); const b = c * Math.sin(hr); return [l, a, b]; }; convert.rgb.ansi16 = function (args, saturation = null) { const [r, g, b] = args; let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization value = Math.round(value / 50); if (value === 0) { return 30; } let ansi = 30 + ((Math.round(b / 255) << 2) | (Math.round(g / 255) << 1) | Math.round(r / 255)); if (value === 2) { ansi += 60; } return ansi; }; convert.hsv.ansi16 = function (args) { // Optimization here; we already know the value and don't need to get // it converted for us. return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); }; convert.rgb.ansi256 = function (args) { const r = args[0]; const g = args[1]; const b = args[2]; // We use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (r === g && g === b) { if (r < 8) { return 16; } if (r > 248) { return 231; } return Math.round(((r - 8) / 247) * 24) + 232; } const ansi = 16 + (36 * Math.round(r / 255 * 5)) + (6 * Math.round(g / 255 * 5)) + Math.round(b / 255 * 5); return ansi; }; convert.ansi16.rgb = function (args) { let color = args % 10; // Handle greyscale if (color === 0 || color === 7) { if (args > 50) { color += 3.5; } color = color / 10.5 * 255; return [color, color, color]; } const mult = (~~(args > 50) + 1) * 0.5; const r = ((color & 1) * mult) * 255; const g = (((color >> 1) & 1) * mult) * 255; const b = (((color >> 2) & 1) * mult) * 255; return [r, g, b]; }; convert.ansi256.rgb = function (args) { // Handle greyscale if (args >= 232) { const c = (args - 232) * 10 + 8; return [c, c, c]; } args -= 16; let rem; const r = Math.floor(args / 36) / 5 * 255; const g = Math.floor((rem = args % 36) / 6) / 5 * 255; const b = (rem % 6) / 5 * 255; return [r, g, b]; }; convert.rgb.hex = function (args) { const integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); const string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.hex.rgb = function (args) { const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); if (!match) { return [0, 0, 0]; } let colorString = match[0]; if (match[0].length === 3) { colorString = colorString.split('').map(char => { return char + char; }).join(''); } const integer = parseInt(colorString, 16); const r = (integer >> 16) & 0xFF; const g = (integer >> 8) & 0xFF; const b = integer & 0xFF; return [r, g, b]; }; convert.rgb.hcg = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const max = Math.max(Math.max(r, g), b); const min = Math.min(Math.min(r, g), b); const chroma = (max - min); let grayscale; let hue; if (chroma < 1) { grayscale = min / (1 - chroma); } else { grayscale = 0; } if (chroma <= 0) { hue = 0; } else if (max === r) { hue = ((g - b) / chroma) % 6; } else if (max === g) { hue = 2 + (b - r) / chroma; } else { hue = 4 + (r - g) / chroma; } hue /= 6; hue %= 1; return [hue * 360, chroma * 100, grayscale * 100]; }; convert.hsl.hcg = function (hsl) { const s = hsl[1] / 100; const l = hsl[2] / 100; const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); let f = 0; if (c < 1.0) { f = (l - 0.5 * c) / (1.0 - c); } return [hsl[0], c * 100, f * 100]; }; convert.hsv.hcg = function (hsv) { const s = hsv[1] / 100; const v = hsv[2] / 100; const c = s * v; let f = 0; if (c < 1.0) { f = (v - c) / (1 - c); } return [hsv[0], c * 100, f * 100]; }; convert.hcg.rgb = function (hcg) { const h = hcg[0] / 360; const c = hcg[1] / 100; const g = hcg[2] / 100; if (c === 0.0) { return [g * 255, g * 255, g * 255]; } const pure = [0, 0, 0]; const hi = (h % 1) * 6; const v = hi % 1; const w = 1 - v; let mg = 0; /* eslint-disable max-statements-per-line */ switch (Math.floor(hi)) { case 0: pure[0] = 1; pure[1] = v; pure[2] = 0; break; case 1: pure[0] = w; pure[1] = 1; pure[2] = 0; break; case 2: pure[0] = 0; pure[1] = 1; pure[2] = v; break; case 3: pure[0] = 0; pure[1] = w; pure[2] = 1; break; case 4: pure[0] = v; pure[1] = 0; pure[2] = 1; break; default: pure[0] = 1; pure[1] = 0; pure[2] = w; } /* eslint-enable max-statements-per-line */ mg = (1.0 - c) * g; return [ (c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255 ]; }; convert.hcg.hsv = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const v = c + g * (1.0 - c); let f = 0; if (v > 0.0) { f = c / v; } return [hcg[0], f * 100, v * 100]; }; convert.hcg.hsl = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const l = g * (1.0 - c) + 0.5 * c; let s = 0; if (l > 0.0 && l < 0.5) { s = c / (2 * l); } else if (l >= 0.5 && l < 1.0) { s = c / (2 * (1 - l)); } return [hcg[0], s * 100, l * 100]; }; convert.hcg.hwb = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const v = c + g * (1.0 - c); return [hcg[0], (v - c) * 100, (1 - v) * 100]; }; convert.hwb.hcg = function (hwb) { const w = hwb[1] / 100; const b = hwb[2] / 100; const v = 1 - b; const c = v - w; let g = 0; if (c < 1) { g = (v - c) / (1 - c); } return [hwb[0], c * 100, g * 100]; }; convert.apple.rgb = function (apple) { return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; }; convert.rgb.apple = function (rgb) { return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; }; convert.gray.rgb = function (args) { return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; }; convert.gray.hsl = function (args) { return [0, 0, args[0]]; }; convert.gray.hsv = convert.gray.hsl; convert.gray.hwb = function (gray) { return [0, 100, gray[0]]; }; convert.gray.cmyk = function (gray) { return [0, 0, 0, gray[0]]; }; convert.gray.lab = function (gray) { return [gray[0], 0, 0]; }; convert.gray.hex = function (gray) { const val = Math.round(gray[0] / 100 * 255) & 0xFF; const integer = (val << 16) + (val << 8) + val; const string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.rgb.gray = function (rgb) { const val = (rgb[0] + rgb[1] + rgb[2]) / 3; return [val / 255 * 100]; }; /***/ }), /***/ 12581: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const conversions = __webpack_require__(24110); const route = __webpack_require__(11712); const convert = {}; const models = Object.keys(conversions); function wrapRaw(fn) { const wrappedFn = function (...args) { const arg0 = args[0]; if (arg0 === undefined || arg0 === null) { return arg0; } if (arg0.length > 1) { args = arg0; } return fn(args); }; // Preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } function wrapRounded(fn) { const wrappedFn = function (...args) { const arg0 = args[0]; if (arg0 === undefined || arg0 === null) { return arg0; } if (arg0.length > 1) { args = arg0; } const result = fn(args); // We're assuming the result is an array here. // see notice in conversions.js; don't use box types // in conversion functions. if (typeof result === 'object') { for (let len = result.length, i = 0; i < len; i++) { result[i] = Math.round(result[i]); } } return result; }; // Preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } models.forEach(fromModel => { convert[fromModel] = {}; Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); const routes = route(fromModel); const routeModels = Object.keys(routes); routeModels.forEach(toModel => { const fn = routes[toModel]; convert[fromModel][toModel] = wrapRounded(fn); convert[fromModel][toModel].raw = wrapRaw(fn); }); }); module.exports = convert; /***/ }), /***/ 11712: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const conversions = __webpack_require__(24110); /* This function routes a model to all other models. all functions that are routed have a property `.conversion` attached to the returned synthetic function. This property is an array of strings, each with the steps in between the 'from' and 'to' color models (inclusive). conversions that are not possible simply are not included. */ function buildGraph() { const graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3 const models = Object.keys(conversions); for (let len = models.length, i = 0; i < len; i++) { graph[models[i]] = { // http://jsperf.com/1-vs-infinity // micro-opt, but this is simple. distance: -1, parent: null }; } return graph; } // https://en.wikipedia.org/wiki/Breadth-first_search function deriveBFS(fromModel) { const graph = buildGraph(); const queue = [fromModel]; // Unshift -> queue -> pop graph[fromModel].distance = 0; while (queue.length) { const current = queue.pop(); const adjacents = Object.keys(conversions[current]); for (let len = adjacents.length, i = 0; i < len; i++) { const adjacent = adjacents[i]; const node = graph[adjacent]; if (node.distance === -1) { node.distance = graph[current].distance + 1; node.parent = current; queue.unshift(adjacent); } } } return graph; } function link(from, to) { return function (args) { return to(from(args)); }; } function wrapConversion(toModel, graph) { const path = [graph[toModel].parent, toModel]; let fn = conversions[graph[toModel].parent][toModel]; let cur = graph[toModel].parent; while (graph[cur].parent) { path.unshift(graph[cur].parent); fn = link(conversions[graph[cur].parent][cur], fn); cur = graph[cur].parent; } fn.conversion = path; return fn; } module.exports = function (fromModel) { const graph = deriveBFS(fromModel); const conversion = {}; const models = Object.keys(graph); for (let len = models.length, i = 0; i < len; i++) { const toModel = models[i]; const node = graph[toModel]; if (node.parent === null) { // No possible conversion, or this node is the source model. continue; } conversion[toModel] = wrapConversion(toModel, graph); } return conversion; }; /***/ }), /***/ 24646: /***/ ((module) => { "use strict"; module.exports = { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255, 235, 205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategray": [47, 79, 79], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "grey": [128, 128, 128], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "rebeccapurple": [102, 51, 153], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50] }; /***/ }), /***/ 19789: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const cp = __webpack_require__(32081); const parse = __webpack_require__(71324); const enoent = __webpack_require__(94059); function spawn(command, args, options) { // Parse the arguments const parsed = parse(command, args, options); // Spawn the child process const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); // Hook into child process "exit" event to emit an error if the command // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 enoent.hookChildProcess(spawned, parsed); return spawned; } function spawnSync(command, args, options) { // Parse the arguments const parsed = parse(command, args, options); // Spawn the child process const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); return result; } module.exports = spawn; module.exports.spawn = spawn; module.exports.sync = spawnSync; module.exports._parse = parse; module.exports._enoent = enoent; /***/ }), /***/ 94059: /***/ ((module) => { "use strict"; const isWin = process.platform === 'win32'; function notFoundError(original, syscall) { return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { code: 'ENOENT', errno: 'ENOENT', syscall: `${syscall} ${original.command}`, path: original.command, spawnargs: original.args, }); } function hookChildProcess(cp, parsed) { if (!isWin) { return; } const originalEmit = cp.emit; cp.emit = function (name, arg1) { // If emitting "exit" event and exit code is 1, we need to check if // the command exists and emit an "error" instead // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 if (name === 'exit') { const err = verifyENOENT(arg1, parsed); if (err) { return originalEmit.call(cp, 'error', err); } } return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params }; } function verifyENOENT(status, parsed) { if (isWin && status === 1 && !parsed.file) { return notFoundError(parsed.original, 'spawn'); } return null; } function verifyENOENTSync(status, parsed) { if (isWin && status === 1 && !parsed.file) { return notFoundError(parsed.original, 'spawnSync'); } return null; } module.exports = { hookChildProcess, verifyENOENT, verifyENOENTSync, notFoundError, }; /***/ }), /***/ 71324: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const path = __webpack_require__(71017); const resolveCommand = __webpack_require__(75282); const escape = __webpack_require__(82152); const readShebang = __webpack_require__(72890); const isWin = process.platform === 'win32'; const isExecutableRegExp = /\.(?:com|exe)$/i; const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; function detectShebang(parsed) { parsed.file = resolveCommand(parsed); const shebang = parsed.file && readShebang(parsed.file); if (shebang) { parsed.args.unshift(parsed.file); parsed.command = shebang; return resolveCommand(parsed); } return parsed.file; } function parseNonShell(parsed) { if (!isWin) { return parsed; } // Detect & add support for shebangs const commandFile = detectShebang(parsed); // We don't need a shell if the command filename is an executable const needsShell = !isExecutableRegExp.test(commandFile); // If a shell is required, use cmd.exe and take care of escaping everything correctly // Note that `forceShell` is an hidden option used only in tests if (parsed.options.forceShell || needsShell) { // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, // we need to double escape them const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) // This is necessary otherwise it will always fail with ENOENT in those cases parsed.command = path.normalize(parsed.command); // Escape command & arguments parsed.command = escape.command(parsed.command); parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars)); const shellCommand = [parsed.command].concat(parsed.args).join(' '); parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; parsed.command = process.env.comspec || 'cmd.exe'; parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped } return parsed; } function parse(command, args, options) { // Normalize arguments, similar to nodejs if (args && !Array.isArray(args)) { options = args; args = null; } args = args ? args.slice(0) : []; // Clone array to avoid changing the original options = Object.assign({}, options); // Clone object to avoid changing the original // Build our parsed object const parsed = { command, args, options, file: undefined, original: { command, args, }, }; // Delegate further parsing to shell or non-shell return options.shell ? parsed : parseNonShell(parsed); } module.exports = parse; /***/ }), /***/ 82152: /***/ ((module) => { "use strict"; // See http://www.robvanderwoude.com/escapechars.php const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; function escapeCommand(arg) { // Escape meta chars arg = arg.replace(metaCharsRegExp, '^$1'); return arg; } function escapeArgument(arg, doubleEscapeMetaChars) { // Convert to string arg = `${arg}`; // Algorithm below is based on https://qntm.org/cmd // It's slightly altered to disable JS backtracking to avoid hanging on specially crafted input // Please see https://github.com/moxystudio/node-cross-spawn/pull/160 for more information // Sequence of backslashes followed by a double quote: // double up all the backslashes and escape the double quote arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"'); // Sequence of backslashes followed by the end of the string // (which will become a double quote later): // double up all the backslashes arg = arg.replace(/(?=(\\+?)?)\1$/, '$1$1'); // All other backslashes occur literally // Quote the whole thing: arg = `"${arg}"`; // Escape meta chars arg = arg.replace(metaCharsRegExp, '^$1'); // Double escape meta chars if necessary if (doubleEscapeMetaChars) { arg = arg.replace(metaCharsRegExp, '^$1'); } return arg; } module.exports.command = escapeCommand; module.exports.argument = escapeArgument; /***/ }), /***/ 72890: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const fs = __webpack_require__(57147); const shebangCommand = __webpack_require__(32975); function readShebang(command) { // Read the first 150 bytes from the file const size = 150; const buffer = Buffer.alloc(size); let fd; try { fd = fs.openSync(command, 'r'); fs.readSync(fd, buffer, 0, size, 0); fs.closeSync(fd); } catch (e) { /* Empty */ } // Attempt to extract shebang (null is returned if not a shebang) return shebangCommand(buffer.toString()); } module.exports = readShebang; /***/ }), /***/ 75282: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const path = __webpack_require__(71017); const which = __webpack_require__(87485); const getPathKey = __webpack_require__(76054); function resolveCommandAttempt(parsed, withoutPathExt) { const env = parsed.options.env || process.env; const cwd = process.cwd(); const hasCustomCwd = parsed.options.cwd != null; // Worker threads do not have process.chdir() const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled; // If a custom `cwd` was specified, we need to change the process cwd // because `which` will do stat calls but does not support a custom cwd if (shouldSwitchCwd) { try { process.chdir(parsed.options.cwd); } catch (err) { /* Empty */ } } let resolved; try { resolved = which.sync(parsed.command, { path: env[getPathKey({ env })], pathExt: withoutPathExt ? path.delimiter : undefined, }); } catch (e) { /* Empty */ } finally { if (shouldSwitchCwd) { process.chdir(cwd); } } // If we successfully resolved, ensure that an absolute path is returned // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it if (resolved) { resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); } return resolved; } function resolveCommand(parsed) { return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); } module.exports = resolveCommand; /***/ }), /***/ 91966: /***/ ((module) => { "use strict"; module.exports = (flag, argv = process.argv) => { const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); const position = argv.indexOf(prefix + flag); const terminatorPosition = argv.indexOf('--'); return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); }; /***/ }), /***/ 78933: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // A linked list to keep track of recently-used-ness const Yallist = __webpack_require__(30543) const MAX = Symbol('max') const LENGTH = Symbol('length') const LENGTH_CALCULATOR = Symbol('lengthCalculator') const ALLOW_STALE = Symbol('allowStale') const MAX_AGE = Symbol('maxAge') const DISPOSE = Symbol('dispose') const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') const LRU_LIST = Symbol('lruList') const CACHE = Symbol('cache') const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') const naiveLength = () => 1 // lruList is a yallist where the head is the youngest // item, and the tail is the oldest. the list contains the Hit // objects as the entries. // Each Hit object has a reference to its Yallist.Node. This // never changes. // // cache is a Map (or PseudoMap) that matches the keys to // the Yallist.Node object. class LRUCache { constructor (options) { if (typeof options === 'number') options = { max: options } if (!options) options = {} if (options.max && (typeof options.max !== 'number' || options.max < 0)) throw new TypeError('max must be a non-negative number') // Kind of weird to have a default max of Infinity, but oh well. const max = this[MAX] = options.max || Infinity const lc = options.length || naiveLength this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc this[ALLOW_STALE] = options.stale || false if (options.maxAge && typeof options.maxAge !== 'number') throw new TypeError('maxAge must be a number') this[MAX_AGE] = options.maxAge || 0 this[DISPOSE] = options.dispose this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false this.reset() } // resize the cache when the max changes. set max (mL) { if (typeof mL !== 'number' || mL < 0) throw new TypeError('max must be a non-negative number') this[MAX] = mL || Infinity trim(this) } get max () { return this[MAX] } set allowStale (allowStale) { this[ALLOW_STALE] = !!allowStale } get allowStale () { return this[ALLOW_STALE] } set maxAge (mA) { if (typeof mA !== 'number') throw new TypeError('maxAge must be a non-negative number') this[MAX_AGE] = mA trim(this) } get maxAge () { return this[MAX_AGE] } // resize the cache when the lengthCalculator changes. set lengthCalculator (lC) { if (typeof lC !== 'function') lC = naiveLength if (lC !== this[LENGTH_CALCULATOR]) { this[LENGTH_CALCULATOR] = lC this[LENGTH] = 0 this[LRU_LIST].forEach(hit => { hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) this[LENGTH] += hit.length }) } trim(this) } get lengthCalculator () { return this[LENGTH_CALCULATOR] } get length () { return this[LENGTH] } get itemCount () { return this[LRU_LIST].length } rforEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].tail; walker !== null;) { const prev = walker.prev forEachStep(this, fn, walker, thisp) walker = prev } } forEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].head; walker !== null;) { const next = walker.next forEachStep(this, fn, walker, thisp) walker = next } } keys () { return this[LRU_LIST].toArray().map(k => k.key) } values () { return this[LRU_LIST].toArray().map(k => k.value) } reset () { if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) { this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) } this[CACHE] = new Map() // hash of items by key this[LRU_LIST] = new Yallist() // list of items in order of use recency this[LENGTH] = 0 // length of items in the list } dump () { return this[LRU_LIST].map(hit => isStale(this, hit) ? false : { k: hit.key, v: hit.value, e: hit.now + (hit.maxAge || 0) }).toArray().filter(h => h) } dumpLru () { return this[LRU_LIST] } set (key, value, maxAge) { maxAge = maxAge || this[MAX_AGE] if (maxAge && typeof maxAge !== 'number') throw new TypeError('maxAge must be a number') const now = maxAge ? Date.now() : 0 const len = this[LENGTH_CALCULATOR](value, key) if (this[CACHE].has(key)) { if (len > this[MAX]) { del(this, this[CACHE].get(key)) return false } const node = this[CACHE].get(key) const item = node.value // dispose of the old one before overwriting // split out into 2 ifs for better coverage tracking if (this[DISPOSE]) { if (!this[NO_DISPOSE_ON_SET]) this[DISPOSE](key, item.value) } item.now = now item.maxAge = maxAge item.value = value this[LENGTH] += len - item.length item.length = len this.get(key) trim(this) return true } const hit = new Entry(key, value, len, now, maxAge) // oversized objects fall out of cache automatically. if (hit.length > this[MAX]) { if (this[DISPOSE]) this[DISPOSE](key, value) return false } this[LENGTH] += hit.length this[LRU_LIST].unshift(hit) this[CACHE].set(key, this[LRU_LIST].head) trim(this) return true } has (key) { if (!this[CACHE].has(key)) return false const hit = this[CACHE].get(key).value return !isStale(this, hit) } get (key) { return get(this, key, true) } peek (key) { return get(this, key, false) } pop () { const node = this[LRU_LIST].tail if (!node) return null del(this, node) return node.value } del (key) { del(this, this[CACHE].get(key)) } load (arr) { // reset the cache this.reset() const now = Date.now() // A previous serialized cache has the most recent items first for (let l = arr.length - 1; l >= 0; l--) { const hit = arr[l] const expiresAt = hit.e || 0 if (expiresAt === 0) // the item was created without expiration in a non aged cache this.set(hit.k, hit.v) else { const maxAge = expiresAt - now // dont add already expired items if (maxAge > 0) { this.set(hit.k, hit.v, maxAge) } } } } prune () { this[CACHE].forEach((value, key) => get(this, key, false)) } } const get = (self, key, doUse) => { const node = self[CACHE].get(key) if (node) { const hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) return undefined } else { if (doUse) { if (self[UPDATE_AGE_ON_GET]) node.value.now = Date.now() self[LRU_LIST].unshiftNode(node) } } return hit.value } } const isStale = (self, hit) => { if (!hit || (!hit.maxAge && !self[MAX_AGE])) return false const diff = Date.now() - hit.now return hit.maxAge ? diff > hit.maxAge : self[MAX_AGE] && (diff > self[MAX_AGE]) } const trim = self => { if (self[LENGTH] > self[MAX]) { for (let walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) { // We know that we're about to delete this one, and also // what the next least recently used key will be, so just // go ahead and set it now. const prev = walker.prev del(self, walker) walker = prev } } } const del = (self, node) => { if (node) { const hit = node.value if (self[DISPOSE]) self[DISPOSE](hit.key, hit.value) self[LENGTH] -= hit.length self[CACHE].delete(hit.key) self[LRU_LIST].removeNode(node) } } class Entry { constructor (key, value, length, now, maxAge) { this.key = key this.value = value this.length = length this.now = now this.maxAge = maxAge || 0 } } const forEachStep = (self, fn, node, thisp) => { let hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) hit = undefined } if (hit) fn.call(thisp, hit.value, hit.key, self) } module.exports = LRUCache /***/ }), /***/ 93743: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const pTry = __webpack_require__(89161); const pLimit = concurrency => { if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) { return Promise.reject(new TypeError('Expected `concurrency` to be a number from 1 and up')); } const queue = []; let activeCount = 0; const next = () => { activeCount--; if (queue.length > 0) { queue.shift()(); } }; const run = (fn, resolve, ...args) => { activeCount++; const result = pTry(fn, ...args); resolve(result); result.then(next, next); }; const enqueue = (fn, resolve, ...args) => { if (activeCount < concurrency) { run(fn, resolve, ...args); } else { queue.push(run.bind(null, fn, resolve, ...args)); } }; const generator = (fn, ...args) => new Promise(resolve => enqueue(fn, resolve, ...args)); Object.defineProperties(generator, { activeCount: { get: () => activeCount }, pendingCount: { get: () => queue.length }, clearQueue: { value: () => { queue.length = 0; } } }); return generator; }; module.exports = pLimit; module.exports["default"] = pLimit; /***/ }), /***/ 76054: /***/ ((module) => { "use strict"; const pathKey = (options = {}) => { const environment = options.env || process.env; const platform = options.platform || process.platform; if (platform !== 'win32') { return 'PATH'; } return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; }; module.exports = pathKey; // TODO: Remove this for the next major release module.exports["default"] = pathKey; /***/ }), /***/ 88469: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const ANY = Symbol('SemVer ANY') // hoisted class for cyclic dependency class Comparator { static get ANY () { return ANY } constructor (comp, options) { options = parseOptions(options) if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } comp = comp.trim().split(/\s+/).join(' ') debug('comparator', comp, options) this.options = options this.loose = !!options.loose this.parse(comp) if (this.semver === ANY) { this.value = '' } else { this.value = this.operator + this.semver.version } debug('comp', this) } parse (comp) { const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] const m = comp.match(r) if (!m) { throw new TypeError(`Invalid comparator: ${comp}`) } this.operator = m[1] !== undefined ? m[1] : '' if (this.operator === '=') { this.operator = '' } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY } else { this.semver = new SemVer(m[2], this.options.loose) } } toString () { return this.value } test (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY || version === ANY) { return true } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } return cmp(version, this.operator, this.semver, this.options) } intersects (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (this.operator === '') { if (this.value === '') { return true } return new Range(comp.value, options).test(this.value) } else if (comp.operator === '') { if (comp.value === '') { return true } return new Range(this.value, options).test(comp.semver) } options = parseOptions(options) // Special cases where nothing can possibly be lower if (options.includePrerelease && (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { return false } if (!options.includePrerelease && (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { return false } // Same direction increasing (> or >=) if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { return true } // Same direction decreasing (< or <=) if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { return true } // same SemVer and both sides are inclusive (<= or >=) if ( (this.semver.version === comp.semver.version) && this.operator.includes('=') && comp.operator.includes('=')) { return true } // opposite directions less than if (cmp(this.semver, '<', comp.semver, options) && this.operator.startsWith('>') && comp.operator.startsWith('<')) { return true } // opposite directions greater than if (cmp(this.semver, '>', comp.semver, options) && this.operator.startsWith('<') && comp.operator.startsWith('>')) { return true } return false } } module.exports = Comparator const parseOptions = __webpack_require__(34360) const { safeRe: re, t } = __webpack_require__(33698) const cmp = __webpack_require__(78196) const debug = __webpack_require__(26244) const SemVer = __webpack_require__(64342) const Range = __webpack_require__(17448) /***/ }), /***/ 17448: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // hoisted class for cyclic dependency class Range { constructor (range, options) { options = parseOptions(options) if (range instanceof Range) { if ( range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease ) { return range } else { return new Range(range.raw, options) } } if (range instanceof Comparator) { // just put it in the set and return this.raw = range.value this.set = [[range]] this.format() return this } this.options = options this.loose = !!options.loose this.includePrerelease = !!options.includePrerelease // First reduce all whitespace as much as possible so we do not have to rely // on potentially slow regexes like \s*. This is then stored and used for // future error messages as well. this.raw = range .trim() .split(/\s+/) .join(' ') // First, split on || this.set = this.raw .split('||') // map the range to a 2d array of comparators .map(r => this.parseRange(r.trim())) // throw out any comparator lists that are empty // this generally means that it was not a valid range, which is allowed // in loose mode, but will still throw if the WHOLE range is invalid. .filter(c => c.length) if (!this.set.length) { throw new TypeError(`Invalid SemVer Range: ${this.raw}`) } // if we have any that are not the null set, throw out null sets. if (this.set.length > 1) { // keep the first one, in case they're all null sets const first = this.set[0] this.set = this.set.filter(c => !isNullSet(c[0])) if (this.set.length === 0) { this.set = [first] } else if (this.set.length > 1) { // if we have any that are *, then the range is just * for (const c of this.set) { if (c.length === 1 && isAny(c[0])) { this.set = [c] break } } } } this.format() } format () { this.range = this.set .map((comps) => comps.join(' ').trim()) .join('||') .trim() return this.range } toString () { return this.range } parseRange (range) { // memoize range parsing for performance. // this is a very hot path, and fully deterministic. const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE) const memoKey = memoOpts + ':' + range const cached = cache.get(memoKey) if (cached) { return cached } const loose = this.options.loose // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range) // `~ 1.2.3` => `~1.2.3` range = range.replace(re[t.TILDETRIM], tildeTrimReplace) debug('tilde trim', range) // `^ 1.2.3` => `^1.2.3` range = range.replace(re[t.CARETTRIM], caretTrimReplace) debug('caret trim', range) // At this point, the range is completely trimmed and // ready to be split into comparators. let rangeList = range .split(' ') .map(comp => parseComparator(comp, this.options)) .join(' ') .split(/\s+/) // >=0.0.0 is equivalent to * .map(comp => replaceGTE0(comp, this.options)) if (loose) { // in loose mode, throw out any that are not valid comparators rangeList = rangeList.filter(comp => { debug('loose invalid filter', comp, this.options) return !!comp.match(re[t.COMPARATORLOOSE]) }) } debug('range list', rangeList) // if any comparators are the null set, then replace with JUST null set // if more than one comparator, remove any * comparators // also, don't include the same comparator more than once const rangeMap = new Map() const comparators = rangeList.map(comp => new Comparator(comp, this.options)) for (const comp of comparators) { if (isNullSet(comp)) { return [comp] } rangeMap.set(comp.value, comp) } if (rangeMap.size > 1 && rangeMap.has('')) { rangeMap.delete('') } const result = [...rangeMap.values()] cache.set(memoKey, result) return result } intersects (range, options) { if (!(range instanceof Range)) { throw new TypeError('a Range is required') } return this.set.some((thisComparators) => { return ( isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => { return ( isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { return rangeComparators.every((rangeComparator) => { return thisComparator.intersects(rangeComparator, options) }) }) ) }) ) }) } // if ANY of the sets match ALL of its comparators, then pass test (version) { if (!version) { return false } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } for (let i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true } } return false } } module.exports = Range const LRU = __webpack_require__(78933) const cache = new LRU({ max: 1000 }) const parseOptions = __webpack_require__(34360) const Comparator = __webpack_require__(88469) const debug = __webpack_require__(26244) const SemVer = __webpack_require__(64342) const { safeRe: re, t, comparatorTrimReplace, tildeTrimReplace, caretTrimReplace, } = __webpack_require__(33698) const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __webpack_require__(11154) const isNullSet = c => c.value === '<0.0.0-0' const isAny = c => c.value === '' // take a set of comparators and determine whether there // exists a version which can satisfy it const isSatisfiable = (comparators, options) => { let result = true const remainingComparators = comparators.slice() let testComparator = remainingComparators.pop() while (result && remainingComparators.length) { result = remainingComparators.every((otherComparator) => { return testComparator.intersects(otherComparator, options) }) testComparator = remainingComparators.pop() } return result } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. const parseComparator = (comp, options) => { debug('comp', comp, options) comp = replaceCarets(comp, options) debug('caret', comp) comp = replaceTildes(comp, options) debug('tildes', comp) comp = replaceXRanges(comp, options) debug('xrange', comp) comp = replaceStars(comp, options) debug('stars', comp) return comp } const isX = id => !id || id.toLowerCase() === 'x' || id === '*' // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 // ~0.0.1 --> >=0.0.1 <0.1.0-0 const replaceTildes = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceTilde(c, options)) .join(' ') } const replaceTilde = (comp, options) => { const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] return comp.replace(r, (_, M, m, p, pr) => { debug('tilde', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0 <${+M + 1}.0.0-0` } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0-0 ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` } else if (pr) { debug('replaceTilde pr', pr) ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } else { // ~1.2.3 == >=1.2.3 <1.3.0-0 ret = `>=${M}.${m}.${p } <${M}.${+m + 1}.0-0` } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 // ^1.2.3 --> >=1.2.3 <2.0.0-0 // ^1.2.0 --> >=1.2.0 <2.0.0-0 // ^0.0.1 --> >=0.0.1 <0.0.2-0 // ^0.1.0 --> >=0.1.0 <0.2.0-0 const replaceCarets = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceCaret(c, options)) .join(' ') } const replaceCaret = (comp, options) => { debug('caret', comp, options) const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] const z = options.includePrerelease ? '-0' : '' return comp.replace(r, (_, M, m, p, pr) => { debug('caret', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` } else if (isX(p)) { if (M === '0') { ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` } else { ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p}-${pr } <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p}-${pr } <${+M + 1}.0.0-0` } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p }${z} <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p }${z} <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p } <${+M + 1}.0.0-0` } } debug('caret return', ret) return ret }) } const replaceXRanges = (comp, options) => { debug('replaceXRanges', comp, options) return comp .split(/\s+/) .map((c) => replaceXRange(c, options)) .join(' ') } const replaceXRange = (comp, options) => { comp = comp.trim() const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] return comp.replace(r, (ret, gtlt, M, m, p, pr) => { debug('xRange', comp, ret, gtlt, M, m, p, pr) const xM = isX(M) const xm = xM || isX(m) const xp = xm || isX(p) const anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } // if we're including prereleases in the match, then we need // to fix this to -0, the lowest possible prerelease value pr = options.includePrerelease ? '-0' : '' if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0-0' } else { // nothing is forbidden ret = '*' } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0 } p = 0 if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 gtlt = '>=' if (xm) { M = +M + 1 m = 0 p = 0 } else { m = +m + 1 p = 0 } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<' if (xm) { M = +M + 1 } else { m = +m + 1 } } if (gtlt === '<') { pr = '-0' } ret = `${gtlt + M}.${m}.${p}${pr}` } else if (xm) { ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` } else if (xp) { ret = `>=${M}.${m}.0${pr } <${M}.${+m + 1}.0-0` } debug('xRange return', ret) return ret }) } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. const replaceStars = (comp, options) => { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp .trim() .replace(re[t.STAR], '') } const replaceGTE0 = (comp, options) => { debug('replaceGTE0', comp, options) return comp .trim() .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') } // This function is passed to string.replace(re[t.HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 const hyphenReplace = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) => { if (isX(fM)) { from = '' } else if (isX(fm)) { from = `>=${fM}.0.0${incPr ? '-0' : ''}` } else if (isX(fp)) { from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` } else if (fpr) { from = `>=${from}` } else { from = `>=${from}${incPr ? '-0' : ''}` } if (isX(tM)) { to = '' } else if (isX(tm)) { to = `<${+tM + 1}.0.0-0` } else if (isX(tp)) { to = `<${tM}.${+tm + 1}.0-0` } else if (tpr) { to = `<=${tM}.${tm}.${tp}-${tpr}` } else if (incPr) { to = `<${tM}.${tm}.${+tp + 1}-0` } else { to = `<=${to}` } return `${from} ${to}`.trim() } const testSet = (set, version, options) => { for (let i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (let i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === Comparator.ANY) { continue } if (set[i].semver.prerelease.length > 0) { const allowed = set[i].semver if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } /***/ }), /***/ 64342: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const debug = __webpack_require__(26244) const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(11154) const { safeRe: re, t } = __webpack_require__(33698) const parseOptions = __webpack_require__(34360) const { compareIdentifiers } = __webpack_require__(36492) class SemVer { constructor (version, options) { options = parseOptions(options) if (version instanceof SemVer) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) } if (version.length > MAX_LENGTH) { throw new TypeError( `version is longer than ${MAX_LENGTH} characters` ) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose // this isn't actually relevant for versions, but keep it so that we // don't run into trouble passing this.options around. this.includePrerelease = !!options.includePrerelease const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) if (!m) { throw new TypeError(`Invalid Version: ${version}`) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map((id) => { if (/^[0-9]+$/.test(id)) { const num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } format () { this.version = `${this.major}.${this.minor}.${this.patch}` if (this.prerelease.length) { this.version += `-${this.prerelease.join('.')}` } return this.version } toString () { return this.version } compare (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { if (typeof other === 'string' && other === this.version) { return 0 } other = new SemVer(other, this.options) } if (other.version === this.version) { return 0 } return this.compareMain(other) || this.comparePre(other) } compareMain (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return ( compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) ) } comparePre (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } let i = 0 do { const a = this.prerelease[i] const b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } compareBuild (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } let i = 0 do { const a = this.build[i] const b = other.build[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc (release, identifier, identifierBase) { switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier, identifierBase) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier, identifierBase) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier, identifierBase) this.inc('pre', identifier, identifierBase) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier, identifierBase) } this.inc('pre', identifier, identifierBase) break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if ( this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0 ) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. case 'pre': { const base = Number(identifierBase) ? 1 : 0 if (!identifier && identifierBase === false) { throw new Error('invalid increment argument: identifier is empty') } if (this.prerelease.length === 0) { this.prerelease = [base] } else { let i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything if (identifier === this.prerelease.join('.') && identifierBase === false) { throw new Error('invalid increment argument: identifier already exists') } this.prerelease.push(base) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 let prerelease = [identifier, base] if (identifierBase === false) { prerelease = [identifier] } if (compareIdentifiers(this.prerelease[0], identifier) === 0) { if (isNaN(this.prerelease[1])) { this.prerelease = prerelease } } else { this.prerelease = prerelease } } break } default: throw new Error(`invalid increment argument: ${release}`) } this.raw = this.format() if (this.build.length) { this.raw += `+${this.build.join('.')}` } return this } } module.exports = SemVer /***/ }), /***/ 95681: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(89947) const clean = (version, options) => { const s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } module.exports = clean /***/ }), /***/ 78196: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const eq = __webpack_require__(7508) const neq = __webpack_require__(23056) const gt = __webpack_require__(33789) const gte = __webpack_require__(76536) const lt = __webpack_require__(16791) const lte = __webpack_require__(44042) const cmp = (a, op, b, loose) => { switch (op) { case '===': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a === b case '!==': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError(`Invalid operator: ${op}`) } } module.exports = cmp /***/ }), /***/ 71269: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(64342) const parse = __webpack_require__(89947) const { safeRe: re, t } = __webpack_require__(33698) const coerce = (version, options) => { if (version instanceof SemVer) { return version } if (typeof version === 'number') { version = String(version) } if (typeof version !== 'string') { return null } options = options || {} let match = null if (!options.rtl) { match = version.match(re[t.COERCE]) } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' // // Walk through the string checking with a /g regexp // Manually set the index so as to pick up overlapping matches. // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. let next while ((next = re[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next } re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length } // leave it in a clean state re[t.COERCERTL].lastIndex = -1 } if (match === null) { return null } return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) } module.exports = coerce /***/ }), /***/ 79963: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(64342) const compareBuild = (a, b, loose) => { const versionA = new SemVer(a, loose) const versionB = new SemVer(b, loose) return versionA.compare(versionB) || versionA.compareBuild(versionB) } module.exports = compareBuild /***/ }), /***/ 58742: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(81142) const compareLoose = (a, b) => compare(a, b, true) module.exports = compareLoose /***/ }), /***/ 81142: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(64342) const compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)) module.exports = compare /***/ }), /***/ 10898: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(89947) const diff = (version1, version2) => { const v1 = parse(version1, null, true) const v2 = parse(version2, null, true) const comparison = v1.compare(v2) if (comparison === 0) { return null } const v1Higher = comparison > 0 const highVersion = v1Higher ? v1 : v2 const lowVersion = v1Higher ? v2 : v1 const highHasPre = !!highVersion.prerelease.length const lowHasPre = !!lowVersion.prerelease.length if (lowHasPre && !highHasPre) { // Going from prerelease -> no prerelease requires some special casing // If the low version has only a major, then it will always be a major // Some examples: // 1.0.0-1 -> 1.0.0 // 1.0.0-1 -> 1.1.1 // 1.0.0-1 -> 2.0.0 if (!lowVersion.patch && !lowVersion.minor) { return 'major' } // Otherwise it can be determined by checking the high version if (highVersion.patch) { // anything higher than a patch bump would result in the wrong version return 'patch' } if (highVersion.minor) { // anything higher than a minor bump would result in the wrong version return 'minor' } // bumping major/minor/patch all have same result return 'major' } // add the `pre` prefix if we are going to a prerelease version const prefix = highHasPre ? 'pre' : '' if (v1.major !== v2.major) { return prefix + 'major' } if (v1.minor !== v2.minor) { return prefix + 'minor' } if (v1.patch !== v2.patch) { return prefix + 'patch' } // high and low are preleases return 'prerelease' } module.exports = diff /***/ }), /***/ 7508: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(81142) const eq = (a, b, loose) => compare(a, b, loose) === 0 module.exports = eq /***/ }), /***/ 33789: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(81142) const gt = (a, b, loose) => compare(a, b, loose) > 0 module.exports = gt /***/ }), /***/ 76536: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(81142) const gte = (a, b, loose) => compare(a, b, loose) >= 0 module.exports = gte /***/ }), /***/ 56342: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(64342) const inc = (version, release, options, identifier, identifierBase) => { if (typeof (options) === 'string') { identifierBase = identifier identifier = options options = undefined } try { return new SemVer( version instanceof SemVer ? version.version : version, options ).inc(release, identifier, identifierBase).version } catch (er) { return null } } module.exports = inc /***/ }), /***/ 16791: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(81142) const lt = (a, b, loose) => compare(a, b, loose) < 0 module.exports = lt /***/ }), /***/ 44042: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(81142) const lte = (a, b, loose) => compare(a, b, loose) <= 0 module.exports = lte /***/ }), /***/ 18747: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(64342) const major = (a, loose) => new SemVer(a, loose).major module.exports = major /***/ }), /***/ 4087: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(64342) const minor = (a, loose) => new SemVer(a, loose).minor module.exports = minor /***/ }), /***/ 23056: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(81142) const neq = (a, b, loose) => compare(a, b, loose) !== 0 module.exports = neq /***/ }), /***/ 89947: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(64342) const parse = (version, options, throwErrors = false) => { if (version instanceof SemVer) { return version } try { return new SemVer(version, options) } catch (er) { if (!throwErrors) { return null } throw er } } module.exports = parse /***/ }), /***/ 94431: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(64342) const patch = (a, loose) => new SemVer(a, loose).patch module.exports = patch /***/ }), /***/ 34400: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(89947) const prerelease = (version, options) => { const parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } module.exports = prerelease /***/ }), /***/ 13370: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(81142) const rcompare = (a, b, loose) => compare(b, a, loose) module.exports = rcompare /***/ }), /***/ 99290: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(79963) const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) module.exports = rsort /***/ }), /***/ 21937: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(17448) const satisfies = (version, range, options) => { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } module.exports = satisfies /***/ }), /***/ 19593: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(79963) const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) module.exports = sort /***/ }), /***/ 67148: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(89947) const valid = (version, options) => { const v = parse(version, options) return v ? v.version : null } module.exports = valid /***/ }), /***/ 74451: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // just pre-load all the stuff that index.js lazily exports const internalRe = __webpack_require__(33698) const constants = __webpack_require__(11154) const SemVer = __webpack_require__(64342) const identifiers = __webpack_require__(36492) const parse = __webpack_require__(89947) const valid = __webpack_require__(67148) const clean = __webpack_require__(95681) const inc = __webpack_require__(56342) const diff = __webpack_require__(10898) const major = __webpack_require__(18747) const minor = __webpack_require__(4087) const patch = __webpack_require__(94431) const prerelease = __webpack_require__(34400) const compare = __webpack_require__(81142) const rcompare = __webpack_require__(13370) const compareLoose = __webpack_require__(58742) const compareBuild = __webpack_require__(79963) const sort = __webpack_require__(19593) const rsort = __webpack_require__(99290) const gt = __webpack_require__(33789) const lt = __webpack_require__(16791) const eq = __webpack_require__(7508) const neq = __webpack_require__(23056) const gte = __webpack_require__(76536) const lte = __webpack_require__(44042) const cmp = __webpack_require__(78196) const coerce = __webpack_require__(71269) const Comparator = __webpack_require__(88469) const Range = __webpack_require__(17448) const satisfies = __webpack_require__(21937) const toComparators = __webpack_require__(76833) const maxSatisfying = __webpack_require__(17465) const minSatisfying = __webpack_require__(38162) const minVersion = __webpack_require__(76438) const validRange = __webpack_require__(92557) const outside = __webpack_require__(91219) const gtr = __webpack_require__(26511) const ltr = __webpack_require__(2060) const intersects = __webpack_require__(87317) const simplifyRange = __webpack_require__(37996) const subset = __webpack_require__(20951) module.exports = { parse, valid, clean, inc, diff, major, minor, patch, prerelease, compare, rcompare, compareLoose, compareBuild, sort, rsort, gt, lt, eq, neq, gte, lte, cmp, coerce, Comparator, Range, satisfies, toComparators, maxSatisfying, minSatisfying, minVersion, validRange, outside, gtr, ltr, intersects, simplifyRange, subset, SemVer, re: internalRe.re, src: internalRe.src, tokens: internalRe.t, SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, RELEASE_TYPES: constants.RELEASE_TYPES, compareIdentifiers: identifiers.compareIdentifiers, rcompareIdentifiers: identifiers.rcompareIdentifiers, } /***/ }), /***/ 11154: /***/ ((module) => { // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. const SEMVER_SPEC_VERSION = '2.0.0' const MAX_LENGTH = 256 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. const MAX_SAFE_COMPONENT_LENGTH = 16 // Max safe length for a build identifier. The max length minus 6 characters for // the shortest version with a build 0.0.0+BUILD. const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 const RELEASE_TYPES = [ 'major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease', ] module.exports = { MAX_LENGTH, MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_SAFE_INTEGER, RELEASE_TYPES, SEMVER_SPEC_VERSION, FLAG_INCLUDE_PRERELEASE: 0b001, FLAG_LOOSE: 0b010, } /***/ }), /***/ 26244: /***/ ((module) => { const debug = ( typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ) ? (...args) => console.error('SEMVER', ...args) : () => {} module.exports = debug /***/ }), /***/ 36492: /***/ ((module) => { const numeric = /^[0-9]+$/ const compareIdentifiers = (a, b) => { const anum = numeric.test(a) const bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) module.exports = { compareIdentifiers, rcompareIdentifiers, } /***/ }), /***/ 34360: /***/ ((module) => { // parse out just the options we care about const looseOption = Object.freeze({ loose: true }) const emptyOpts = Object.freeze({ }) const parseOptions = options => { if (!options) { return emptyOpts } if (typeof options !== 'object') { return looseOption } return options } module.exports = parseOptions /***/ }), /***/ 33698: /***/ ((module, exports, __webpack_require__) => { const { MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_LENGTH, } = __webpack_require__(11154) const debug = __webpack_require__(26244) exports = module.exports = {} // The actual regexps go on exports.re const re = exports.re = [] const safeRe = exports.safeRe = [] const src = exports.src = [] const t = exports.t = {} let R = 0 const LETTERDASHNUMBER = '[a-zA-Z0-9-]' // Replace some greedy regex tokens to prevent regex dos issues. These regex are // used internally via the safeRe object since all inputs in this library get // normalized first to trim and collapse all extra whitespace. The original // regexes are exported for userland consumption and lower level usage. A // future breaking change could export the safer regex only with a note that // all input should have extra whitespace removed. const safeRegexReplacements = [ ['\\s', 1], ['\\d', MAX_LENGTH], [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], ] const makeSafeRegex = (value) => { for (const [token, max] of safeRegexReplacements) { value = value .split(`${token}*`).join(`${token}{0,${max}}`) .split(`${token}+`).join(`${token}{1,${max}}`) } return value } const createToken = (name, value, isGlobal) => { const safe = makeSafeRegex(value) const index = R++ debug(name, index, value) t[name] = index src[index] = value re[index] = new RegExp(value, isGlobal ? 'g' : undefined) safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) } // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') createToken('NUMERICIDENTIFIERLOOSE', '\\d+') // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) // ## Main Version // Three dot-separated numeric identifiers. createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`) createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] }|${src[t.NONNUMERICIDENTIFIER]})`) createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] }|${src[t.NONNUMERICIDENTIFIER]})`) // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] }(?:\\.${src[t.BUILDIDENTIFIER]})*))`) // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. createToken('FULLPLAIN', `v?${src[t.MAINVERSION] }${src[t.PRERELEASE]}?${ src[t.BUILD]}?`) createToken('FULL', `^${src[t.FULLPLAIN]}$`) // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] }${src[t.PRERELEASELOOSE]}?${ src[t.BUILD]}?`) createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) createToken('GTLT', '((?:<|>)?=?)') // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) // Coercion. // Extract anything that could conceivably be a part of a valid semver createToken('COERCE', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:$|[^\\d])`) createToken('COERCERTL', src[t.COERCE], true) // Tilde ranges. // Meaning is "reasonably at or greater than" createToken('LONETILDE', '(?:~>?)') createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) exports.tildeTrimReplace = '$1~' createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) // Caret ranges. // Meaning is "at least and backwards compatible with" createToken('LONECARET', '(?:\\^)') createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) exports.caretTrimReplace = '$1^' createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) // A simple gt/lt/eq thing, or just "" to indicate "any version" createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) exports.comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`) createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`) // Star ranges basically just allow anything at all. createToken('STAR', '(<|>)?=?\\s*\\*') // >=0.0.0 is like a star createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') /***/ }), /***/ 26511: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Determine if version is greater than all the versions possible in the range. const outside = __webpack_require__(91219) const gtr = (version, range, options) => outside(version, range, '>', options) module.exports = gtr /***/ }), /***/ 87317: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(17448) const intersects = (r1, r2, options) => { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2, options) } module.exports = intersects /***/ }), /***/ 2060: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const outside = __webpack_require__(91219) // Determine if version is less than all the versions possible in the range const ltr = (version, range, options) => outside(version, range, '<', options) module.exports = ltr /***/ }), /***/ 17465: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(64342) const Range = __webpack_require__(17448) const maxSatisfying = (versions, range, options) => { let max = null let maxSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } module.exports = maxSatisfying /***/ }), /***/ 38162: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(64342) const Range = __webpack_require__(17448) const minSatisfying = (versions, range, options) => { let min = null let minSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } module.exports = minSatisfying /***/ }), /***/ 76438: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(64342) const Range = __webpack_require__(17448) const gt = __webpack_require__(33789) const minVersion = (range, loose) => { range = new Range(range, loose) let minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let setMin = null comparators.forEach((comparator) => { // Clone to avoid manipulating the comparator's semver object. const compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!setMin || gt(compver, setMin)) { setMin = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error(`Unexpected operation: ${comparator.operator}`) } }) if (setMin && (!minver || gt(minver, setMin))) { minver = setMin } } if (minver && range.test(minver)) { return minver } return null } module.exports = minVersion /***/ }), /***/ 91219: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(64342) const Comparator = __webpack_require__(88469) const { ANY } = Comparator const Range = __webpack_require__(17448) const satisfies = __webpack_require__(21937) const gt = __webpack_require__(33789) const lt = __webpack_require__(16791) const lte = __webpack_require__(44042) const gte = __webpack_require__(76536) const outside = (version, range, hilo, options) => { version = new SemVer(version, options) range = new Range(range, options) let gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisfies the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let high = null let low = null comparators.forEach((comparator) => { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } module.exports = outside /***/ }), /***/ 37996: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // given a set of versions and a range, create a "simplified" range // that includes the same versions that the original range does // If the original range is shorter than the simplified one, return that. const satisfies = __webpack_require__(21937) const compare = __webpack_require__(81142) module.exports = (versions, range, options) => { const set = [] let first = null let prev = null const v = versions.sort((a, b) => compare(a, b, options)) for (const version of v) { const included = satisfies(version, range, options) if (included) { prev = version if (!first) { first = version } } else { if (prev) { set.push([first, prev]) } prev = null first = null } } if (first) { set.push([first, null]) } const ranges = [] for (const [min, max] of set) { if (min === max) { ranges.push(min) } else if (!max && min === v[0]) { ranges.push('*') } else if (!max) { ranges.push(`>=${min}`) } else if (min === v[0]) { ranges.push(`<=${max}`) } else { ranges.push(`${min} - ${max}`) } } const simplified = ranges.join(' || ') const original = typeof range.raw === 'string' ? range.raw : String(range) return simplified.length < original.length ? simplified : range } /***/ }), /***/ 20951: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(17448) const Comparator = __webpack_require__(88469) const { ANY } = Comparator const satisfies = __webpack_require__(21937) const compare = __webpack_require__(81142) // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: // - Every simple range `r1, r2, ...` is a null set, OR // - Every simple range `r1, r2, ...` which is not a null set is a subset of // some `R1, R2, ...` // // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: // - If c is only the ANY comparator // - If C is only the ANY comparator, return true // - Else if in prerelease mode, return false // - else replace c with `[>=0.0.0]` // - If C is only the ANY comparator // - if in prerelease mode, return true // - else replace C with `[>=0.0.0]` // - Let EQ be the set of = comparators in c // - If EQ is more than one, return true (null set) // - Let GT be the highest > or >= comparator in c // - Let LT be the lowest < or <= comparator in c // - If GT and LT, and GT.semver > LT.semver, return true (null set) // - If any C is a = range, and GT or LT are set, return false // - If EQ // - If GT, and EQ does not satisfy GT, return true (null set) // - If LT, and EQ does not satisfy LT, return true (null set) // - If EQ satisfies every C, return true // - Else return false // - If GT // - If GT.semver is lower than any > or >= comp in C, return false // - If GT is >=, and GT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the GT.semver tuple, return false // - If LT // - If LT.semver is greater than any < or <= comp in C, return false // - If LT is <=, and LT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the LT.semver tuple, return false // - Else return true const subset = (sub, dom, options = {}) => { if (sub === dom) { return true } sub = new Range(sub, options) dom = new Range(dom, options) let sawNonNull = false OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { const isSub = simpleSubset(simpleSub, simpleDom, options) sawNonNull = sawNonNull || isSub !== null if (isSub) { continue OUTER } } // the null set is a subset of everything, but null simple ranges in // a complex range should be ignored. so if we saw a non-null range, // then we know this isn't a subset, but if EVERY simple range was null, // then it is a subset. if (sawNonNull) { return false } } return true } const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] const minimumVersion = [new Comparator('>=0.0.0')] const simpleSubset = (sub, dom, options) => { if (sub === dom) { return true } if (sub.length === 1 && sub[0].semver === ANY) { if (dom.length === 1 && dom[0].semver === ANY) { return true } else if (options.includePrerelease) { sub = minimumVersionWithPreRelease } else { sub = minimumVersion } } if (dom.length === 1 && dom[0].semver === ANY) { if (options.includePrerelease) { return true } else { dom = minimumVersion } } const eqSet = new Set() let gt, lt for (const c of sub) { if (c.operator === '>' || c.operator === '>=') { gt = higherGT(gt, c, options) } else if (c.operator === '<' || c.operator === '<=') { lt = lowerLT(lt, c, options) } else { eqSet.add(c.semver) } } if (eqSet.size > 1) { return null } let gtltComp if (gt && lt) { gtltComp = compare(gt.semver, lt.semver, options) if (gtltComp > 0) { return null } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { return null } } // will iterate one or zero times for (const eq of eqSet) { if (gt && !satisfies(eq, String(gt), options)) { return null } if (lt && !satisfies(eq, String(lt), options)) { return null } for (const c of dom) { if (!satisfies(eq, String(c), options)) { return false } } return true } let higher, lower let hasDomLT, hasDomGT // if the subset has a prerelease, we need a comparator in the superset // with the same tuple and a prerelease, or it's not a subset let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false // exception: <1.2.3-0 is the same as <1.2.3 if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { needDomLTPre = false } for (const c of dom) { hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' if (gt) { if (needDomGTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { needDomGTPre = false } } if (c.operator === '>' || c.operator === '>=') { higher = higherGT(gt, c, options) if (higher === c && higher !== gt) { return false } } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { return false } } if (lt) { if (needDomLTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { needDomLTPre = false } } if (c.operator === '<' || c.operator === '<=') { lower = lowerLT(lt, c, options) if (lower === c && lower !== lt) { return false } } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { return false } } if (!c.operator && (lt || gt) && gtltComp !== 0) { return false } } // if there was a < or >, and nothing in the dom, then must be false // UNLESS it was limited by another range in the other direction. // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 if (gt && hasDomLT && !lt && gtltComp !== 0) { return false } if (lt && hasDomGT && !gt && gtltComp !== 0) { return false } // we needed a prerelease range in a specific tuple, but didn't get one // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, // because it includes prereleases in the 1.2.3 tuple if (needDomGTPre || needDomLTPre) { return false } return true } // >=1.2.3 is lower than >1.2.3 const higherGT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp > 0 ? a : comp < 0 ? b : b.operator === '>' && a.operator === '>=' ? b : a } // <=1.2.3 is higher than <1.2.3 const lowerLT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp < 0 ? a : comp > 0 ? b : b.operator === '<' && a.operator === '<=' ? b : a } module.exports = subset /***/ }), /***/ 76833: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(17448) // Mostly just for testing and legacy API reasons const toComparators = (range, options) => new Range(range, options).set .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) module.exports = toComparators /***/ }), /***/ 92557: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(17448) const validRange = (range, options) => { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } module.exports = validRange /***/ }), /***/ 32975: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const shebangRegex = __webpack_require__(41355); module.exports = (string = '') => { const match = string.match(shebangRegex); if (!match) { return null; } const [path, argument] = match[0].replace(/#! ?/, '').split(' '); const binary = path.split('/').pop(); if (binary === 'env') { return argument; } return argument ? `${binary} ${argument}` : binary; }; /***/ }), /***/ 41355: /***/ ((module) => { "use strict"; module.exports = /^#!(.*)/; /***/ }), /***/ 58597: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const os = __webpack_require__(22037); const tty = __webpack_require__(76224); const hasFlag = __webpack_require__(91966); const {env} = process; let forceColor; if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false') || hasFlag('color=never')) { forceColor = 0; } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { forceColor = 1; } if ('FORCE_COLOR' in env) { if (env.FORCE_COLOR === 'true') { forceColor = 1; } else if (env.FORCE_COLOR === 'false') { forceColor = 0; } else { forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); } } function translateLevel(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function supportsColor(haveStream, streamIsTTY) { if (forceColor === 0) { return 0; } if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { return 3; } if (hasFlag('color=256')) { return 2; } if (haveStream && !streamIsTTY && forceColor === undefined) { return 0; } const min = forceColor || 0; if (env.TERM === 'dumb') { return min; } if (process.platform === 'win32') { // Windows 10 build 10586 is the first Windows release that supports 256 colors. // Windows 10 build 14931 is the first release that supports 16m/TrueColor. const osRelease = os.release().split('.'); if ( Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586 ) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ('CI' in env) { if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { return 1; } return min; } if ('TEAMCITY_VERSION' in env) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; } if (env.COLORTERM === 'truecolor') { return 3; } if ('TERM_PROGRAM' in env) { const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); switch (env.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': return 2; // No default } } if (/-256(color)?$/i.test(env.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { return 1; } if ('COLORTERM' in env) { return 1; } return min; } function getSupportLevel(stream) { const level = supportsColor(stream, stream && stream.isTTY); return translateLevel(level); } module.exports = { supportsColor: getSupportLevel, stdout: translateLevel(supportsColor(true, tty.isatty(1))), stderr: translateLevel(supportsColor(true, tty.isatty(2))) }; /***/ }), /***/ 87485: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const isWindows = process.platform === 'win32' || process.env.OSTYPE === 'cygwin' || process.env.OSTYPE === 'msys' const path = __webpack_require__(71017) const COLON = isWindows ? ';' : ':' const isexe = __webpack_require__(31959) const getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }) const getPathInfo = (cmd, opt) => { const colon = opt.colon || COLON // If it has a slash, then we don't bother searching the pathenv. // just check the file itself, and that's it. const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] : ( [ // windows always checks the cwd first ...(isWindows ? [process.cwd()] : []), ...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */ '').split(colon), ] ) const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' : '' const pathExt = isWindows ? pathExtExe.split(colon) : [''] if (isWindows) { if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') pathExt.unshift('') } return { pathEnv, pathExt, pathExtExe, } } const which = (cmd, opt, cb) => { if (typeof opt === 'function') { cb = opt opt = {} } if (!opt) opt = {} const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) const found = [] const step = i => new Promise((resolve, reject) => { if (i === pathEnv.length) return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd)) const ppRaw = pathEnv[i] const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw const pCmd = path.join(pathPart, cmd) const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd resolve(subStep(p, i, 0)) }) const subStep = (p, i, ii) => new Promise((resolve, reject) => { if (ii === pathExt.length) return resolve(step(i + 1)) const ext = pathExt[ii] isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { if (!er && is) { if (opt.all) found.push(p + ext) else return resolve(p + ext) } return resolve(subStep(p, i, ii + 1)) }) }) return cb ? step(0).then(res => cb(null, res), cb) : step(0) } const whichSync = (cmd, opt) => { opt = opt || {} const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) const found = [] for (let i = 0; i < pathEnv.length; i ++) { const ppRaw = pathEnv[i] const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw const pCmd = path.join(pathPart, cmd) const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd for (let j = 0; j < pathExt.length; j ++) { const cur = p + pathExt[j] try { const is = isexe.sync(cur, { pathExt: pathExtExe }) if (is) { if (opt.all) found.push(cur) else return cur } } catch (ex) {} } } if (opt.all && found.length) return found if (opt.nothrow) return null throw getNotFoundError(cmd) } module.exports = which which.sync = whichSync /***/ }), /***/ 23783: /***/ ((module) => { "use strict"; module.exports = function (Yallist) { Yallist.prototype[Symbol.iterator] = function* () { for (let walker = this.head; walker; walker = walker.next) { yield walker.value } } } /***/ }), /***/ 30543: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = Yallist Yallist.Node = Node Yallist.create = Yallist function Yallist (list) { var self = this if (!(self instanceof Yallist)) { self = new Yallist() } self.tail = null self.head = null self.length = 0 if (list && typeof list.forEach === 'function') { list.forEach(function (item) { self.push(item) }) } else if (arguments.length > 0) { for (var i = 0, l = arguments.length; i < l; i++) { self.push(arguments[i]) } } return self } Yallist.prototype.removeNode = function (node) { if (node.list !== this) { throw new Error('removing node which does not belong to this list') } var next = node.next var prev = node.prev if (next) { next.prev = prev } if (prev) { prev.next = next } if (node === this.head) { this.head = next } if (node === this.tail) { this.tail = prev } node.list.length-- node.next = null node.prev = null node.list = null return next } Yallist.prototype.unshiftNode = function (node) { if (node === this.head) { return } if (node.list) { node.list.removeNode(node) } var head = this.head node.list = this node.next = head if (head) { head.prev = node } this.head = node if (!this.tail) { this.tail = node } this.length++ } Yallist.prototype.pushNode = function (node) { if (node === this.tail) { return } if (node.list) { node.list.removeNode(node) } var tail = this.tail node.list = this node.prev = tail if (tail) { tail.next = node } this.tail = node if (!this.head) { this.head = node } this.length++ } Yallist.prototype.push = function () { for (var i = 0, l = arguments.length; i < l; i++) { push(this, arguments[i]) } return this.length } Yallist.prototype.unshift = function () { for (var i = 0, l = arguments.length; i < l; i++) { unshift(this, arguments[i]) } return this.length } Yallist.prototype.pop = function () { if (!this.tail) { return undefined } var res = this.tail.value this.tail = this.tail.prev if (this.tail) { this.tail.next = null } else { this.head = null } this.length-- return res } Yallist.prototype.shift = function () { if (!this.head) { return undefined } var res = this.head.value this.head = this.head.next if (this.head) { this.head.prev = null } else { this.tail = null } this.length-- return res } Yallist.prototype.forEach = function (fn, thisp) { thisp = thisp || this for (var walker = this.head, i = 0; walker !== null; i++) { fn.call(thisp, walker.value, i, this) walker = walker.next } } Yallist.prototype.forEachReverse = function (fn, thisp) { thisp = thisp || this for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { fn.call(thisp, walker.value, i, this) walker = walker.prev } } Yallist.prototype.get = function (n) { for (var i = 0, walker = this.head; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.next } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.getReverse = function (n) { for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.prev } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.map = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.head; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.next } return res } Yallist.prototype.mapReverse = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.tail; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.prev } return res } Yallist.prototype.reduce = function (fn, initial) { var acc var walker = this.head if (arguments.length > 1) { acc = initial } else if (this.head) { walker = this.head.next acc = this.head.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = 0; walker !== null; i++) { acc = fn(acc, walker.value, i) walker = walker.next } return acc } Yallist.prototype.reduceReverse = function (fn, initial) { var acc var walker = this.tail if (arguments.length > 1) { acc = initial } else if (this.tail) { walker = this.tail.prev acc = this.tail.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = this.length - 1; walker !== null; i--) { acc = fn(acc, walker.value, i) walker = walker.prev } return acc } Yallist.prototype.toArray = function () { var arr = new Array(this.length) for (var i = 0, walker = this.head; walker !== null; i++) { arr[i] = walker.value walker = walker.next } return arr } Yallist.prototype.toArrayReverse = function () { var arr = new Array(this.length) for (var i = 0, walker = this.tail; walker !== null; i++) { arr[i] = walker.value walker = walker.prev } return arr } Yallist.prototype.slice = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = 0, walker = this.head; walker !== null && i < from; i++) { walker = walker.next } for (; walker !== null && i < to; i++, walker = walker.next) { ret.push(walker.value) } return ret } Yallist.prototype.sliceReverse = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { walker = walker.prev } for (; walker !== null && i > from; i--, walker = walker.prev) { ret.push(walker.value) } return ret } Yallist.prototype.splice = function (start, deleteCount, ...nodes) { if (start > this.length) { start = this.length - 1 } if (start < 0) { start = this.length + start; } for (var i = 0, walker = this.head; walker !== null && i < start; i++) { walker = walker.next } var ret = [] for (var i = 0; walker && i < deleteCount; i++) { ret.push(walker.value) walker = this.removeNode(walker) } if (walker === null) { walker = this.tail } if (walker !== this.head && walker !== this.tail) { walker = walker.prev } for (var i = 0; i < nodes.length; i++) { walker = insert(this, walker, nodes[i]) } return ret; } Yallist.prototype.reverse = function () { var head = this.head var tail = this.tail for (var walker = head; walker !== null; walker = walker.prev) { var p = walker.prev walker.prev = walker.next walker.next = p } this.head = tail this.tail = head return this } function insert (self, node, value) { var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self) if (inserted.next === null) { self.tail = inserted } if (inserted.prev === null) { self.head = inserted } self.length++ return inserted } function push (self, item) { self.tail = new Node(item, self.tail, null, self) if (!self.head) { self.head = self.tail } self.length++ } function unshift (self, item) { self.head = new Node(item, null, self.head, self) if (!self.tail) { self.tail = self.head } self.length++ } function Node (value, prev, next, list) { if (!(this instanceof Node)) { return new Node(value, prev, next, list) } this.list = list this.value = value if (prev) { prev.next = this this.prev = prev } else { this.prev = null } if (next) { next.prev = this this.next = next } else { this.next = null } } try { // add if support for Symbol.iterator is present __webpack_require__(23783)(Yallist) } catch (er) {} /***/ }), /***/ 11473: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AliasFS = void 0; const ProxiedFS_1 = __webpack_require__(93334); class AliasFS extends ProxiedFS_1.ProxiedFS { constructor(target, { baseFs, pathUtils }) { super(pathUtils); this.target = target; this.baseFs = baseFs; } getRealPath() { return this.target; } getBaseFs() { return this.baseFs; } mapFromBase(p) { return p; } mapToBase(p) { return p; } } exports.AliasFS = AliasFS; /***/ }), /***/ 79918: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CwdFS = void 0; const NodeFS_1 = __webpack_require__(78633); const ProxiedFS_1 = __webpack_require__(93334); const path_1 = __webpack_require__(7194); class CwdFS extends ProxiedFS_1.ProxiedFS { constructor(target, { baseFs = new NodeFS_1.NodeFS() } = {}) { super(path_1.ppath); this.target = this.pathUtils.normalize(target); this.baseFs = baseFs; } getRealPath() { return this.pathUtils.resolve(this.baseFs.getRealPath(), this.target); } resolve(p) { if (this.pathUtils.isAbsolute(p)) { return path_1.ppath.normalize(p); } else { return this.baseFs.resolve(path_1.ppath.join(this.target, p)); } } mapFromBase(path) { return path; } mapToBase(path) { if (this.pathUtils.isAbsolute(path)) { return path; } else { return this.pathUtils.join(this.target, path); } } } exports.CwdFS = CwdFS; /***/ }), /***/ 86936: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.normalizeLineEndings = exports.BasePortableFakeFS = exports.FakeFS = void 0; const os_1 = __webpack_require__(22037); const copyPromise_1 = __webpack_require__(9867); const path_1 = __webpack_require__(7194); class FakeFS { constructor(pathUtils) { this.pathUtils = pathUtils; } async *genTraversePromise(init, { stableSort = false } = {}) { const stack = [init]; while (stack.length > 0) { const p = stack.shift(); const entry = await this.lstatPromise(p); if (entry.isDirectory()) { const entries = await this.readdirPromise(p); if (stableSort) { for (const entry of entries.sort()) { stack.push(this.pathUtils.join(p, entry)); } } else { throw new Error(`Not supported`); } } else { yield p; } } } async removePromise(p, { recursive = true, maxRetries = 5 } = {}) { let stat; try { stat = await this.lstatPromise(p); } catch (error) { if (error.code === `ENOENT`) { return; } else { throw error; } } if (stat.isDirectory()) { if (recursive) { const entries = await this.readdirPromise(p); await Promise.all(entries.map(entry => { return this.removePromise(this.pathUtils.resolve(p, entry)); })); } // 5 gives 1s worth of retries at worst let t = 0; do { try { await this.rmdirPromise(p); break; } catch (error) { if (error.code === `EBUSY` || error.code === `ENOTEMPTY`) { if (maxRetries === 0) { break; } else { await new Promise(resolve => setTimeout(resolve, t * 100)); continue; } } else { throw error; } } } while (t++ < maxRetries); } else { await this.unlinkPromise(p); } } removeSync(p, { recursive = true } = {}) { let stat; try { stat = this.lstatSync(p); } catch (error) { if (error.code === `ENOENT`) { return; } else { throw error; } } if (stat.isDirectory()) { if (recursive) for (const entry of this.readdirSync(p)) this.removeSync(this.pathUtils.resolve(p, entry)); this.rmdirSync(p); } else { this.unlinkSync(p); } } async mkdirpPromise(p, { chmod, utimes } = {}) { p = this.resolve(p); if (p === this.pathUtils.dirname(p)) return; const parts = p.split(this.pathUtils.sep); for (let u = 2; u <= parts.length; ++u) { const subPath = parts.slice(0, u).join(this.pathUtils.sep); if (!this.existsSync(subPath)) { try { await this.mkdirPromise(subPath); } catch (error) { if (error.code === `EEXIST`) { continue; } else { throw error; } } if (chmod != null) await this.chmodPromise(subPath, chmod); if (utimes != null) { await this.utimesPromise(subPath, utimes[0], utimes[1]); } else { const parentStat = await this.statPromise(this.pathUtils.dirname(subPath)); await this.utimesPromise(subPath, parentStat.atime, parentStat.mtime); } } } } mkdirpSync(p, { chmod, utimes } = {}) { p = this.resolve(p); if (p === this.pathUtils.dirname(p)) return; const parts = p.split(this.pathUtils.sep); for (let u = 2; u <= parts.length; ++u) { const subPath = parts.slice(0, u).join(this.pathUtils.sep); if (!this.existsSync(subPath)) { try { this.mkdirSync(subPath); } catch (error) { if (error.code === `EEXIST`) { continue; } else { throw error; } } if (chmod != null) this.chmodSync(subPath, chmod); if (utimes != null) { this.utimesSync(subPath, utimes[0], utimes[1]); } else { const parentStat = this.statSync(this.pathUtils.dirname(subPath)); this.utimesSync(subPath, parentStat.atime, parentStat.mtime); } } } } async copyPromise(destination, source, { baseFs = this, overwrite = true, stableSort = false, stableTime = false, linkStrategy = null } = {}) { return await copyPromise_1.copyPromise(this, destination, baseFs, source, { overwrite, stableSort, stableTime, linkStrategy }); } copySync(destination, source, { baseFs = this, overwrite = true } = {}) { const stat = baseFs.lstatSync(source); const exists = this.existsSync(destination); if (stat.isDirectory()) { this.mkdirpSync(destination); const directoryListing = baseFs.readdirSync(source); for (const entry of directoryListing) { this.copySync(this.pathUtils.join(destination, entry), baseFs.pathUtils.join(source, entry), { baseFs, overwrite }); } } else if (stat.isFile()) { if (!exists || overwrite) { if (exists) this.removeSync(destination); const content = baseFs.readFileSync(source); this.writeFileSync(destination, content); } } else if (stat.isSymbolicLink()) { if (!exists || overwrite) { if (exists) this.removeSync(destination); const target = baseFs.readlinkSync(source); this.symlinkSync(path_1.convertPath(this.pathUtils, target), destination); } } else { throw new Error(`Unsupported file type (file: ${source}, mode: 0o${stat.mode.toString(8).padStart(6, `0`)})`); } const mode = stat.mode & 0o777; this.chmodSync(destination, mode); } async changeFilePromise(p, content, opts = {}) { if (Buffer.isBuffer(content)) { return this.changeFileBufferPromise(p, content); } else { return this.changeFileTextPromise(p, content, opts); } } async changeFileBufferPromise(p, content) { let current = Buffer.alloc(0); try { current = await this.readFilePromise(p); } catch (error) { // ignore errors, no big deal } if (Buffer.compare(current, content) === 0) return; await this.writeFilePromise(p, content); } async changeFileTextPromise(p, content, { automaticNewlines } = {}) { let current = ``; try { current = await this.readFilePromise(p, `utf8`); } catch (error) { // ignore errors, no big deal } const normalizedContent = automaticNewlines ? normalizeLineEndings(current, content) : content; if (current === normalizedContent) return; await this.writeFilePromise(p, normalizedContent); } changeFileSync(p, content, opts = {}) { if (Buffer.isBuffer(content)) { return this.changeFileBufferSync(p, content); } else { return this.changeFileTextSync(p, content, opts); } } changeFileBufferSync(p, content) { let current = Buffer.alloc(0); try { current = this.readFileSync(p); } catch (error) { // ignore errors, no big deal } if (Buffer.compare(current, content) === 0) return; this.writeFileSync(p, content); } changeFileTextSync(p, content, { automaticNewlines = false } = {}) { let current = ``; try { current = this.readFileSync(p, `utf8`); } catch (error) { // ignore errors, no big deal } const normalizedContent = automaticNewlines ? normalizeLineEndings(current, content) : content; if (current === normalizedContent) return; this.writeFileSync(p, normalizedContent); } async movePromise(fromP, toP) { try { await this.renamePromise(fromP, toP); } catch (error) { if (error.code === `EXDEV`) { await this.copyPromise(toP, fromP); await this.removePromise(fromP); } else { throw error; } } } moveSync(fromP, toP) { try { this.renameSync(fromP, toP); } catch (error) { if (error.code === `EXDEV`) { this.copySync(toP, fromP); this.removeSync(fromP); } else { throw error; } } } async lockPromise(affectedPath, callback) { const lockPath = `${affectedPath}.flock`; const interval = 1000 / 60; const startTime = Date.now(); let fd = null; // Even when we detect that a lock file exists, we still look inside to see // whether the pid that created it is still alive. It's not foolproof // (there are false positive), but there are no false negative and that's // all that matters in 99% of the cases. const isAlive = async () => { let pid; try { ([pid] = await this.readJsonPromise(lockPath)); } catch (error) { // If we can't read the file repeatedly, we assume the process was // aborted before even writing finishing writing the payload. return Date.now() - startTime < 500; } try { // "As a special case, a signal of 0 can be used to test for the // existence of a process" - so we check whether it's alive. process.kill(pid, 0); return true; } catch (error) { return false; } }; while (fd === null) { try { fd = await this.openPromise(lockPath, `wx`); } catch (error) { if (error.code === `EEXIST`) { if (!await isAlive()) { try { await this.unlinkPromise(lockPath); continue; } catch (error) { // No big deal if we can't remove it. Just fallback to wait for // it to be eventually released by its owner. } } if (Date.now() - startTime < 60 * 1000) { await new Promise(resolve => setTimeout(resolve, interval)); } else { throw new Error(`Couldn't acquire a lock in a reasonable time (via ${lockPath})`); } } else { throw error; } } } await this.writePromise(fd, JSON.stringify([process.pid])); try { return await callback(); } finally { try { // closePromise needs to come before unlinkPromise otherwise another process can attempt // to get the file handle after the unlink but before close resuling in // EPERM: operation not permitted, open await this.closePromise(fd); await this.unlinkPromise(lockPath); } catch (error) { // noop } } } async readJsonPromise(p) { const content = await this.readFilePromise(p, `utf8`); try { return JSON.parse(content); } catch (error) { error.message += ` (in ${p})`; throw error; } } readJsonSync(p) { const content = this.readFileSync(p, `utf8`); try { return JSON.parse(content); } catch (error) { error.message += ` (in ${p})`; throw error; } } async writeJsonPromise(p, data) { return await this.writeFilePromise(p, `${JSON.stringify(data, null, 2)}\n`); } writeJsonSync(p, data) { return this.writeFileSync(p, `${JSON.stringify(data, null, 2)}\n`); } async preserveTimePromise(p, cb) { const stat = await this.lstatPromise(p); const result = await cb(); if (typeof result !== `undefined`) p = result; if (this.lutimesPromise) { await this.lutimesPromise(p, stat.atime, stat.mtime); } else if (!stat.isSymbolicLink()) { await this.utimesPromise(p, stat.atime, stat.mtime); } } async preserveTimeSync(p, cb) { const stat = this.lstatSync(p); const result = cb(); if (typeof result !== `undefined`) p = result; if (this.lutimesSync) { this.lutimesSync(p, stat.atime, stat.mtime); } else if (!stat.isSymbolicLink()) { this.utimesSync(p, stat.atime, stat.mtime); } } } exports.FakeFS = FakeFS; FakeFS.DEFAULT_TIME = 315532800; class BasePortableFakeFS extends FakeFS { constructor() { super(path_1.ppath); } } exports.BasePortableFakeFS = BasePortableFakeFS; function getEndOfLine(content) { const matches = content.match(/\r?\n/g); if (matches === null) return os_1.EOL; const crlf = matches.filter(nl => nl === `\r\n`).length; const lf = matches.length - crlf; return crlf > lf ? `\r\n` : `\n`; } function normalizeLineEndings(originalContent, newContent) { return newContent.replace(/\r?\n/g, getEndOfLine(originalContent)); } exports.normalizeLineEndings = normalizeLineEndings; /***/ }), /***/ 73266: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JailFS = void 0; const NodeFS_1 = __webpack_require__(78633); const ProxiedFS_1 = __webpack_require__(93334); const path_1 = __webpack_require__(7194); const JAIL_ROOT = path_1.PortablePath.root; class JailFS extends ProxiedFS_1.ProxiedFS { constructor(target, { baseFs = new NodeFS_1.NodeFS() } = {}) { super(path_1.ppath); this.target = this.pathUtils.resolve(path_1.PortablePath.root, target); this.baseFs = baseFs; } getRealPath() { return this.pathUtils.resolve(this.baseFs.getRealPath(), this.pathUtils.relative(path_1.PortablePath.root, this.target)); } getTarget() { return this.target; } getBaseFs() { return this.baseFs; } mapToBase(p) { const normalized = this.pathUtils.normalize(p); if (this.pathUtils.isAbsolute(p)) return this.pathUtils.resolve(this.target, this.pathUtils.relative(JAIL_ROOT, p)); if (normalized.match(/^\.\.\/?/)) throw new Error(`Resolving this path (${p}) would escape the jail`); return this.pathUtils.resolve(this.target, p); } mapFromBase(p) { return this.pathUtils.resolve(JAIL_ROOT, this.pathUtils.relative(this.target, p)); } } exports.JailFS = JailFS; /***/ }), /***/ 44242: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LazyFS = void 0; const ProxiedFS_1 = __webpack_require__(93334); class LazyFS extends ProxiedFS_1.ProxiedFS { constructor(factory, pathUtils) { super(pathUtils); this.instance = null; this.factory = factory; } get baseFs() { if (!this.instance) this.instance = this.factory(); return this.instance; } set baseFs(value) { this.instance = value; } mapFromBase(p) { return p; } mapToBase(p) { return p; } } exports.LazyFS = LazyFS; /***/ }), /***/ 74585: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoFS = void 0; const FakeFS_1 = __webpack_require__(86936); const path_1 = __webpack_require__(7194); const makeError = () => Object.assign(new Error(`ENOSYS: unsupported filesystem access`), { code: `ENOSYS` }); class NoFS extends FakeFS_1.FakeFS { constructor() { super(path_1.ppath); } getExtractHint() { throw makeError(); } getRealPath() { throw makeError(); } resolve() { throw makeError(); } async openPromise() { throw makeError(); } openSync() { throw makeError(); } async opendirPromise() { throw makeError(); } opendirSync() { throw makeError(); } async readPromise() { throw makeError(); } readSync() { throw makeError(); } async writePromise() { throw makeError(); } writeSync() { throw makeError(); } async closePromise() { throw makeError(); } closeSync() { throw makeError(); } createWriteStream() { throw makeError(); } createReadStream() { throw makeError(); } async realpathPromise() { throw makeError(); } realpathSync() { throw makeError(); } async readdirPromise() { throw makeError(); } readdirSync() { throw makeError(); } async existsPromise(p) { throw makeError(); } existsSync(p) { throw makeError(); } async accessPromise() { throw makeError(); } accessSync() { throw makeError(); } async statPromise() { throw makeError(); } statSync() { throw makeError(); } async fstatPromise(fd) { throw makeError(); } fstatSync(fd) { throw makeError(); } async lstatPromise(p) { throw makeError(); } lstatSync(p) { throw makeError(); } async chmodPromise() { throw makeError(); } chmodSync() { throw makeError(); } async chownPromise() { throw makeError(); } chownSync() { throw makeError(); } async mkdirPromise() { throw makeError(); } mkdirSync() { throw makeError(); } async rmdirPromise() { throw makeError(); } rmdirSync() { throw makeError(); } async linkPromise() { throw makeError(); } linkSync() { throw makeError(); } async symlinkPromise() { throw makeError(); } symlinkSync() { throw makeError(); } async renamePromise() { throw makeError(); } renameSync() { throw makeError(); } async copyFilePromise() { throw makeError(); } copyFileSync() { throw makeError(); } async appendFilePromise() { throw makeError(); } appendFileSync() { throw makeError(); } async writeFilePromise() { throw makeError(); } writeFileSync() { throw makeError(); } async unlinkPromise() { throw makeError(); } unlinkSync() { throw makeError(); } async utimesPromise() { throw makeError(); } utimesSync() { throw makeError(); } async readFilePromise() { throw makeError(); } readFileSync() { throw makeError(); } async readlinkPromise() { throw makeError(); } readlinkSync() { throw makeError(); } async truncatePromise() { throw makeError(); } truncateSync() { throw makeError(); } watch() { throw makeError(); } watchFile() { throw makeError(); } unwatchFile() { throw makeError(); } } exports.NoFS = NoFS; NoFS.instance = new NoFS(); /***/ }), /***/ 78633: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NodeFS = void 0; const tslib_1 = __webpack_require__(70655); const fs_1 = tslib_1.__importDefault(__webpack_require__(57147)); const FakeFS_1 = __webpack_require__(86936); const errors_1 = __webpack_require__(15004); const path_1 = __webpack_require__(7194); class NodeFS extends FakeFS_1.BasePortableFakeFS { constructor(realFs = fs_1.default) { super(); this.realFs = realFs; // @ts-expect-error if (typeof this.realFs.lutimes !== `undefined`) { this.lutimesPromise = this.lutimesPromiseImpl; this.lutimesSync = this.lutimesSyncImpl; } } getExtractHint() { return false; } getRealPath() { return path_1.PortablePath.root; } resolve(p) { return path_1.ppath.resolve(p); } async openPromise(p, flags, mode) { return await new Promise((resolve, reject) => { this.realFs.open(path_1.npath.fromPortablePath(p), flags, mode, this.makeCallback(resolve, reject)); }); } openSync(p, flags, mode) { return this.realFs.openSync(path_1.npath.fromPortablePath(p), flags, mode); } async opendirPromise(p, opts) { return await new Promise((resolve, reject) => { if (typeof opts !== `undefined`) { this.realFs.opendir(path_1.npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject)); } else { this.realFs.opendir(path_1.npath.fromPortablePath(p), this.makeCallback(resolve, reject)); } }).then(dir => { return Object.defineProperty(dir, `path`, { value: p, configurable: true, writable: true }); }); } opendirSync(p, opts) { const dir = typeof opts !== `undefined` ? this.realFs.opendirSync(path_1.npath.fromPortablePath(p), opts) : this.realFs.opendirSync(path_1.npath.fromPortablePath(p)); return Object.defineProperty(dir, `path`, { value: p, configurable: true, writable: true }); } async readPromise(fd, buffer, offset = 0, length = 0, position = -1) { return await new Promise((resolve, reject) => { this.realFs.read(fd, buffer, offset, length, position, (error, bytesRead) => { if (error) { reject(error); } else { resolve(bytesRead); } }); }); } readSync(fd, buffer, offset, length, position) { return this.realFs.readSync(fd, buffer, offset, length, position); } async writePromise(fd, buffer, offset, length, position) { return await new Promise((resolve, reject) => { if (typeof buffer === `string`) { return this.realFs.write(fd, buffer, offset, this.makeCallback(resolve, reject)); } else { return this.realFs.write(fd, buffer, offset, length, position, this.makeCallback(resolve, reject)); } }); } writeSync(fd, buffer, offset, length, position) { if (typeof buffer === `string`) { return this.realFs.writeSync(fd, buffer, offset); } else { return this.realFs.writeSync(fd, buffer, offset, length, position); } } async closePromise(fd) { await new Promise((resolve, reject) => { this.realFs.close(fd, this.makeCallback(resolve, reject)); }); } closeSync(fd) { this.realFs.closeSync(fd); } createReadStream(p, opts) { const realPath = (p !== null ? path_1.npath.fromPortablePath(p) : p); return this.realFs.createReadStream(realPath, opts); } createWriteStream(p, opts) { const realPath = (p !== null ? path_1.npath.fromPortablePath(p) : p); return this.realFs.createWriteStream(realPath, opts); } async realpathPromise(p) { return await new Promise((resolve, reject) => { this.realFs.realpath(path_1.npath.fromPortablePath(p), {}, this.makeCallback(resolve, reject)); }).then(path => { return path_1.npath.toPortablePath(path); }); } realpathSync(p) { return path_1.npath.toPortablePath(this.realFs.realpathSync(path_1.npath.fromPortablePath(p), {})); } async existsPromise(p) { return await new Promise(resolve => { this.realFs.exists(path_1.npath.fromPortablePath(p), resolve); }); } accessSync(p, mode) { return this.realFs.accessSync(path_1.npath.fromPortablePath(p), mode); } async accessPromise(p, mode) { return await new Promise((resolve, reject) => { this.realFs.access(path_1.npath.fromPortablePath(p), mode, this.makeCallback(resolve, reject)); }); } existsSync(p) { return this.realFs.existsSync(path_1.npath.fromPortablePath(p)); } async statPromise(p, opts) { return await new Promise((resolve, reject) => { if (opts) { this.realFs.stat(path_1.npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject)); } else { this.realFs.stat(path_1.npath.fromPortablePath(p), this.makeCallback(resolve, reject)); } }); } statSync(p, opts) { if (opts) { return this.realFs.statSync(path_1.npath.fromPortablePath(p), opts); } else { return this.realFs.statSync(path_1.npath.fromPortablePath(p)); } } async fstatPromise(fd, opts) { return await new Promise((resolve, reject) => { if (opts) { // @ts-expect-error - The node typings doesn't know about the options this.realFs.fstat(fd, opts, this.makeCallback(resolve, reject)); } else { this.realFs.fstat(fd, this.makeCallback(resolve, reject)); } }); } fstatSync(fd, opts) { if (opts) { // @ts-expect-error - The node typings doesn't know about the options return this.realFs.fstatSync(fd, opts); } else { return this.realFs.fstatSync(fd); } } async lstatPromise(p, opts) { return await new Promise((resolve, reject) => { if (opts) { // @ts-expect-error - TS does not know this takes options this.realFs.lstat(path_1.npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject)); } else { this.realFs.lstat(path_1.npath.fromPortablePath(p), this.makeCallback(resolve, reject)); } }); } lstatSync(p, opts) { if (opts) { // @ts-expect-error - TS does not know this takes options return this.realFs.lstatSync(path_1.npath.fromPortablePath(p), opts); } else { return this.realFs.lstatSync(path_1.npath.fromPortablePath(p)); } } async chmodPromise(p, mask) { return await new Promise((resolve, reject) => { this.realFs.chmod(path_1.npath.fromPortablePath(p), mask, this.makeCallback(resolve, reject)); }); } chmodSync(p, mask) { return this.realFs.chmodSync(path_1.npath.fromPortablePath(p), mask); } async chownPromise(p, uid, gid) { return await new Promise((resolve, reject) => { this.realFs.chown(path_1.npath.fromPortablePath(p), uid, gid, this.makeCallback(resolve, reject)); }); } chownSync(p, uid, gid) { return this.realFs.chownSync(path_1.npath.fromPortablePath(p), uid, gid); } async renamePromise(oldP, newP) { return await new Promise((resolve, reject) => { this.realFs.rename(path_1.npath.fromPortablePath(oldP), path_1.npath.fromPortablePath(newP), this.makeCallback(resolve, reject)); }); } renameSync(oldP, newP) { return this.realFs.renameSync(path_1.npath.fromPortablePath(oldP), path_1.npath.fromPortablePath(newP)); } async copyFilePromise(sourceP, destP, flags = 0) { return await new Promise((resolve, reject) => { this.realFs.copyFile(path_1.npath.fromPortablePath(sourceP), path_1.npath.fromPortablePath(destP), flags, this.makeCallback(resolve, reject)); }); } copyFileSync(sourceP, destP, flags = 0) { return this.realFs.copyFileSync(path_1.npath.fromPortablePath(sourceP), path_1.npath.fromPortablePath(destP), flags); } async appendFilePromise(p, content, opts) { return await new Promise((resolve, reject) => { const fsNativePath = typeof p === `string` ? path_1.npath.fromPortablePath(p) : p; if (opts) { this.realFs.appendFile(fsNativePath, content, opts, this.makeCallback(resolve, reject)); } else { this.realFs.appendFile(fsNativePath, content, this.makeCallback(resolve, reject)); } }); } appendFileSync(p, content, opts) { const fsNativePath = typeof p === `string` ? path_1.npath.fromPortablePath(p) : p; if (opts) { this.realFs.appendFileSync(fsNativePath, content, opts); } else { this.realFs.appendFileSync(fsNativePath, content); } } async writeFilePromise(p, content, opts) { return await new Promise((resolve, reject) => { const fsNativePath = typeof p === `string` ? path_1.npath.fromPortablePath(p) : p; if (opts) { this.realFs.writeFile(fsNativePath, content, opts, this.makeCallback(resolve, reject)); } else { this.realFs.writeFile(fsNativePath, content, this.makeCallback(resolve, reject)); } }); } writeFileSync(p, content, opts) { const fsNativePath = typeof p === `string` ? path_1.npath.fromPortablePath(p) : p; if (opts) { this.realFs.writeFileSync(fsNativePath, content, opts); } else { this.realFs.writeFileSync(fsNativePath, content); } } async unlinkPromise(p) { return await new Promise((resolve, reject) => { this.realFs.unlink(path_1.npath.fromPortablePath(p), this.makeCallback(resolve, reject)); }); } unlinkSync(p) { return this.realFs.unlinkSync(path_1.npath.fromPortablePath(p)); } async utimesPromise(p, atime, mtime) { return await new Promise((resolve, reject) => { this.realFs.utimes(path_1.npath.fromPortablePath(p), atime, mtime, this.makeCallback(resolve, reject)); }); } utimesSync(p, atime, mtime) { this.realFs.utimesSync(path_1.npath.fromPortablePath(p), atime, mtime); } async lutimesPromiseImpl(p, atime, mtime) { // @ts-expect-error: Not yet in DefinitelyTyped const lutimes = this.realFs.lutimes; if (typeof lutimes === `undefined`) throw errors_1.ENOSYS(`unavailable Node binding`, `lutimes '${p}'`); return await new Promise((resolve, reject) => { lutimes.call(this.realFs, path_1.npath.fromPortablePath(p), atime, mtime, this.makeCallback(resolve, reject)); }); } lutimesSyncImpl(p, atime, mtime) { // @ts-expect-error: Not yet in DefinitelyTyped const lutimesSync = this.realFs.lutimesSync; if (typeof lutimesSync === `undefined`) throw errors_1.ENOSYS(`unavailable Node binding`, `lutimes '${p}'`); lutimesSync.call(this.realFs, path_1.npath.fromPortablePath(p), atime, mtime); } async mkdirPromise(p, opts) { return await new Promise((resolve, reject) => { this.realFs.mkdir(path_1.npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject)); }); } mkdirSync(p, opts) { return this.realFs.mkdirSync(path_1.npath.fromPortablePath(p), opts); } async rmdirPromise(p, opts) { return await new Promise((resolve, reject) => { // TODO: always pass opts when min node version is 12.10+ if (opts) { this.realFs.rmdir(path_1.npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject)); } else { this.realFs.rmdir(path_1.npath.fromPortablePath(p), this.makeCallback(resolve, reject)); } }); } rmdirSync(p, opts) { return this.realFs.rmdirSync(path_1.npath.fromPortablePath(p), opts); } async linkPromise(existingP, newP) { return await new Promise((resolve, reject) => { this.realFs.link(path_1.npath.fromPortablePath(existingP), path_1.npath.fromPortablePath(newP), this.makeCallback(resolve, reject)); }); } linkSync(existingP, newP) { return this.realFs.linkSync(path_1.npath.fromPortablePath(existingP), path_1.npath.fromPortablePath(newP)); } async symlinkPromise(target, p, type) { return await new Promise((resolve, reject) => { this.realFs.symlink(path_1.npath.fromPortablePath(target.replace(/\/+$/, ``)), path_1.npath.fromPortablePath(p), type, this.makeCallback(resolve, reject)); }); } symlinkSync(target, p, type) { return this.realFs.symlinkSync(path_1.npath.fromPortablePath(target.replace(/\/+$/, ``)), path_1.npath.fromPortablePath(p), type); } async readFilePromise(p, encoding) { return await new Promise((resolve, reject) => { const fsNativePath = typeof p === `string` ? path_1.npath.fromPortablePath(p) : p; this.realFs.readFile(fsNativePath, encoding, this.makeCallback(resolve, reject)); }); } readFileSync(p, encoding) { const fsNativePath = typeof p === `string` ? path_1.npath.fromPortablePath(p) : p; return this.realFs.readFileSync(fsNativePath, encoding); } async readdirPromise(p, opts) { return await new Promise((resolve, reject) => { if (opts === null || opts === void 0 ? void 0 : opts.withFileTypes) { this.realFs.readdir(path_1.npath.fromPortablePath(p), { withFileTypes: true }, this.makeCallback(resolve, reject)); } else { this.realFs.readdir(path_1.npath.fromPortablePath(p), this.makeCallback(value => resolve(value), reject)); } }); } readdirSync(p, opts) { if (opts === null || opts === void 0 ? void 0 : opts.withFileTypes) { return this.realFs.readdirSync(path_1.npath.fromPortablePath(p), { withFileTypes: true }); } else { return this.realFs.readdirSync(path_1.npath.fromPortablePath(p)); } } async readlinkPromise(p) { return await new Promise((resolve, reject) => { this.realFs.readlink(path_1.npath.fromPortablePath(p), this.makeCallback(resolve, reject)); }).then(path => { return path_1.npath.toPortablePath(path); }); } readlinkSync(p) { return path_1.npath.toPortablePath(this.realFs.readlinkSync(path_1.npath.fromPortablePath(p))); } async truncatePromise(p, len) { return await new Promise((resolve, reject) => { this.realFs.truncate(path_1.npath.fromPortablePath(p), len, this.makeCallback(resolve, reject)); }); } truncateSync(p, len) { return this.realFs.truncateSync(path_1.npath.fromPortablePath(p), len); } watch(p, a, b) { return this.realFs.watch(path_1.npath.fromPortablePath(p), // @ts-expect-error a, b); } watchFile(p, a, b) { return this.realFs.watchFile(path_1.npath.fromPortablePath(p), // @ts-expect-error a, b); } unwatchFile(p, cb) { return this.realFs.unwatchFile(path_1.npath.fromPortablePath(p), cb); } makeCallback(resolve, reject) { return (err, result) => { if (err) { reject(err); } else { resolve(result); } }; } } exports.NodeFS = NodeFS; /***/ }), /***/ 22155: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PosixFS = void 0; const ProxiedFS_1 = __webpack_require__(93334); const path_1 = __webpack_require__(7194); class PosixFS extends ProxiedFS_1.ProxiedFS { constructor(baseFs) { super(path_1.npath); this.baseFs = baseFs; } mapFromBase(path) { return path_1.npath.fromPortablePath(path); } mapToBase(path) { return path_1.npath.toPortablePath(path); } } exports.PosixFS = PosixFS; /***/ }), /***/ 93334: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProxiedFS = void 0; const FakeFS_1 = __webpack_require__(86936); class ProxiedFS extends FakeFS_1.FakeFS { getExtractHint(hints) { return this.baseFs.getExtractHint(hints); } resolve(path) { return this.mapFromBase(this.baseFs.resolve(this.mapToBase(path))); } getRealPath() { return this.mapFromBase(this.baseFs.getRealPath()); } async openPromise(p, flags, mode) { return this.baseFs.openPromise(this.mapToBase(p), flags, mode); } openSync(p, flags, mode) { return this.baseFs.openSync(this.mapToBase(p), flags, mode); } async opendirPromise(p, opts) { return Object.assign(await this.baseFs.opendirPromise(this.mapToBase(p), opts), { path: p }); } opendirSync(p, opts) { return Object.assign(this.baseFs.opendirSync(this.mapToBase(p), opts), { path: p }); } async readPromise(fd, buffer, offset, length, position) { return await this.baseFs.readPromise(fd, buffer, offset, length, position); } readSync(fd, buffer, offset, length, position) { return this.baseFs.readSync(fd, buffer, offset, length, position); } async writePromise(fd, buffer, offset, length, position) { if (typeof buffer === `string`) { return await this.baseFs.writePromise(fd, buffer, offset); } else { return await this.baseFs.writePromise(fd, buffer, offset, length, position); } } writeSync(fd, buffer, offset, length, position) { if (typeof buffer === `string`) { return this.baseFs.writeSync(fd, buffer, offset); } else { return this.baseFs.writeSync(fd, buffer, offset, length, position); } } async closePromise(fd) { return this.baseFs.closePromise(fd); } closeSync(fd) { this.baseFs.closeSync(fd); } createReadStream(p, opts) { return this.baseFs.createReadStream(p !== null ? this.mapToBase(p) : p, opts); } createWriteStream(p, opts) { return this.baseFs.createWriteStream(p !== null ? this.mapToBase(p) : p, opts); } async realpathPromise(p) { return this.mapFromBase(await this.baseFs.realpathPromise(this.mapToBase(p))); } realpathSync(p) { return this.mapFromBase(this.baseFs.realpathSync(this.mapToBase(p))); } async existsPromise(p) { return this.baseFs.existsPromise(this.mapToBase(p)); } existsSync(p) { return this.baseFs.existsSync(this.mapToBase(p)); } accessSync(p, mode) { return this.baseFs.accessSync(this.mapToBase(p), mode); } async accessPromise(p, mode) { return this.baseFs.accessPromise(this.mapToBase(p), mode); } async statPromise(p, opts) { return this.baseFs.statPromise(this.mapToBase(p), opts); } statSync(p, opts) { return this.baseFs.statSync(this.mapToBase(p), opts); } async fstatPromise(fd, opts) { return this.baseFs.fstatPromise(fd, opts); } fstatSync(fd, opts) { return this.baseFs.fstatSync(fd, opts); } async lstatPromise(p, opts) { return this.baseFs.lstatPromise(this.mapToBase(p), opts); } lstatSync(p, opts) { return this.baseFs.lstatSync(this.mapToBase(p), opts); } async chmodPromise(p, mask) { return this.baseFs.chmodPromise(this.mapToBase(p), mask); } chmodSync(p, mask) { return this.baseFs.chmodSync(this.mapToBase(p), mask); } async chownPromise(p, uid, gid) { return this.baseFs.chownPromise(this.mapToBase(p), uid, gid); } chownSync(p, uid, gid) { return this.baseFs.chownSync(this.mapToBase(p), uid, gid); } async renamePromise(oldP, newP) { return this.baseFs.renamePromise(this.mapToBase(oldP), this.mapToBase(newP)); } renameSync(oldP, newP) { return this.baseFs.renameSync(this.mapToBase(oldP), this.mapToBase(newP)); } async copyFilePromise(sourceP, destP, flags = 0) { return this.baseFs.copyFilePromise(this.mapToBase(sourceP), this.mapToBase(destP), flags); } copyFileSync(sourceP, destP, flags = 0) { return this.baseFs.copyFileSync(this.mapToBase(sourceP), this.mapToBase(destP), flags); } async appendFilePromise(p, content, opts) { return this.baseFs.appendFilePromise(this.fsMapToBase(p), content, opts); } appendFileSync(p, content, opts) { return this.baseFs.appendFileSync(this.fsMapToBase(p), content, opts); } async writeFilePromise(p, content, opts) { return this.baseFs.writeFilePromise(this.fsMapToBase(p), content, opts); } writeFileSync(p, content, opts) { return this.baseFs.writeFileSync(this.fsMapToBase(p), content, opts); } async unlinkPromise(p) { return this.baseFs.unlinkPromise(this.mapToBase(p)); } unlinkSync(p) { return this.baseFs.unlinkSync(this.mapToBase(p)); } async utimesPromise(p, atime, mtime) { return this.baseFs.utimesPromise(this.mapToBase(p), atime, mtime); } utimesSync(p, atime, mtime) { return this.baseFs.utimesSync(this.mapToBase(p), atime, mtime); } async mkdirPromise(p, opts) { return this.baseFs.mkdirPromise(this.mapToBase(p), opts); } mkdirSync(p, opts) { return this.baseFs.mkdirSync(this.mapToBase(p), opts); } async rmdirPromise(p, opts) { return this.baseFs.rmdirPromise(this.mapToBase(p), opts); } rmdirSync(p, opts) { return this.baseFs.rmdirSync(this.mapToBase(p), opts); } async linkPromise(existingP, newP) { return this.baseFs.linkPromise(this.mapToBase(existingP), this.mapToBase(newP)); } linkSync(existingP, newP) { return this.baseFs.linkSync(this.mapToBase(existingP), this.mapToBase(newP)); } async symlinkPromise(target, p, type) { const mappedP = this.mapToBase(p); if (this.pathUtils.isAbsolute(target)) return this.baseFs.symlinkPromise(this.mapToBase(target), mappedP, type); const mappedAbsoluteTarget = this.mapToBase(this.pathUtils.join(this.pathUtils.dirname(p), target)); const mappedTarget = this.baseFs.pathUtils.relative(this.baseFs.pathUtils.dirname(mappedP), mappedAbsoluteTarget); return this.baseFs.symlinkPromise(mappedTarget, mappedP, type); } symlinkSync(target, p, type) { const mappedP = this.mapToBase(p); if (this.pathUtils.isAbsolute(target)) return this.baseFs.symlinkSync(this.mapToBase(target), mappedP, type); const mappedAbsoluteTarget = this.mapToBase(this.pathUtils.join(this.pathUtils.dirname(p), target)); const mappedTarget = this.baseFs.pathUtils.relative(this.baseFs.pathUtils.dirname(mappedP), mappedAbsoluteTarget); return this.baseFs.symlinkSync(mappedTarget, mappedP, type); } async readFilePromise(p, encoding) { // This weird condition is required to tell TypeScript that the signatures are proper (otherwise it thinks that only the generic one is covered) if (encoding === `utf8`) { return this.baseFs.readFilePromise(this.fsMapToBase(p), encoding); } else { return this.baseFs.readFilePromise(this.fsMapToBase(p), encoding); } } readFileSync(p, encoding) { // This weird condition is required to tell TypeScript that the signatures are proper (otherwise it thinks that only the generic one is covered) if (encoding === `utf8`) { return this.baseFs.readFileSync(this.fsMapToBase(p), encoding); } else { return this.baseFs.readFileSync(this.fsMapToBase(p), encoding); } } async readdirPromise(p, opts) { return this.baseFs.readdirPromise(this.mapToBase(p), opts); } readdirSync(p, opts) { return this.baseFs.readdirSync(this.mapToBase(p), opts); } async readlinkPromise(p) { return this.mapFromBase(await this.baseFs.readlinkPromise(this.mapToBase(p))); } readlinkSync(p) { return this.mapFromBase(this.baseFs.readlinkSync(this.mapToBase(p))); } async truncatePromise(p, len) { return this.baseFs.truncatePromise(this.mapToBase(p), len); } truncateSync(p, len) { return this.baseFs.truncateSync(this.mapToBase(p), len); } watch(p, a, b) { return this.baseFs.watch(this.mapToBase(p), // @ts-expect-error a, b); } watchFile(p, a, b) { return this.baseFs.watchFile(this.mapToBase(p), // @ts-expect-error a, b); } unwatchFile(p, cb) { return this.baseFs.unwatchFile(this.mapToBase(p), cb); } fsMapToBase(p) { if (typeof p === `number`) { return p; } else { return this.mapToBase(p); } } } exports.ProxiedFS = ProxiedFS; /***/ }), /***/ 81894: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.URLFS = void 0; const url_1 = __webpack_require__(57310); const ProxiedFS_1 = __webpack_require__(93334); const path_1 = __webpack_require__(7194); /** * Adds support for file URLs to the wrapped `baseFs`, but *not* inside the typings. * * Only exists for compatibility with Node's behavior. * * Automatically wraps all FS instances passed to `patchFs` & `extendFs`. * * Don't use it! */ class URLFS extends ProxiedFS_1.ProxiedFS { constructor(baseFs) { super(path_1.npath); this.baseFs = baseFs; } mapFromBase(path) { return path; } mapToBase(path) { if (path instanceof url_1.URL) return url_1.fileURLToPath(path); return path; } } exports.URLFS = URLFS; /***/ }), /***/ 65013: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.VirtualFS = void 0; const NodeFS_1 = __webpack_require__(78633); const ProxiedFS_1 = __webpack_require__(93334); const path_1 = __webpack_require__(7194); const NUMBER_REGEXP = /^[0-9]+$/; // $0: full path // $1: virtual folder // $2: virtual segment // $3: hash // $4: depth // $5: subpath const VIRTUAL_REGEXP = /^(\/(?:[^/]+\/)*?(?:\$\$virtual|__virtual__))((?:\/((?:[^/]+-)?[a-f0-9]+)(?:\/([^/]+))?)?((?:\/.*)?))$/; const VALID_COMPONENT = /^([^/]+-)?[a-f0-9]+$/; class VirtualFS extends ProxiedFS_1.ProxiedFS { constructor({ baseFs = new NodeFS_1.NodeFS() } = {}) { super(path_1.ppath); this.baseFs = baseFs; } static makeVirtualPath(base, component, to) { if (path_1.ppath.basename(base) !== `__virtual__`) throw new Error(`Assertion failed: Virtual folders must be named "__virtual__"`); if (!path_1.ppath.basename(component).match(VALID_COMPONENT)) throw new Error(`Assertion failed: Virtual components must be ended by an hexadecimal hash`); // Obtains the relative distance between the virtual path and its actual target const target = path_1.ppath.relative(path_1.ppath.dirname(base), to); const segments = target.split(`/`); // Counts how many levels we need to go back to start applying the rest of the path let depth = 0; while (depth < segments.length && segments[depth] === `..`) depth += 1; const finalSegments = segments.slice(depth); const fullVirtualPath = path_1.ppath.join(base, component, String(depth), ...finalSegments); return fullVirtualPath; } static resolveVirtual(p) { const match = p.match(VIRTUAL_REGEXP); if (!match || (!match[3] && match[5])) return p; const target = path_1.ppath.dirname(match[1]); if (!match[3] || !match[4]) return target; const isnum = NUMBER_REGEXP.test(match[4]); if (!isnum) return p; const depth = Number(match[4]); const backstep = `../`.repeat(depth); const subpath = (match[5] || `.`); return VirtualFS.resolveVirtual(path_1.ppath.join(target, backstep, subpath)); } getExtractHint(hints) { return this.baseFs.getExtractHint(hints); } getRealPath() { return this.baseFs.getRealPath(); } realpathSync(p) { const match = p.match(VIRTUAL_REGEXP); if (!match) return this.baseFs.realpathSync(p); if (!match[5]) return p; const realpath = this.baseFs.realpathSync(this.mapToBase(p)); return VirtualFS.makeVirtualPath(match[1], match[3], realpath); } async realpathPromise(p) { const match = p.match(VIRTUAL_REGEXP); if (!match) return await this.baseFs.realpathPromise(p); if (!match[5]) return p; const realpath = await this.baseFs.realpathPromise(this.mapToBase(p)); return VirtualFS.makeVirtualPath(match[1], match[3], realpath); } mapToBase(p) { if (this.pathUtils.isAbsolute(p)) return VirtualFS.resolveVirtual(p); const resolvedRoot = VirtualFS.resolveVirtual(this.baseFs.resolve(path_1.PortablePath.dot)); const resolvedP = VirtualFS.resolveVirtual(this.baseFs.resolve(p)); return path_1.ppath.relative(resolvedRoot, resolvedP); } mapFromBase(p) { return p; } } exports.VirtualFS = VirtualFS; /***/ }), /***/ 56970: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ZipFS = exports.DEFAULT_COMPRESSION_LEVEL = void 0; const tslib_1 = __webpack_require__(70655); const fs_1 = __webpack_require__(57147); const stream_1 = __webpack_require__(12781); const util_1 = __webpack_require__(73837); const zlib_1 = tslib_1.__importDefault(__webpack_require__(59796)); const FakeFS_1 = __webpack_require__(86936); const NodeFS_1 = __webpack_require__(78633); const opendir_1 = __webpack_require__(74694); const watchFile_1 = __webpack_require__(38242); const constants_1 = __webpack_require__(92775); const errors = tslib_1.__importStar(__webpack_require__(15004)); const path_1 = __webpack_require__(7194); const statUtils = tslib_1.__importStar(__webpack_require__(62576)); exports.DEFAULT_COMPRESSION_LEVEL = `mixed`; function toUnixTimestamp(time) { if (typeof time === `string` && String(+time) === time) return +time; if (Number.isFinite(time)) { if (time < 0) { return Date.now() / 1000; } else { return time; } } // convert to 123.456 UNIX timestamp if (util_1.isDate(time)) return time.getTime() / 1000; throw new Error(`Invalid time`); } class ZipFS extends FakeFS_1.BasePortableFakeFS { constructor(source, opts) { super(); this.lzSource = null; this.listings = new Map(); this.entries = new Map(); /** * A cache of indices mapped to file sources. * Populated by `setFileSource` calls. * Required for supporting read after write. */ this.fileSources = new Map(); this.fds = new Map(); this.nextFd = 0; this.ready = false; this.readOnly = false; this.libzip = opts.libzip; const pathOptions = opts; this.level = typeof pathOptions.level !== `undefined` ? pathOptions.level : exports.DEFAULT_COMPRESSION_LEVEL; if (source === null) { source = Buffer.from([ 0x50, 0x4B, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]); } if (typeof source === `string`) { const { baseFs = new NodeFS_1.NodeFS() } = pathOptions; this.baseFs = baseFs; this.path = source; } else { this.path = null; this.baseFs = null; } if (opts.stats) { this.stats = opts.stats; } else { if (typeof source === `string`) { try { this.stats = this.baseFs.statSync(source); } catch (error) { if (error.code === `ENOENT` && pathOptions.create) { this.stats = statUtils.makeDefaultStats(); } else { throw error; } } } else { this.stats = statUtils.makeDefaultStats(); } } const errPtr = this.libzip.malloc(4); try { let flags = 0; if (typeof source === `string` && pathOptions.create) flags |= this.libzip.ZIP_CREATE | this.libzip.ZIP_TRUNCATE; if (opts.readOnly) { flags |= this.libzip.ZIP_RDONLY; this.readOnly = true; } if (typeof source === `string`) { this.zip = this.libzip.open(path_1.npath.fromPortablePath(source), flags, errPtr); } else { const lzSource = this.allocateUnattachedSource(source); try { this.zip = this.libzip.openFromSource(lzSource, flags, errPtr); this.lzSource = lzSource; } catch (error) { this.libzip.source.free(lzSource); throw error; } } if (this.zip === 0) { const error = this.libzip.struct.errorS(); this.libzip.error.initWithCode(error, this.libzip.getValue(errPtr, `i32`)); throw this.makeLibzipError(error); } } finally { this.libzip.free(errPtr); } this.listings.set(path_1.PortablePath.root, new Set()); const entryCount = this.libzip.getNumEntries(this.zip, 0); for (let t = 0; t < entryCount; ++t) { const raw = this.libzip.getName(this.zip, t, 0); if (path_1.ppath.isAbsolute(raw)) continue; const p = path_1.ppath.resolve(path_1.PortablePath.root, raw); this.registerEntry(p, t); // If the raw path is a directory, register it // to prevent empty folder being skipped if (raw.endsWith(`/`)) { this.registerListing(p); } } this.symlinkCount = this.libzip.ext.countSymlinks(this.zip); if (this.symlinkCount === -1) throw this.makeLibzipError(this.libzip.getError(this.zip)); this.ready = true; } makeLibzipError(error) { const errorCode = this.libzip.struct.errorCodeZip(error); const strerror = this.libzip.error.strerror(error); const libzipError = new errors.LibzipError(strerror, this.libzip.errors[errorCode]); // This error should never come up because of the file source cache if (errorCode === this.libzip.errors.ZIP_ER_CHANGED) throw new Error(`Assertion failed: Unexpected libzip error: ${libzipError.message}`); return libzipError; } getExtractHint(hints) { for (const fileName of this.entries.keys()) { const ext = this.pathUtils.extname(fileName); if (hints.relevantExtensions.has(ext)) { return true; } } return false; } getAllFiles() { return Array.from(this.entries.keys()); } getRealPath() { if (!this.path) throw new Error(`ZipFS don't have real paths when loaded from a buffer`); return this.path; } getBufferAndClose() { this.prepareClose(); if (!this.lzSource) throw new Error(`ZipFS was not created from a Buffer`); try { // Prevent close from cleaning up the source this.libzip.source.keep(this.lzSource); // Close the zip archive if (this.libzip.close(this.zip) === -1) throw this.makeLibzipError(this.libzip.getError(this.zip)); // Open the source for reading if (this.libzip.source.open(this.lzSource) === -1) throw this.makeLibzipError(this.libzip.source.error(this.lzSource)); // Move to the end of source if (this.libzip.source.seek(this.lzSource, 0, 0, this.libzip.SEEK_END) === -1) throw this.makeLibzipError(this.libzip.source.error(this.lzSource)); // Get the size of source const size = this.libzip.source.tell(this.lzSource); if (size === -1) throw this.makeLibzipError(this.libzip.source.error(this.lzSource)); // Move to the start of source if (this.libzip.source.seek(this.lzSource, 0, 0, this.libzip.SEEK_SET) === -1) throw this.makeLibzipError(this.libzip.source.error(this.lzSource)); const buffer = this.libzip.malloc(size); if (!buffer) throw new Error(`Couldn't allocate enough memory`); try { const rc = this.libzip.source.read(this.lzSource, buffer, size); if (rc === -1) throw this.makeLibzipError(this.libzip.source.error(this.lzSource)); else if (rc < size) throw new Error(`Incomplete read`); else if (rc > size) throw new Error(`Overread`); const memory = this.libzip.HEAPU8.subarray(buffer, buffer + size); return Buffer.from(memory); } finally { this.libzip.free(buffer); } } finally { this.libzip.source.close(this.lzSource); this.libzip.source.free(this.lzSource); this.ready = false; } } prepareClose() { if (!this.ready) throw errors.EBUSY(`archive closed, close`); watchFile_1.unwatchAllFiles(this); } saveAndClose() { if (!this.path || !this.baseFs) throw new Error(`ZipFS cannot be saved and must be discarded when loaded from a buffer`); this.prepareClose(); if (this.readOnly) { this.discardAndClose(); return; } const previousMod = this.baseFs.existsSync(this.path) ? this.baseFs.statSync(this.path).mode & 0o777 : null; const rc = this.libzip.close(this.zip); if (rc === -1) throw this.makeLibzipError(this.libzip.getError(this.zip)); // this.libzip overrides the chmod when writing the archive, which is a weird // behavior I don't totally understand (plus the umask seems bogus in some // weird cases - maybe related to emscripten?) // // See also https://github.com/nih-at/libzip/issues/77 if (previousMod === null) this.baseFs.chmodSync(this.path, this.stats.mode); else if (previousMod !== (this.baseFs.statSync(this.path).mode & 0o777)) this.baseFs.chmodSync(this.path, previousMod); this.ready = false; } discardAndClose() { this.prepareClose(); this.libzip.discard(this.zip); this.ready = false; } resolve(p) { return path_1.ppath.resolve(path_1.PortablePath.root, p); } async openPromise(p, flags, mode) { return this.openSync(p, flags, mode); } openSync(p, flags, mode) { const fd = this.nextFd++; this.fds.set(fd, { cursor: 0, p }); return fd; } hasOpenFileHandles() { return !!this.fds.size; } async opendirPromise(p, opts) { return this.opendirSync(p, opts); } opendirSync(p, opts = {}) { const resolvedP = this.resolveFilename(`opendir '${p}'`, p); if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP)) throw errors.ENOENT(`opendir '${p}'`); const directoryListing = this.listings.get(resolvedP); if (!directoryListing) throw errors.ENOTDIR(`opendir '${p}'`); const entries = [...directoryListing]; const fd = this.openSync(resolvedP, `r`); const onClose = () => { this.closeSync(fd); }; return opendir_1.opendir(this, resolvedP, entries, { onClose }); } async readPromise(fd, buffer, offset, length, position) { return this.readSync(fd, buffer, offset, length, position); } readSync(fd, buffer, offset = 0, length = 0, position = -1) { const entry = this.fds.get(fd); if (typeof entry === `undefined`) throw errors.EBADF(`read`); let realPosition; if (position === -1 || position === null) realPosition = entry.cursor; else realPosition = position; const source = this.readFileSync(entry.p); source.copy(buffer, offset, realPosition, realPosition + length); const bytesRead = Math.max(0, Math.min(source.length - realPosition, length)); if (position === -1 || position === null) entry.cursor += bytesRead; return bytesRead; } async writePromise(fd, buffer, offset, length, position) { if (typeof buffer === `string`) { return this.writeSync(fd, buffer, position); } else { return this.writeSync(fd, buffer, offset, length, position); } } writeSync(fd, buffer, offset, length, position) { const entry = this.fds.get(fd); if (typeof entry === `undefined`) throw errors.EBADF(`read`); throw new Error(`Unimplemented`); } async closePromise(fd) { return this.closeSync(fd); } closeSync(fd) { const entry = this.fds.get(fd); if (typeof entry === `undefined`) throw errors.EBADF(`read`); this.fds.delete(fd); } createReadStream(p, { encoding } = {}) { if (p === null) throw new Error(`Unimplemented`); const fd = this.openSync(p, `r`); const stream = Object.assign(new stream_1.PassThrough({ emitClose: true, autoDestroy: true, destroy: (error, callback) => { clearImmediate(immediate); this.closeSync(fd); callback(error); }, }), { close() { stream.destroy(); }, bytesRead: 0, path: p, }); const immediate = setImmediate(async () => { try { const data = await this.readFilePromise(p, encoding); stream.bytesRead = data.length; stream.end(data); } catch (error) { stream.destroy(error); } }); return stream; } createWriteStream(p, { encoding } = {}) { if (this.readOnly) throw errors.EROFS(`open '${p}'`); if (p === null) throw new Error(`Unimplemented`); const chunks = []; const fd = this.openSync(p, `w`); const stream = Object.assign(new stream_1.PassThrough({ autoDestroy: true, emitClose: true, destroy: (error, callback) => { try { if (error) { callback(error); } else { this.writeFileSync(p, Buffer.concat(chunks), encoding); callback(null); } } catch (err) { callback(err); } finally { this.closeSync(fd); } }, }), { bytesWritten: 0, path: p, close() { stream.destroy(); }, }); stream.on(`data`, chunk => { const chunkBuffer = Buffer.from(chunk); stream.bytesWritten += chunkBuffer.length; chunks.push(chunkBuffer); }); return stream; } async realpathPromise(p) { return this.realpathSync(p); } realpathSync(p) { const resolvedP = this.resolveFilename(`lstat '${p}'`, p); if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP)) throw errors.ENOENT(`lstat '${p}'`); return resolvedP; } async existsPromise(p) { return this.existsSync(p); } existsSync(p) { if (!this.ready) throw errors.EBUSY(`archive closed, existsSync '${p}'`); if (this.symlinkCount === 0) { const resolvedP = path_1.ppath.resolve(path_1.PortablePath.root, p); return this.entries.has(resolvedP) || this.listings.has(resolvedP); } let resolvedP; try { resolvedP = this.resolveFilename(`stat '${p}'`, p); } catch (error) { return false; } return this.entries.has(resolvedP) || this.listings.has(resolvedP); } async accessPromise(p, mode) { return this.accessSync(p, mode); } accessSync(p, mode = fs_1.constants.F_OK) { const resolvedP = this.resolveFilename(`access '${p}'`, p); if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP)) throw errors.ENOENT(`access '${p}'`); if (this.readOnly && (mode & fs_1.constants.W_OK)) { throw errors.EROFS(`access '${p}'`); } } async statPromise(p, opts) { return this.statSync(p, opts); } statSync(p, opts) { const resolvedP = this.resolveFilename(`stat '${p}'`, p); if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP)) throw errors.ENOENT(`stat '${p}'`); if (p[p.length - 1] === `/` && !this.listings.has(resolvedP)) throw errors.ENOTDIR(`stat '${p}'`); return this.statImpl(`stat '${p}'`, resolvedP, opts); } async fstatPromise(fd, opts) { return this.fstatSync(fd, opts); } fstatSync(fd, opts) { const entry = this.fds.get(fd); if (typeof entry === `undefined`) throw errors.EBADF(`fstatSync`); const { p } = entry; const resolvedP = this.resolveFilename(`stat '${p}'`, p); if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP)) throw errors.ENOENT(`stat '${p}'`); if (p[p.length - 1] === `/` && !this.listings.has(resolvedP)) throw errors.ENOTDIR(`stat '${p}'`); return this.statImpl(`fstat '${p}'`, resolvedP, opts); } async lstatPromise(p, opts) { return this.lstatSync(p, opts); } lstatSync(p, opts) { const resolvedP = this.resolveFilename(`lstat '${p}'`, p, false); if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP)) throw errors.ENOENT(`lstat '${p}'`); if (p[p.length - 1] === `/` && !this.listings.has(resolvedP)) throw errors.ENOTDIR(`lstat '${p}'`); return this.statImpl(`lstat '${p}'`, resolvedP, opts); } statImpl(reason, p, opts = {}) { const entry = this.entries.get(p); // File, or explicit directory if (typeof entry !== `undefined`) { const stat = this.libzip.struct.statS(); const rc = this.libzip.statIndex(this.zip, entry, 0, 0, stat); if (rc === -1) throw this.makeLibzipError(this.libzip.getError(this.zip)); const uid = this.stats.uid; const gid = this.stats.gid; const size = (this.libzip.struct.statSize(stat) >>> 0); const blksize = 512; const blocks = Math.ceil(size / blksize); const mtimeMs = (this.libzip.struct.statMtime(stat) >>> 0) * 1000; const atimeMs = mtimeMs; const birthtimeMs = mtimeMs; const ctimeMs = mtimeMs; const atime = new Date(atimeMs); const birthtime = new Date(birthtimeMs); const ctime = new Date(ctimeMs); const mtime = new Date(mtimeMs); const type = this.listings.has(p) ? constants_1.S_IFDIR : this.isSymbolicLink(entry) ? constants_1.S_IFLNK : constants_1.S_IFREG; const defaultMode = type === constants_1.S_IFDIR ? 0o755 : 0o644; const mode = type | (this.getUnixMode(entry, defaultMode) & 0o777); const crc = this.libzip.struct.statCrc(stat); const statInstance = Object.assign(new statUtils.StatEntry(), { uid, gid, size, blksize, blocks, atime, birthtime, ctime, mtime, atimeMs, birthtimeMs, ctimeMs, mtimeMs, mode, crc }); return opts.bigint === true ? statUtils.convertToBigIntStats(statInstance) : statInstance; } // Implicit directory if (this.listings.has(p)) { const uid = this.stats.uid; const gid = this.stats.gid; const size = 0; const blksize = 512; const blocks = 0; const atimeMs = this.stats.mtimeMs; const birthtimeMs = this.stats.mtimeMs; const ctimeMs = this.stats.mtimeMs; const mtimeMs = this.stats.mtimeMs; const atime = new Date(atimeMs); const birthtime = new Date(birthtimeMs); const ctime = new Date(ctimeMs); const mtime = new Date(mtimeMs); const mode = constants_1.S_IFDIR | 0o755; const crc = 0; const statInstance = Object.assign(new statUtils.StatEntry(), { uid, gid, size, blksize, blocks, atime, birthtime, ctime, mtime, atimeMs, birthtimeMs, ctimeMs, mtimeMs, mode, crc }); return opts.bigint === true ? statUtils.convertToBigIntStats(statInstance) : statInstance; } throw new Error(`Unreachable`); } getUnixMode(index, defaultMode) { const rc = this.libzip.file.getExternalAttributes(this.zip, index, 0, 0, this.libzip.uint08S, this.libzip.uint32S); if (rc === -1) throw this.makeLibzipError(this.libzip.getError(this.zip)); const opsys = this.libzip.getValue(this.libzip.uint08S, `i8`) >>> 0; if (opsys !== this.libzip.ZIP_OPSYS_UNIX) return defaultMode; return this.libzip.getValue(this.libzip.uint32S, `i32`) >>> 16; } registerListing(p) { let listing = this.listings.get(p); if (listing) return listing; const parentListing = this.registerListing(path_1.ppath.dirname(p)); listing = new Set(); parentListing.add(path_1.ppath.basename(p)); this.listings.set(p, listing); return listing; } registerEntry(p, index) { const parentListing = this.registerListing(path_1.ppath.dirname(p)); parentListing.add(path_1.ppath.basename(p)); this.entries.set(p, index); } unregisterListing(p) { this.listings.delete(p); const parentListing = this.listings.get(path_1.ppath.dirname(p)); parentListing === null || parentListing === void 0 ? void 0 : parentListing.delete(path_1.ppath.basename(p)); } unregisterEntry(p) { this.unregisterListing(p); const entry = this.entries.get(p); this.entries.delete(p); if (typeof entry === `undefined`) return; this.fileSources.delete(entry); if (this.isSymbolicLink(entry)) { this.symlinkCount--; } } deleteEntry(p, index) { this.unregisterEntry(p); const rc = this.libzip.delete(this.zip, index); if (rc === -1) { throw this.makeLibzipError(this.libzip.getError(this.zip)); } } resolveFilename(reason, p, resolveLastComponent = true) { if (!this.ready) throw errors.EBUSY(`archive closed, ${reason}`); let resolvedP = path_1.ppath.resolve(path_1.PortablePath.root, p); if (resolvedP === `/`) return path_1.PortablePath.root; const fileIndex = this.entries.get(resolvedP); if (resolveLastComponent && fileIndex !== undefined) { if (this.symlinkCount !== 0 && this.isSymbolicLink(fileIndex)) { const target = this.getFileSource(fileIndex).toString(); return this.resolveFilename(reason, path_1.ppath.resolve(path_1.ppath.dirname(resolvedP), target), true); } else { return resolvedP; } } while (true) { const parentP = this.resolveFilename(reason, path_1.ppath.dirname(resolvedP), true); const isDir = this.listings.has(parentP); const doesExist = this.entries.has(parentP); if (!isDir && !doesExist) throw errors.ENOENT(reason); if (!isDir) throw errors.ENOTDIR(reason); resolvedP = path_1.ppath.resolve(parentP, path_1.ppath.basename(resolvedP)); if (!resolveLastComponent || this.symlinkCount === 0) break; const index = this.libzip.name.locate(this.zip, resolvedP.slice(1)); if (index === -1) break; if (this.isSymbolicLink(index)) { const target = this.getFileSource(index).toString(); resolvedP = path_1.ppath.resolve(path_1.ppath.dirname(resolvedP), target); } else { break; } } return resolvedP; } allocateBuffer(content) { if (!Buffer.isBuffer(content)) content = Buffer.from(content); const buffer = this.libzip.malloc(content.byteLength); if (!buffer) throw new Error(`Couldn't allocate enough memory`); // Copy the file into the Emscripten heap const heap = new Uint8Array(this.libzip.HEAPU8.buffer, buffer, content.byteLength); heap.set(content); return { buffer, byteLength: content.byteLength }; } allocateUnattachedSource(content) { const error = this.libzip.struct.errorS(); const { buffer, byteLength } = this.allocateBuffer(content); const source = this.libzip.source.fromUnattachedBuffer(buffer, byteLength, 0, true, error); if (source === 0) { this.libzip.free(error); throw this.makeLibzipError(error); } return source; } allocateSource(content) { const { buffer, byteLength } = this.allocateBuffer(content); const source = this.libzip.source.fromBuffer(this.zip, buffer, byteLength, 0, true); if (source === 0) { this.libzip.free(buffer); throw this.makeLibzipError(this.libzip.getError(this.zip)); } return source; } setFileSource(p, content) { const buffer = Buffer.isBuffer(content) ? content : Buffer.from(content); const target = path_1.ppath.relative(path_1.PortablePath.root, p); const lzSource = this.allocateSource(content); try { const newIndex = this.libzip.file.add(this.zip, target, lzSource, this.libzip.ZIP_FL_OVERWRITE); if (newIndex === -1) throw this.makeLibzipError(this.libzip.getError(this.zip)); if (this.level !== `mixed`) { // Use store for level 0, and deflate for 1..9 let method; if (this.level === 0) method = this.libzip.ZIP_CM_STORE; else method = this.libzip.ZIP_CM_DEFLATE; const rc = this.libzip.file.setCompression(this.zip, newIndex, 0, method, this.level); if (rc === -1) { throw this.makeLibzipError(this.libzip.getError(this.zip)); } } this.fileSources.set(newIndex, buffer); return newIndex; } catch (error) { this.libzip.source.free(lzSource); throw error; } } isSymbolicLink(index) { if (this.symlinkCount === 0) return false; const attrs = this.libzip.file.getExternalAttributes(this.zip, index, 0, 0, this.libzip.uint08S, this.libzip.uint32S); if (attrs === -1) throw this.makeLibzipError(this.libzip.getError(this.zip)); const opsys = this.libzip.getValue(this.libzip.uint08S, `i8`) >>> 0; if (opsys !== this.libzip.ZIP_OPSYS_UNIX) return false; const attributes = this.libzip.getValue(this.libzip.uint32S, `i32`) >>> 16; return (attributes & constants_1.S_IFMT) === constants_1.S_IFLNK; } getFileSource(index, opts = { asyncDecompress: false }) { const cachedFileSource = this.fileSources.get(index); if (typeof cachedFileSource !== `undefined`) return cachedFileSource; const stat = this.libzip.struct.statS(); const rc = this.libzip.statIndex(this.zip, index, 0, 0, stat); if (rc === -1) throw this.makeLibzipError(this.libzip.getError(this.zip)); const size = this.libzip.struct.statCompSize(stat); const compressionMethod = this.libzip.struct.statCompMethod(stat); const buffer = this.libzip.malloc(size); try { const file = this.libzip.fopenIndex(this.zip, index, 0, this.libzip.ZIP_FL_COMPRESSED); if (file === 0) throw this.makeLibzipError(this.libzip.getError(this.zip)); try { const rc = this.libzip.fread(file, buffer, size, 0); if (rc === -1) throw this.makeLibzipError(this.libzip.file.getError(file)); else if (rc < size) throw new Error(`Incomplete read`); else if (rc > size) throw new Error(`Overread`); const memory = this.libzip.HEAPU8.subarray(buffer, buffer + size); const data = Buffer.from(memory); if (compressionMethod === 0) { this.fileSources.set(index, data); return data; } else if (opts.asyncDecompress) { return new Promise((resolve, reject) => { zlib_1.default.inflateRaw(data, (error, result) => { if (error) { reject(error); } else { this.fileSources.set(index, result); resolve(result); } }); }); } else { const decompressedData = zlib_1.default.inflateRawSync(data); this.fileSources.set(index, decompressedData); return decompressedData; } } finally { this.libzip.fclose(file); } } finally { this.libzip.free(buffer); } } async chmodPromise(p, mask) { return this.chmodSync(p, mask); } chmodSync(p, mask) { if (this.readOnly) throw errors.EROFS(`chmod '${p}'`); // We don't allow to make the extracted entries group-writable mask &= 0o755; const resolvedP = this.resolveFilename(`chmod '${p}'`, p, false); const entry = this.entries.get(resolvedP); if (typeof entry === `undefined`) throw new Error(`Assertion failed: The entry should have been registered (${resolvedP})`); const oldMod = this.getUnixMode(entry, constants_1.S_IFREG | 0o000); const newMod = oldMod & (~0o777) | mask; const rc = this.libzip.file.setExternalAttributes(this.zip, entry, 0, 0, this.libzip.ZIP_OPSYS_UNIX, newMod << 16); if (rc === -1) { throw this.makeLibzipError(this.libzip.getError(this.zip)); } } async chownPromise(p, uid, gid) { return this.chownSync(p, uid, gid); } chownSync(p, uid, gid) { throw new Error(`Unimplemented`); } async renamePromise(oldP, newP) { return this.renameSync(oldP, newP); } renameSync(oldP, newP) { throw new Error(`Unimplemented`); } async copyFilePromise(sourceP, destP, flags) { const { indexSource, indexDest, resolvedDestP } = this.prepareCopyFile(sourceP, destP, flags); const source = await this.getFileSource(indexSource, { asyncDecompress: true }); const newIndex = this.setFileSource(resolvedDestP, source); if (newIndex !== indexDest) { this.registerEntry(resolvedDestP, newIndex); } } copyFileSync(sourceP, destP, flags = 0) { const { indexSource, indexDest, resolvedDestP } = this.prepareCopyFile(sourceP, destP, flags); const source = this.getFileSource(indexSource); const newIndex = this.setFileSource(resolvedDestP, source); if (newIndex !== indexDest) { this.registerEntry(resolvedDestP, newIndex); } } prepareCopyFile(sourceP, destP, flags = 0) { if (this.readOnly) throw errors.EROFS(`copyfile '${sourceP} -> '${destP}'`); if ((flags & fs_1.constants.COPYFILE_FICLONE_FORCE) !== 0) throw errors.ENOSYS(`unsupported clone operation`, `copyfile '${sourceP}' -> ${destP}'`); const resolvedSourceP = this.resolveFilename(`copyfile '${sourceP} -> ${destP}'`, sourceP); const indexSource = this.entries.get(resolvedSourceP); if (typeof indexSource === `undefined`) throw errors.EINVAL(`copyfile '${sourceP}' -> '${destP}'`); const resolvedDestP = this.resolveFilename(`copyfile '${sourceP}' -> ${destP}'`, destP); const indexDest = this.entries.get(resolvedDestP); if ((flags & (fs_1.constants.COPYFILE_EXCL | fs_1.constants.COPYFILE_FICLONE_FORCE)) !== 0 && typeof indexDest !== `undefined`) throw errors.EEXIST(`copyfile '${sourceP}' -> '${destP}'`); return { indexSource, resolvedDestP, indexDest, }; } async appendFilePromise(p, content, opts) { if (this.readOnly) throw errors.EROFS(`open '${p}'`); if (typeof opts === `undefined`) opts = { flag: `a` }; else if (typeof opts === `string`) opts = { flag: `a`, encoding: opts }; else if (typeof opts.flag === `undefined`) opts = { flag: `a`, ...opts }; return this.writeFilePromise(p, content, opts); } appendFileSync(p, content, opts = {}) { if (this.readOnly) throw errors.EROFS(`open '${p}'`); if (typeof opts === `undefined`) opts = { flag: `a` }; else if (typeof opts === `string`) opts = { flag: `a`, encoding: opts }; else if (typeof opts.flag === `undefined`) opts = { flag: `a`, ...opts }; return this.writeFileSync(p, content, opts); } async writeFilePromise(p, content, opts) { const { encoding, index, resolvedP } = this.prepareWriteFile(p, opts); if (index !== undefined && typeof opts === `object` && opts.flag && opts.flag.includes(`a`)) content = Buffer.concat([await this.getFileSource(index, { asyncDecompress: true }), Buffer.from(content)]); if (encoding !== null) content = content.toString(encoding); const newIndex = this.setFileSource(resolvedP, content); if (newIndex !== index) { this.registerEntry(resolvedP, newIndex); } } writeFileSync(p, content, opts) { const { encoding, index, resolvedP } = this.prepareWriteFile(p, opts); if (index !== undefined && typeof opts === `object` && opts.flag && opts.flag.includes(`a`)) content = Buffer.concat([this.getFileSource(index), Buffer.from(content)]); if (encoding !== null) content = content.toString(encoding); const newIndex = this.setFileSource(resolvedP, content); if (newIndex !== index) { this.registerEntry(resolvedP, newIndex); } } prepareWriteFile(p, opts) { if (typeof p !== `string`) throw errors.EBADF(`read`); if (this.readOnly) throw errors.EROFS(`open '${p}'`); const resolvedP = this.resolveFilename(`open '${p}'`, p); if (this.listings.has(resolvedP)) throw errors.EISDIR(`open '${p}'`); let encoding = null; if (typeof opts === `string`) encoding = opts; else if (typeof opts === `object` && opts.encoding) encoding = opts.encoding; const index = this.entries.get(resolvedP); return { encoding, resolvedP, index, }; } async unlinkPromise(p) { return this.unlinkSync(p); } unlinkSync(p) { if (this.readOnly) throw errors.EROFS(`unlink '${p}'`); const resolvedP = this.resolveFilename(`unlink '${p}'`, p); if (this.listings.has(resolvedP)) throw errors.EISDIR(`unlink '${p}'`); const index = this.entries.get(resolvedP); if (typeof index === `undefined`) throw errors.EINVAL(`unlink '${p}'`); this.deleteEntry(resolvedP, index); } async utimesPromise(p, atime, mtime) { return this.utimesSync(p, atime, mtime); } utimesSync(p, atime, mtime) { if (this.readOnly) throw errors.EROFS(`utimes '${p}'`); const resolvedP = this.resolveFilename(`utimes '${p}'`, p); this.utimesImpl(resolvedP, mtime); } async lutimesPromise(p, atime, mtime) { return this.lutimesSync(p, atime, mtime); } lutimesSync(p, atime, mtime) { if (this.readOnly) throw errors.EROFS(`lutimes '${p}'`); const resolvedP = this.resolveFilename(`utimes '${p}'`, p, false); this.utimesImpl(resolvedP, mtime); } utimesImpl(resolvedP, mtime) { if (this.listings.has(resolvedP)) if (!this.entries.has(resolvedP)) this.hydrateDirectory(resolvedP); const entry = this.entries.get(resolvedP); if (entry === undefined) throw new Error(`Unreachable`); const rc = this.libzip.file.setMtime(this.zip, entry, 0, toUnixTimestamp(mtime), 0); if (rc === -1) { throw this.makeLibzipError(this.libzip.getError(this.zip)); } } async mkdirPromise(p, opts) { return this.mkdirSync(p, opts); } mkdirSync(p, { mode = 0o755, recursive = false } = {}) { if (recursive) { this.mkdirpSync(p, { chmod: mode }); return; } if (this.readOnly) throw errors.EROFS(`mkdir '${p}'`); const resolvedP = this.resolveFilename(`mkdir '${p}'`, p); if (this.entries.has(resolvedP) || this.listings.has(resolvedP)) throw errors.EEXIST(`mkdir '${p}'`); this.hydrateDirectory(resolvedP); this.chmodSync(resolvedP, mode); } async rmdirPromise(p, opts) { return this.rmdirSync(p, opts); } rmdirSync(p, { recursive = false } = {}) { if (this.readOnly) throw errors.EROFS(`rmdir '${p}'`); if (recursive) { this.removeSync(p); return; } const resolvedP = this.resolveFilename(`rmdir '${p}'`, p); const directoryListing = this.listings.get(resolvedP); if (!directoryListing) throw errors.ENOTDIR(`rmdir '${p}'`); if (directoryListing.size > 0) throw errors.ENOTEMPTY(`rmdir '${p}'`); const index = this.entries.get(resolvedP); if (typeof index === `undefined`) throw errors.EINVAL(`rmdir '${p}'`); this.deleteEntry(p, index); } hydrateDirectory(resolvedP) { const index = this.libzip.dir.add(this.zip, path_1.ppath.relative(path_1.PortablePath.root, resolvedP)); if (index === -1) throw this.makeLibzipError(this.libzip.getError(this.zip)); this.registerListing(resolvedP); this.registerEntry(resolvedP, index); return index; } async linkPromise(existingP, newP) { return this.linkSync(existingP, newP); } linkSync(existingP, newP) { // Zip archives don't support hard links: // https://stackoverflow.com/questions/8859616/are-hard-links-possible-within-a-zip-archive throw errors.EOPNOTSUPP(`link '${existingP}' -> '${newP}'`); } async symlinkPromise(target, p) { return this.symlinkSync(target, p); } symlinkSync(target, p) { if (this.readOnly) throw errors.EROFS(`symlink '${target}' -> '${p}'`); const resolvedP = this.resolveFilename(`symlink '${target}' -> '${p}'`, p); if (this.listings.has(resolvedP)) throw errors.EISDIR(`symlink '${target}' -> '${p}'`); if (this.entries.has(resolvedP)) throw errors.EEXIST(`symlink '${target}' -> '${p}'`); const index = this.setFileSource(resolvedP, target); this.registerEntry(resolvedP, index); const rc = this.libzip.file.setExternalAttributes(this.zip, index, 0, 0, this.libzip.ZIP_OPSYS_UNIX, (constants_1.S_IFLNK | 0o777) << 16); if (rc === -1) throw this.makeLibzipError(this.libzip.getError(this.zip)); this.symlinkCount += 1; } async readFilePromise(p, encoding) { // This is messed up regarding the TS signatures if (typeof encoding === `object`) // @ts-expect-error encoding = encoding ? encoding.encoding : undefined; const data = await this.readFileBuffer(p, { asyncDecompress: true }); return encoding ? data.toString(encoding) : data; } readFileSync(p, encoding) { // This is messed up regarding the TS signatures if (typeof encoding === `object`) // @ts-expect-error encoding = encoding ? encoding.encoding : undefined; const data = this.readFileBuffer(p); return encoding ? data.toString(encoding) : data; } readFileBuffer(p, opts = { asyncDecompress: false }) { const resolvedP = this.resolveFilename(`open '${p}'`, p); if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP)) throw errors.ENOENT(`open '${p}'`); // Ensures that the last component is a directory, if the user said so (even if it is we'll throw right after with EISDIR anyway) if (p[p.length - 1] === `/` && !this.listings.has(resolvedP)) throw errors.ENOTDIR(`open '${p}'`); if (this.listings.has(resolvedP)) throw errors.EISDIR(`read`); const entry = this.entries.get(resolvedP); if (entry === undefined) throw new Error(`Unreachable`); return this.getFileSource(entry, opts); } async readdirPromise(p, opts) { return this.readdirSync(p, opts); } readdirSync(p, opts) { const resolvedP = this.resolveFilename(`scandir '${p}'`, p); if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP)) throw errors.ENOENT(`scandir '${p}'`); const directoryListing = this.listings.get(resolvedP); if (!directoryListing) throw errors.ENOTDIR(`scandir '${p}'`); const entries = [...directoryListing]; if (!(opts === null || opts === void 0 ? void 0 : opts.withFileTypes)) return entries; return entries.map(name => { return Object.assign(this.statImpl(`lstat`, path_1.ppath.join(p, name)), { name, }); }); } async readlinkPromise(p) { const entry = this.prepareReadlink(p); return (await this.getFileSource(entry, { asyncDecompress: true })).toString(); } readlinkSync(p) { const entry = this.prepareReadlink(p); return this.getFileSource(entry).toString(); } prepareReadlink(p) { const resolvedP = this.resolveFilename(`readlink '${p}'`, p, false); if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP)) throw errors.ENOENT(`readlink '${p}'`); // Ensure that the last component is a directory (if it is we'll throw right after with EISDIR anyway) if (p[p.length - 1] === `/` && !this.listings.has(resolvedP)) throw errors.ENOTDIR(`open '${p}'`); if (this.listings.has(resolvedP)) throw errors.EINVAL(`readlink '${p}'`); const entry = this.entries.get(resolvedP); if (entry === undefined) throw new Error(`Unreachable`); if (!this.isSymbolicLink(entry)) throw errors.EINVAL(`readlink '${p}'`); return entry; } async truncatePromise(p, len = 0) { const resolvedP = this.resolveFilename(`open '${p}'`, p); const index = this.entries.get(resolvedP); if (typeof index === `undefined`) throw errors.EINVAL(`open '${p}'`); const source = await this.getFileSource(index, { asyncDecompress: true }); const truncated = Buffer.alloc(len, 0x00); source.copy(truncated); return await this.writeFilePromise(p, truncated); } truncateSync(p, len = 0) { const resolvedP = this.resolveFilename(`open '${p}'`, p); const index = this.entries.get(resolvedP); if (typeof index === `undefined`) throw errors.EINVAL(`open '${p}'`); const source = this.getFileSource(index); const truncated = Buffer.alloc(len, 0x00); source.copy(truncated); return this.writeFileSync(p, truncated); } watch(p, a, b) { let persistent; switch (typeof a) { case `function`: case `string`: case `undefined`: { persistent = true; } break; default: { ({ persistent = true } = a); } break; } if (!persistent) return { on: () => { }, close: () => { } }; const interval = setInterval(() => { }, 24 * 60 * 60 * 1000); return { on: () => { }, close: () => { clearInterval(interval); } }; } watchFile(p, a, b) { const resolvedP = this.resolveFilename(`open '${p}'`, p); return watchFile_1.watchFile(this, resolvedP, a, b); } unwatchFile(p, cb) { const resolvedP = this.resolveFilename(`open '${p}'`, p); return watchFile_1.unwatchFile(this, resolvedP, cb); } } exports.ZipFS = ZipFS; /***/ }), /***/ 32031: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ZipOpenFS = exports.getArchivePart = void 0; const tslib_1 = __webpack_require__(70655); const fs_1 = __webpack_require__(57147); const FakeFS_1 = __webpack_require__(86936); const NodeFS_1 = __webpack_require__(78633); const ZipFS_1 = __webpack_require__(56970); const watchFile_1 = __webpack_require__(38242); const errors = tslib_1.__importStar(__webpack_require__(15004)); const path_1 = __webpack_require__(7194); const ZIP_FD = 0x80000000; const DOT_ZIP = `.zip`; /** * Extracts the archive part (ending in the first `.zip`) from a path. * * The indexOf-based implementation is ~3.7x faster than a RegExp-based implementation. */ const getArchivePart = (path) => { let idx = path.indexOf(DOT_ZIP); if (idx <= 0) return null; let nextCharIdx = idx; while (idx >= 0) { nextCharIdx = idx + DOT_ZIP.length; if (path[nextCharIdx] === path_1.ppath.sep) break; // Disallow files named ".zip" if (path[idx - 1] === path_1.ppath.sep) return null; idx = path.indexOf(DOT_ZIP, nextCharIdx); } // The path either has to end in ".zip" or contain an archive subpath (".zip/...") if (path.length > nextCharIdx && path[nextCharIdx] !== path_1.ppath.sep) return null; return path.slice(0, nextCharIdx); }; exports.getArchivePart = getArchivePart; class ZipOpenFS extends FakeFS_1.BasePortableFakeFS { constructor({ libzip, baseFs = new NodeFS_1.NodeFS(), filter = null, maxOpenFiles = Infinity, readOnlyArchives = false, useCache = true, maxAge = 5000 }) { super(); this.fdMap = new Map(); this.nextFd = 3; this.isZip = new Set(); this.notZip = new Set(); this.realPaths = new Map(); this.limitOpenFilesTimeout = null; this.libzipFactory = typeof libzip !== `function` ? () => libzip : libzip; this.baseFs = baseFs; this.zipInstances = useCache ? new Map() : null; this.filter = filter; this.maxOpenFiles = maxOpenFiles; this.readOnlyArchives = readOnlyArchives; this.maxAge = maxAge; } static async openPromise(fn, opts) { const zipOpenFs = new ZipOpenFS(opts); try { return await fn(zipOpenFs); } finally { zipOpenFs.saveAndClose(); } } get libzip() { if (typeof this.libzipInstance === `undefined`) this.libzipInstance = this.libzipFactory(); return this.libzipInstance; } getExtractHint(hints) { return this.baseFs.getExtractHint(hints); } getRealPath() { return this.baseFs.getRealPath(); } saveAndClose() { watchFile_1.unwatchAllFiles(this); if (this.zipInstances) { for (const [path, { zipFs }] of this.zipInstances.entries()) { zipFs.saveAndClose(); this.zipInstances.delete(path); } } } discardAndClose() { watchFile_1.unwatchAllFiles(this); if (this.zipInstances) { for (const [path, { zipFs }] of this.zipInstances.entries()) { zipFs.discardAndClose(); this.zipInstances.delete(path); } } } resolve(p) { return this.baseFs.resolve(p); } remapFd(zipFs, fd) { const remappedFd = this.nextFd++ | ZIP_FD; this.fdMap.set(remappedFd, [zipFs, fd]); return remappedFd; } async openPromise(p, flags, mode) { return await this.makeCallPromise(p, async () => { return await this.baseFs.openPromise(p, flags, mode); }, async (zipFs, { subPath }) => { return this.remapFd(zipFs, await zipFs.openPromise(subPath, flags, mode)); }); } openSync(p, flags, mode) { return this.makeCallSync(p, () => { return this.baseFs.openSync(p, flags, mode); }, (zipFs, { subPath }) => { return this.remapFd(zipFs, zipFs.openSync(subPath, flags, mode)); }); } async opendirPromise(p, opts) { return await this.makeCallPromise(p, async () => { return await this.baseFs.opendirPromise(p, opts); }, async (zipFs, { subPath }) => { return await zipFs.opendirPromise(subPath, opts); }, { requireSubpath: false, }); } opendirSync(p, opts) { return this.makeCallSync(p, () => { return this.baseFs.opendirSync(p, opts); }, (zipFs, { subPath }) => { return zipFs.opendirSync(subPath, opts); }, { requireSubpath: false, }); } async readPromise(fd, buffer, offset, length, position) { if ((fd & ZIP_FD) === 0) return await this.baseFs.readPromise(fd, buffer, offset, length, position); const entry = this.fdMap.get(fd); if (typeof entry === `undefined`) throw errors.EBADF(`read`); const [zipFs, realFd] = entry; return await zipFs.readPromise(realFd, buffer, offset, length, position); } readSync(fd, buffer, offset, length, position) { if ((fd & ZIP_FD) === 0) return this.baseFs.readSync(fd, buffer, offset, length, position); const entry = this.fdMap.get(fd); if (typeof entry === `undefined`) throw errors.EBADF(`readSync`); const [zipFs, realFd] = entry; return zipFs.readSync(realFd, buffer, offset, length, position); } async writePromise(fd, buffer, offset, length, position) { if ((fd & ZIP_FD) === 0) { if (typeof buffer === `string`) { return await this.baseFs.writePromise(fd, buffer, offset); } else { return await this.baseFs.writePromise(fd, buffer, offset, length, position); } } const entry = this.fdMap.get(fd); if (typeof entry === `undefined`) throw errors.EBADF(`write`); const [zipFs, realFd] = entry; if (typeof buffer === `string`) { return await zipFs.writePromise(realFd, buffer, offset); } else { return await zipFs.writePromise(realFd, buffer, offset, length, position); } } writeSync(fd, buffer, offset, length, position) { if ((fd & ZIP_FD) === 0) { if (typeof buffer === `string`) { return this.baseFs.writeSync(fd, buffer, offset); } else { return this.baseFs.writeSync(fd, buffer, offset, length, position); } } const entry = this.fdMap.get(fd); if (typeof entry === `undefined`) throw errors.EBADF(`writeSync`); const [zipFs, realFd] = entry; if (typeof buffer === `string`) { return zipFs.writeSync(realFd, buffer, offset); } else { return zipFs.writeSync(realFd, buffer, offset, length, position); } } async closePromise(fd) { if ((fd & ZIP_FD) === 0) return await this.baseFs.closePromise(fd); const entry = this.fdMap.get(fd); if (typeof entry === `undefined`) throw errors.EBADF(`close`); this.fdMap.delete(fd); const [zipFs, realFd] = entry; return await zipFs.closePromise(realFd); } closeSync(fd) { if ((fd & ZIP_FD) === 0) return this.baseFs.closeSync(fd); const entry = this.fdMap.get(fd); if (typeof entry === `undefined`) throw errors.EBADF(`closeSync`); this.fdMap.delete(fd); const [zipFs, realFd] = entry; return zipFs.closeSync(realFd); } createReadStream(p, opts) { if (p === null) return this.baseFs.createReadStream(p, opts); return this.makeCallSync(p, () => { return this.baseFs.createReadStream(p, opts); }, (zipFs, { subPath }) => { return zipFs.createReadStream(subPath, opts); }); } createWriteStream(p, opts) { if (p === null) return this.baseFs.createWriteStream(p, opts); return this.makeCallSync(p, () => { return this.baseFs.createWriteStream(p, opts); }, (zipFs, { subPath }) => { return zipFs.createWriteStream(subPath, opts); }); } async realpathPromise(p) { return await this.makeCallPromise(p, async () => { return await this.baseFs.realpathPromise(p); }, async (zipFs, { archivePath, subPath }) => { let realArchivePath = this.realPaths.get(archivePath); if (typeof realArchivePath === `undefined`) { realArchivePath = await this.baseFs.realpathPromise(archivePath); this.realPaths.set(archivePath, realArchivePath); } return this.pathUtils.join(realArchivePath, this.pathUtils.relative(path_1.PortablePath.root, await zipFs.realpathPromise(subPath))); }); } realpathSync(p) { return this.makeCallSync(p, () => { return this.baseFs.realpathSync(p); }, (zipFs, { archivePath, subPath }) => { let realArchivePath = this.realPaths.get(archivePath); if (typeof realArchivePath === `undefined`) { realArchivePath = this.baseFs.realpathSync(archivePath); this.realPaths.set(archivePath, realArchivePath); } return this.pathUtils.join(realArchivePath, this.pathUtils.relative(path_1.PortablePath.root, zipFs.realpathSync(subPath))); }); } async existsPromise(p) { return await this.makeCallPromise(p, async () => { return await this.baseFs.existsPromise(p); }, async (zipFs, { subPath }) => { return await zipFs.existsPromise(subPath); }); } existsSync(p) { return this.makeCallSync(p, () => { return this.baseFs.existsSync(p); }, (zipFs, { subPath }) => { return zipFs.existsSync(subPath); }); } async accessPromise(p, mode) { return await this.makeCallPromise(p, async () => { return await this.baseFs.accessPromise(p, mode); }, async (zipFs, { subPath }) => { return await zipFs.accessPromise(subPath, mode); }); } accessSync(p, mode) { return this.makeCallSync(p, () => { return this.baseFs.accessSync(p, mode); }, (zipFs, { subPath }) => { return zipFs.accessSync(subPath, mode); }); } async statPromise(p, opts) { return await this.makeCallPromise(p, async () => { return await this.baseFs.statPromise(p, opts); }, async (zipFs, { subPath }) => { return await zipFs.statPromise(subPath, opts); }); } statSync(p, opts) { return this.makeCallSync(p, () => { return this.baseFs.statSync(p, opts); }, (zipFs, { subPath }) => { return zipFs.statSync(subPath, opts); }); } async fstatPromise(fd, opts) { if ((fd & ZIP_FD) === 0) return this.baseFs.fstatPromise(fd, opts); const entry = this.fdMap.get(fd); if (typeof entry === `undefined`) throw errors.EBADF(`fstat`); const [zipFs, realFd] = entry; return zipFs.fstatPromise(realFd, opts); } fstatSync(fd, opts) { if ((fd & ZIP_FD) === 0) return this.baseFs.fstatSync(fd, opts); const entry = this.fdMap.get(fd); if (typeof entry === `undefined`) throw errors.EBADF(`fstatSync`); const [zipFs, realFd] = entry; return zipFs.fstatSync(realFd, opts); } async lstatPromise(p, opts) { return await this.makeCallPromise(p, async () => { return await this.baseFs.lstatPromise(p, opts); }, async (zipFs, { subPath }) => { return await zipFs.lstatPromise(subPath, opts); }); } lstatSync(p, opts) { return this.makeCallSync(p, () => { return this.baseFs.lstatSync(p, opts); }, (zipFs, { subPath }) => { return zipFs.lstatSync(subPath, opts); }); } async chmodPromise(p, mask) { return await this.makeCallPromise(p, async () => { return await this.baseFs.chmodPromise(p, mask); }, async (zipFs, { subPath }) => { return await zipFs.chmodPromise(subPath, mask); }); } chmodSync(p, mask) { return this.makeCallSync(p, () => { return this.baseFs.chmodSync(p, mask); }, (zipFs, { subPath }) => { return zipFs.chmodSync(subPath, mask); }); } async chownPromise(p, uid, gid) { return await this.makeCallPromise(p, async () => { return await this.baseFs.chownPromise(p, uid, gid); }, async (zipFs, { subPath }) => { return await zipFs.chownPromise(subPath, uid, gid); }); } chownSync(p, uid, gid) { return this.makeCallSync(p, () => { return this.baseFs.chownSync(p, uid, gid); }, (zipFs, { subPath }) => { return zipFs.chownSync(subPath, uid, gid); }); } async renamePromise(oldP, newP) { return await this.makeCallPromise(oldP, async () => { return await this.makeCallPromise(newP, async () => { return await this.baseFs.renamePromise(oldP, newP); }, async () => { throw Object.assign(new Error(`EEXDEV: cross-device link not permitted`), { code: `EEXDEV` }); }); }, async (zipFsO, { subPath: subPathO }) => { return await this.makeCallPromise(newP, async () => { throw Object.assign(new Error(`EEXDEV: cross-device link not permitted`), { code: `EEXDEV` }); }, async (zipFsN, { subPath: subPathN }) => { if (zipFsO !== zipFsN) { throw Object.assign(new Error(`EEXDEV: cross-device link not permitted`), { code: `EEXDEV` }); } else { return await zipFsO.renamePromise(subPathO, subPathN); } }); }); } renameSync(oldP, newP) { return this.makeCallSync(oldP, () => { return this.makeCallSync(newP, () => { return this.baseFs.renameSync(oldP, newP); }, async () => { throw Object.assign(new Error(`EEXDEV: cross-device link not permitted`), { code: `EEXDEV` }); }); }, (zipFsO, { subPath: subPathO }) => { return this.makeCallSync(newP, () => { throw Object.assign(new Error(`EEXDEV: cross-device link not permitted`), { code: `EEXDEV` }); }, (zipFsN, { subPath: subPathN }) => { if (zipFsO !== zipFsN) { throw Object.assign(new Error(`EEXDEV: cross-device link not permitted`), { code: `EEXDEV` }); } else { return zipFsO.renameSync(subPathO, subPathN); } }); }); } async copyFilePromise(sourceP, destP, flags = 0) { const fallback = async (sourceFs, sourceP, destFs, destP) => { if ((flags & fs_1.constants.COPYFILE_FICLONE_FORCE) !== 0) throw Object.assign(new Error(`EXDEV: cross-device clone not permitted, copyfile '${sourceP}' -> ${destP}'`), { code: `EXDEV` }); if ((flags & fs_1.constants.COPYFILE_EXCL) && await this.existsPromise(sourceP)) throw Object.assign(new Error(`EEXIST: file already exists, copyfile '${sourceP}' -> '${destP}'`), { code: `EEXIST` }); let content; try { content = await sourceFs.readFilePromise(sourceP); } catch (error) { throw Object.assign(new Error(`EINVAL: invalid argument, copyfile '${sourceP}' -> '${destP}'`), { code: `EINVAL` }); } await destFs.writeFilePromise(destP, content); }; return await this.makeCallPromise(sourceP, async () => { return await this.makeCallPromise(destP, async () => { return await this.baseFs.copyFilePromise(sourceP, destP, flags); }, async (zipFsD, { subPath: subPathD }) => { return await fallback(this.baseFs, sourceP, zipFsD, subPathD); }); }, async (zipFsS, { subPath: subPathS }) => { return await this.makeCallPromise(destP, async () => { return await fallback(zipFsS, subPathS, this.baseFs, destP); }, async (zipFsD, { subPath: subPathD }) => { if (zipFsS !== zipFsD) { return await fallback(zipFsS, subPathS, zipFsD, subPathD); } else { return await zipFsS.copyFilePromise(subPathS, subPathD, flags); } }); }); } copyFileSync(sourceP, destP, flags = 0) { const fallback = (sourceFs, sourceP, destFs, destP) => { if ((flags & fs_1.constants.COPYFILE_FICLONE_FORCE) !== 0) throw Object.assign(new Error(`EXDEV: cross-device clone not permitted, copyfile '${sourceP}' -> ${destP}'`), { code: `EXDEV` }); if ((flags & fs_1.constants.COPYFILE_EXCL) && this.existsSync(sourceP)) throw Object.assign(new Error(`EEXIST: file already exists, copyfile '${sourceP}' -> '${destP}'`), { code: `EEXIST` }); let content; try { content = sourceFs.readFileSync(sourceP); } catch (error) { throw Object.assign(new Error(`EINVAL: invalid argument, copyfile '${sourceP}' -> '${destP}'`), { code: `EINVAL` }); } destFs.writeFileSync(destP, content); }; return this.makeCallSync(sourceP, () => { return this.makeCallSync(destP, () => { return this.baseFs.copyFileSync(sourceP, destP, flags); }, (zipFsD, { subPath: subPathD }) => { return fallback(this.baseFs, sourceP, zipFsD, subPathD); }); }, (zipFsS, { subPath: subPathS }) => { return this.makeCallSync(destP, () => { return fallback(zipFsS, subPathS, this.baseFs, destP); }, (zipFsD, { subPath: subPathD }) => { if (zipFsS !== zipFsD) { return fallback(zipFsS, subPathS, zipFsD, subPathD); } else { return zipFsS.copyFileSync(subPathS, subPathD, flags); } }); }); } async appendFilePromise(p, content, opts) { return await this.makeCallPromise(p, async () => { return await this.baseFs.appendFilePromise(p, content, opts); }, async (zipFs, { subPath }) => { return await zipFs.appendFilePromise(subPath, content, opts); }); } appendFileSync(p, content, opts) { return this.makeCallSync(p, () => { return this.baseFs.appendFileSync(p, content, opts); }, (zipFs, { subPath }) => { return zipFs.appendFileSync(subPath, content, opts); }); } async writeFilePromise(p, content, opts) { return await this.makeCallPromise(p, async () => { return await this.baseFs.writeFilePromise(p, content, opts); }, async (zipFs, { subPath }) => { return await zipFs.writeFilePromise(subPath, content, opts); }); } writeFileSync(p, content, opts) { return this.makeCallSync(p, () => { return this.baseFs.writeFileSync(p, content, opts); }, (zipFs, { subPath }) => { return zipFs.writeFileSync(subPath, content, opts); }); } async unlinkPromise(p) { return await this.makeCallPromise(p, async () => { return await this.baseFs.unlinkPromise(p); }, async (zipFs, { subPath }) => { return await zipFs.unlinkPromise(subPath); }); } unlinkSync(p) { return this.makeCallSync(p, () => { return this.baseFs.unlinkSync(p); }, (zipFs, { subPath }) => { return zipFs.unlinkSync(subPath); }); } async utimesPromise(p, atime, mtime) { return await this.makeCallPromise(p, async () => { return await this.baseFs.utimesPromise(p, atime, mtime); }, async (zipFs, { subPath }) => { return await zipFs.utimesPromise(subPath, atime, mtime); }); } utimesSync(p, atime, mtime) { return this.makeCallSync(p, () => { return this.baseFs.utimesSync(p, atime, mtime); }, (zipFs, { subPath }) => { return zipFs.utimesSync(subPath, atime, mtime); }); } async mkdirPromise(p, opts) { return await this.makeCallPromise(p, async () => { return await this.baseFs.mkdirPromise(p, opts); }, async (zipFs, { subPath }) => { return await zipFs.mkdirPromise(subPath, opts); }); } mkdirSync(p, opts) { return this.makeCallSync(p, () => { return this.baseFs.mkdirSync(p, opts); }, (zipFs, { subPath }) => { return zipFs.mkdirSync(subPath, opts); }); } async rmdirPromise(p, opts) { return await this.makeCallPromise(p, async () => { return await this.baseFs.rmdirPromise(p, opts); }, async (zipFs, { subPath }) => { return await zipFs.rmdirPromise(subPath, opts); }); } rmdirSync(p, opts) { return this.makeCallSync(p, () => { return this.baseFs.rmdirSync(p, opts); }, (zipFs, { subPath }) => { return zipFs.rmdirSync(subPath, opts); }); } async linkPromise(existingP, newP) { return await this.makeCallPromise(newP, async () => { return await this.baseFs.linkPromise(existingP, newP); }, async (zipFs, { subPath }) => { return await zipFs.linkPromise(existingP, subPath); }); } linkSync(existingP, newP) { return this.makeCallSync(newP, () => { return this.baseFs.linkSync(existingP, newP); }, (zipFs, { subPath }) => { return zipFs.linkSync(existingP, subPath); }); } async symlinkPromise(target, p, type) { return await this.makeCallPromise(p, async () => { return await this.baseFs.symlinkPromise(target, p, type); }, async (zipFs, { subPath }) => { return await zipFs.symlinkPromise(target, subPath); }); } symlinkSync(target, p, type) { return this.makeCallSync(p, () => { return this.baseFs.symlinkSync(target, p, type); }, (zipFs, { subPath }) => { return zipFs.symlinkSync(target, subPath); }); } async readFilePromise(p, encoding) { return this.makeCallPromise(p, async () => { // This weird switch is required to tell TypeScript that the signatures are proper (otherwise it thinks that only the generic one is covered) switch (encoding) { case `utf8`: return await this.baseFs.readFilePromise(p, encoding); default: return await this.baseFs.readFilePromise(p, encoding); } }, async (zipFs, { subPath }) => { return await zipFs.readFilePromise(subPath, encoding); }); } readFileSync(p, encoding) { return this.makeCallSync(p, () => { // This weird switch is required to tell TypeScript that the signatures are proper (otherwise it thinks that only the generic one is covered) switch (encoding) { case `utf8`: return this.baseFs.readFileSync(p, encoding); default: return this.baseFs.readFileSync(p, encoding); } }, (zipFs, { subPath }) => { return zipFs.readFileSync(subPath, encoding); }); } async readdirPromise(p, opts) { return await this.makeCallPromise(p, async () => { return await this.baseFs.readdirPromise(p, opts); }, async (zipFs, { subPath }) => { return await zipFs.readdirPromise(subPath, opts); }, { requireSubpath: false, }); } readdirSync(p, opts) { return this.makeCallSync(p, () => { return this.baseFs.readdirSync(p, opts); }, (zipFs, { subPath }) => { return zipFs.readdirSync(subPath, opts); }, { requireSubpath: false, }); } async readlinkPromise(p) { return await this.makeCallPromise(p, async () => { return await this.baseFs.readlinkPromise(p); }, async (zipFs, { subPath }) => { return await zipFs.readlinkPromise(subPath); }); } readlinkSync(p) { return this.makeCallSync(p, () => { return this.baseFs.readlinkSync(p); }, (zipFs, { subPath }) => { return zipFs.readlinkSync(subPath); }); } async truncatePromise(p, len) { return await this.makeCallPromise(p, async () => { return await this.baseFs.truncatePromise(p, len); }, async (zipFs, { subPath }) => { return await zipFs.truncatePromise(subPath, len); }); } truncateSync(p, len) { return this.makeCallSync(p, () => { return this.baseFs.truncateSync(p, len); }, (zipFs, { subPath }) => { return zipFs.truncateSync(subPath, len); }); } watch(p, a, b) { return this.makeCallSync(p, () => { return this.baseFs.watch(p, // @ts-expect-error a, b); }, (zipFs, { subPath }) => { return zipFs.watch(subPath, // @ts-expect-error a, b); }); } watchFile(p, a, b) { return this.makeCallSync(p, () => { return this.baseFs.watchFile(p, // @ts-expect-error a, b); }, () => { return watchFile_1.watchFile(this, p, a, b); }); } unwatchFile(p, cb) { return this.makeCallSync(p, () => { return this.baseFs.unwatchFile(p, cb); }, () => { return watchFile_1.unwatchFile(this, p, cb); }); } async makeCallPromise(p, discard, accept, { requireSubpath = true } = {}) { if (typeof p !== `string`) return await discard(); const normalizedP = this.resolve(p); const zipInfo = this.findZip(normalizedP); if (!zipInfo) return await discard(); if (requireSubpath && zipInfo.subPath === `/`) return await discard(); return await this.getZipPromise(zipInfo.archivePath, async (zipFs) => await accept(zipFs, zipInfo)); } makeCallSync(p, discard, accept, { requireSubpath = true } = {}) { if (typeof p !== `string`) return discard(); const normalizedP = this.resolve(p); const zipInfo = this.findZip(normalizedP); if (!zipInfo) return discard(); if (requireSubpath && zipInfo.subPath === `/`) return discard(); return this.getZipSync(zipInfo.archivePath, zipFs => accept(zipFs, zipInfo)); } findZip(p) { if (this.filter && !this.filter.test(p)) return null; let filePath = ``; while (true) { const archivePart = exports.getArchivePart(p.substr(filePath.length)); if (!archivePart) return null; filePath = this.pathUtils.join(filePath, archivePart); if (this.isZip.has(filePath) === false) { if (this.notZip.has(filePath)) continue; try { if (!this.baseFs.lstatSync(filePath).isFile()) { this.notZip.add(filePath); continue; } } catch (_a) { return null; } this.isZip.add(filePath); } return { archivePath: filePath, subPath: this.pathUtils.join(path_1.PortablePath.root, p.substr(filePath.length)), }; } } limitOpenFiles(max) { if (this.zipInstances === null) return; const now = Date.now(); let nextExpiresAt = now + this.maxAge; let closeCount = max === null ? 0 : this.zipInstances.size - max; for (const [path, { zipFs, expiresAt, refCount }] of this.zipInstances.entries()) { if (refCount !== 0 || zipFs.hasOpenFileHandles()) { continue; } else if (now >= expiresAt) { zipFs.saveAndClose(); this.zipInstances.delete(path); closeCount -= 1; continue; } else if (max === null || closeCount <= 0) { nextExpiresAt = expiresAt; break; } zipFs.saveAndClose(); this.zipInstances.delete(path); closeCount -= 1; } if (this.limitOpenFilesTimeout === null && ((max === null && this.zipInstances.size > 0) || max !== null)) { this.limitOpenFilesTimeout = setTimeout(() => { this.limitOpenFilesTimeout = null; this.limitOpenFiles(null); }, nextExpiresAt - now).unref(); } } async getZipPromise(p, accept) { const getZipOptions = async () => ({ baseFs: this.baseFs, libzip: this.libzip, readOnly: this.readOnlyArchives, stats: await this.baseFs.statPromise(p), }); if (this.zipInstances) { let cachedZipFs = this.zipInstances.get(p); if (!cachedZipFs) { const zipOptions = await getZipOptions(); // We need to recheck because concurrent getZipPromise calls may // have instantiated the zip archive while we were waiting cachedZipFs = this.zipInstances.get(p); if (!cachedZipFs) { cachedZipFs = { zipFs: new ZipFS_1.ZipFS(p, zipOptions), expiresAt: 0, refCount: 0, }; } } // Removing then re-adding the field allows us to easily implement // a basic LRU garbage collection strategy this.zipInstances.delete(p); this.limitOpenFiles(this.maxOpenFiles - 1); this.zipInstances.set(p, cachedZipFs); cachedZipFs.expiresAt = Date.now() + this.maxAge; cachedZipFs.refCount += 1; try { return await accept(cachedZipFs.zipFs); } finally { cachedZipFs.refCount -= 1; } } else { const zipFs = new ZipFS_1.ZipFS(p, await getZipOptions()); try { return await accept(zipFs); } finally { zipFs.saveAndClose(); } } } getZipSync(p, accept) { const getZipOptions = () => ({ baseFs: this.baseFs, libzip: this.libzip, readOnly: this.readOnlyArchives, stats: this.baseFs.statSync(p), }); if (this.zipInstances) { let cachedZipFs = this.zipInstances.get(p); if (!cachedZipFs) { cachedZipFs = { zipFs: new ZipFS_1.ZipFS(p, getZipOptions()), expiresAt: 0, refCount: 0, }; } // Removing then re-adding the field allows us to easily implement // a basic LRU garbage collection strategy this.zipInstances.delete(p); this.limitOpenFiles(this.maxOpenFiles - 1); this.zipInstances.set(p, cachedZipFs); cachedZipFs.expiresAt = Date.now() + this.maxAge; return accept(cachedZipFs.zipFs); } else { const zipFs = new ZipFS_1.ZipFS(p, getZipOptions()); try { return accept(zipFs); } finally { zipFs.saveAndClose(); } } } } exports.ZipOpenFS = ZipOpenFS; /***/ }), /***/ 9867: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.copyPromise = exports.LinkStrategy = void 0; const tslib_1 = __webpack_require__(70655); const fs_1 = tslib_1.__importDefault(__webpack_require__(57147)); const path_1 = __webpack_require__(7194); // 1980-01-01, like Fedora const defaultTime = new Date(315532800 * 1000); var LinkStrategy; (function (LinkStrategy) { LinkStrategy["Allow"] = "allow"; LinkStrategy["ReadOnly"] = "readOnly"; })(LinkStrategy = exports.LinkStrategy || (exports.LinkStrategy = {})); async function copyPromise(destinationFs, destination, sourceFs, source, opts) { const normalizedDestination = destinationFs.pathUtils.normalize(destination); const normalizedSource = sourceFs.pathUtils.normalize(source); const prelayout = []; const postlayout = []; await destinationFs.mkdirPromise(destinationFs.pathUtils.dirname(destination), { recursive: true }); const updateTime = typeof destinationFs.lutimesPromise === `function` ? destinationFs.lutimesPromise.bind(destinationFs) : destinationFs.utimesPromise.bind(destinationFs); await copyImpl(prelayout, postlayout, updateTime, destinationFs, normalizedDestination, sourceFs, normalizedSource, opts); for (const operation of prelayout) await operation(); await Promise.all(postlayout.map(operation => { return operation(); })); } exports.copyPromise = copyPromise; async function copyImpl(prelayout, postlayout, updateTime, destinationFs, destination, sourceFs, source, opts) { var _a, _b; const destinationStat = await maybeLStat(destinationFs, destination); const sourceStat = await sourceFs.lstatPromise(source); const referenceTime = opts.stableTime ? { mtime: defaultTime, atime: defaultTime } : sourceStat; let updated; switch (true) { case sourceStat.isDirectory(): { updated = await copyFolder(prelayout, postlayout, updateTime, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts); } break; case sourceStat.isFile(): { updated = await copyFile(prelayout, postlayout, updateTime, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts); } break; case sourceStat.isSymbolicLink(): { updated = await copySymlink(prelayout, postlayout, updateTime, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts); } break; default: { throw new Error(`Unsupported file type (${sourceStat.mode})`); } break; } if (updated || ((_a = destinationStat === null || destinationStat === void 0 ? void 0 : destinationStat.mtime) === null || _a === void 0 ? void 0 : _a.getTime()) !== referenceTime.mtime.getTime() || ((_b = destinationStat === null || destinationStat === void 0 ? void 0 : destinationStat.atime) === null || _b === void 0 ? void 0 : _b.getTime()) !== referenceTime.atime.getTime()) { postlayout.push(() => updateTime(destination, referenceTime.atime, referenceTime.mtime)); updated = true; } if (destinationStat === null || (destinationStat.mode & 0o777) !== (sourceStat.mode & 0o777)) { postlayout.push(() => destinationFs.chmodPromise(destination, sourceStat.mode & 0o777)); updated = true; } return updated; } async function maybeLStat(baseFs, p) { try { return await baseFs.lstatPromise(p); } catch (e) { return null; } } async function copyFolder(prelayout, postlayout, updateTime, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts) { if (destinationStat !== null && !destinationStat.isDirectory()) { if (opts.overwrite) { prelayout.push(async () => destinationFs.removePromise(destination)); destinationStat = null; } else { return false; } } let updated = false; if (destinationStat === null) { prelayout.push(async () => destinationFs.mkdirPromise(destination, { mode: sourceStat.mode })); updated = true; } const entries = await sourceFs.readdirPromise(source); if (opts.stableSort) { for (const entry of entries.sort()) { if (await copyImpl(prelayout, postlayout, updateTime, destinationFs, destinationFs.pathUtils.join(destination, entry), sourceFs, sourceFs.pathUtils.join(source, entry), opts)) { updated = true; } } } else { const entriesUpdateStatus = await Promise.all(entries.map(async (entry) => { await copyImpl(prelayout, postlayout, updateTime, destinationFs, destinationFs.pathUtils.join(destination, entry), sourceFs, sourceFs.pathUtils.join(source, entry), opts); })); if (entriesUpdateStatus.some(status => status)) { updated = true; } } return updated; } const isCloneSupportedCache = new WeakMap(); function makeLinkOperation(opFs, destination, source, sourceStat, linkStrategy) { return async () => { await opFs.linkPromise(source, destination); if (linkStrategy === LinkStrategy.ReadOnly) { // We mutate the stat, otherwise it'll be reset by copyImpl sourceStat.mode &= ~0o222; await opFs.chmodPromise(destination, sourceStat.mode); } }; } function makeCloneLinkOperation(opFs, destination, source, sourceStat, linkStrategy) { const isCloneSupported = isCloneSupportedCache.get(opFs); if (typeof isCloneSupported === `undefined`) { return async () => { try { await opFs.copyFilePromise(source, destination, fs_1.default.constants.COPYFILE_FICLONE_FORCE); isCloneSupportedCache.set(opFs, true); } catch (err) { if (err.code === `ENOSYS` || err.code === `ENOTSUP`) { isCloneSupportedCache.set(opFs, false); await makeLinkOperation(opFs, destination, source, sourceStat, linkStrategy)(); } else { throw err; } } }; } else { if (isCloneSupported) { return async () => opFs.copyFilePromise(source, destination, fs_1.default.constants.COPYFILE_FICLONE_FORCE); } else { return makeLinkOperation(opFs, destination, source, sourceStat, linkStrategy); } } } async function copyFile(prelayout, postlayout, updateTime, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts) { var _a; if (destinationStat !== null) { if (opts.overwrite) { prelayout.push(async () => destinationFs.removePromise(destination)); destinationStat = null; } else { return false; } } const linkStrategy = (_a = opts.linkStrategy) !== null && _a !== void 0 ? _a : null; const op = destinationFs === sourceFs ? linkStrategy !== null ? makeCloneLinkOperation(destinationFs, destination, source, sourceStat, linkStrategy) : async () => destinationFs.copyFilePromise(source, destination, fs_1.default.constants.COPYFILE_FICLONE) : linkStrategy !== null ? makeLinkOperation(destinationFs, destination, source, sourceStat, linkStrategy) : async () => destinationFs.writeFilePromise(destination, await sourceFs.readFilePromise(source)); prelayout.push(async () => op()); return true; } async function copySymlink(prelayout, postlayout, updateTime, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts) { if (destinationStat !== null) { if (opts.overwrite) { prelayout.push(async () => destinationFs.removePromise(destination)); destinationStat = null; } else { return false; } } prelayout.push(async () => { await destinationFs.symlinkPromise(path_1.convertPath(destinationFs.pathUtils, await sourceFs.readlinkPromise(source)), destination); }); return true; } /***/ }), /***/ 74694: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.opendir = exports.CustomDir = void 0; const tslib_1 = __webpack_require__(70655); const errors = tslib_1.__importStar(__webpack_require__(15004)); class CustomDir { constructor(path, nextDirent, opts = {}) { this.path = path; this.nextDirent = nextDirent; this.opts = opts; this.closed = false; } throwIfClosed() { if (this.closed) { throw errors.ERR_DIR_CLOSED(); } } async *[Symbol.asyncIterator]() { try { let dirent; // eslint-disable-next-line no-cond-assign while ((dirent = await this.read()) !== null) { yield dirent; } } finally { await this.close(); } } read(cb) { const dirent = this.readSync(); if (typeof cb !== `undefined`) return cb(null, dirent); return Promise.resolve(dirent); } readSync() { this.throwIfClosed(); return this.nextDirent(); } close(cb) { this.closeSync(); if (typeof cb !== `undefined`) return cb(null); return Promise.resolve(); } closeSync() { var _a, _b; this.throwIfClosed(); (_b = (_a = this.opts).onClose) === null || _b === void 0 ? void 0 : _b.call(_a); this.closed = true; } } exports.CustomDir = CustomDir; function opendir(fakeFs, path, entries, opts) { const nextDirent = () => { const filename = entries.shift(); if (typeof filename === `undefined`) return null; return Object.assign(fakeFs.statSync(fakeFs.pathUtils.join(path, filename)), { name: filename, }); }; return new CustomDir(path, nextDirent, opts); } exports.opendir = opendir; /***/ }), /***/ 38242: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.unwatchAllFiles = exports.unwatchFile = exports.watchFile = void 0; const CustomStatWatcher_1 = __webpack_require__(54190); const statWatchersByFakeFS = new WeakMap(); function watchFile(fakeFs, path, a, b) { let bigint; let persistent; let interval; let listener; switch (typeof a) { case `function`: { bigint = false; persistent = true; interval = 5007; listener = a; } break; default: { ({ bigint = false, persistent = true, interval = 5007, } = a); listener = b; } break; } let statWatchers = statWatchersByFakeFS.get(fakeFs); if (typeof statWatchers === `undefined`) statWatchersByFakeFS.set(fakeFs, statWatchers = new Map()); let statWatcher = statWatchers.get(path); if (typeof statWatcher === `undefined`) { statWatcher = CustomStatWatcher_1.CustomStatWatcher.create(fakeFs, path, { bigint }); statWatchers.set(path, statWatcher); } statWatcher.registerChangeListener(listener, { persistent, interval }); return statWatcher; } exports.watchFile = watchFile; function unwatchFile(fakeFs, path, cb) { const statWatchers = statWatchersByFakeFS.get(fakeFs); if (typeof statWatchers === `undefined`) return; const statWatcher = statWatchers.get(path); if (typeof statWatcher === `undefined`) return; if (typeof cb === `undefined`) statWatcher.unregisterAllChangeListeners(); else statWatcher.unregisterChangeListener(cb); if (!statWatcher.hasChangeListeners()) { statWatcher.stop(); statWatchers.delete(path); } } exports.unwatchFile = unwatchFile; function unwatchAllFiles(fakeFs) { const statWatchers = statWatchersByFakeFS.get(fakeFs); if (typeof statWatchers === `undefined`) return; for (const path of statWatchers.keys()) { unwatchFile(fakeFs, path); } } exports.unwatchAllFiles = unwatchAllFiles; /***/ }), /***/ 54190: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CustomStatWatcher = exports.assertStatus = exports.Status = exports.Event = void 0; const tslib_1 = __webpack_require__(70655); const events_1 = __webpack_require__(82361); const statUtils = tslib_1.__importStar(__webpack_require__(62576)); var Event; (function (Event) { Event["Change"] = "change"; Event["Stop"] = "stop"; })(Event = exports.Event || (exports.Event = {})); var Status; (function (Status) { Status["Ready"] = "ready"; Status["Running"] = "running"; Status["Stopped"] = "stopped"; })(Status = exports.Status || (exports.Status = {})); function assertStatus(current, expected) { if (current !== expected) { throw new Error(`Invalid StatWatcher status: expected '${expected}', got '${current}'`); } } exports.assertStatus = assertStatus; class CustomStatWatcher extends events_1.EventEmitter { constructor(fakeFs, path, { bigint = false } = {}) { super(); this.status = Status.Ready; this.changeListeners = new Map(); this.startTimeout = null; this.fakeFs = fakeFs; this.path = path; this.bigint = bigint; this.lastStats = this.stat(); } static create(fakeFs, path, opts) { const statWatcher = new CustomStatWatcher(fakeFs, path, opts); statWatcher.start(); return statWatcher; } start() { assertStatus(this.status, Status.Ready); this.status = Status.Running; // Node allows other listeners to be registered up to 3 milliseconds // after the watcher has been started, so that's what we're doing too this.startTimeout = setTimeout(() => { this.startTimeout = null; // Per the Node FS docs: // "When an fs.watchFile operation results in an ENOENT error, // it will invoke the listener once, with all the fields zeroed // (or, for dates, the Unix Epoch)." if (!this.fakeFs.existsSync(this.path)) { this.emit(Event.Change, this.lastStats, this.lastStats); } }, 3); } stop() { assertStatus(this.status, Status.Running); this.status = Status.Stopped; if (this.startTimeout !== null) { clearTimeout(this.startTimeout); this.startTimeout = null; } this.emit(Event.Stop); } stat() { try { return this.fakeFs.statSync(this.path, { bigint: this.bigint }); } catch (error) { if (error.code === `ENOENT`) { const statInstance = this.bigint ? new statUtils.BigIntStatsEntry() : new statUtils.StatEntry(); return statUtils.clearStats(statInstance); } else { throw error; } } } /** * Creates an interval whose callback compares the current stats with the previous stats and notifies all listeners in case of changes. * * @param opts.persistent Decides whether the interval should be immediately unref-ed. */ makeInterval(opts) { const interval = setInterval(() => { const currentStats = this.stat(); const previousStats = this.lastStats; if (statUtils.areStatsEqual(currentStats, previousStats)) return; this.lastStats = currentStats; this.emit(Event.Change, currentStats, previousStats); }, opts.interval); return opts.persistent ? interval : interval.unref(); } /** * Registers a listener and assigns it an interval. */ registerChangeListener(listener, opts) { this.addListener(Event.Change, listener); this.changeListeners.set(listener, this.makeInterval(opts)); } /** * Unregisters the listener and clears the assigned interval. */ unregisterChangeListener(listener) { this.removeListener(Event.Change, listener); const interval = this.changeListeners.get(listener); if (typeof interval !== `undefined`) clearInterval(interval); this.changeListeners.delete(listener); } /** * Unregisters all listeners and clears all assigned intervals. */ unregisterAllChangeListeners() { for (const listener of this.changeListeners.keys()) { this.unregisterChangeListener(listener); } } hasChangeListeners() { return this.changeListeners.size > 0; } /** * Refs all stored intervals. */ ref() { for (const interval of this.changeListeners.values()) interval.ref(); return this; } /** * Unrefs all stored intervals. */ unref() { for (const interval of this.changeListeners.values()) interval.unref(); return this; } } exports.CustomStatWatcher = CustomStatWatcher; /***/ }), /***/ 92775: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.S_IFLNK = exports.S_IFREG = exports.S_IFDIR = exports.S_IFMT = void 0; exports.S_IFMT = 0o170000; exports.S_IFDIR = 0o040000; exports.S_IFREG = 0o100000; exports.S_IFLNK = 0o120000; /***/ }), /***/ 15004: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LibzipError = exports.ERR_DIR_CLOSED = exports.EOPNOTSUPP = exports.ENOTEMPTY = exports.EROFS = exports.EEXIST = exports.EISDIR = exports.ENOTDIR = exports.ENOENT = exports.EBADF = exports.EINVAL = exports.ENOSYS = exports.EBUSY = void 0; function makeError(code, message) { return Object.assign(new Error(`${code}: ${message}`), { code }); } function EBUSY(message) { return makeError(`EBUSY`, message); } exports.EBUSY = EBUSY; function ENOSYS(message, reason) { return makeError(`ENOSYS`, `${message}, ${reason}`); } exports.ENOSYS = ENOSYS; function EINVAL(reason) { return makeError(`EINVAL`, `invalid argument, ${reason}`); } exports.EINVAL = EINVAL; function EBADF(reason) { return makeError(`EBADF`, `bad file descriptor, ${reason}`); } exports.EBADF = EBADF; function ENOENT(reason) { return makeError(`ENOENT`, `no such file or directory, ${reason}`); } exports.ENOENT = ENOENT; function ENOTDIR(reason) { return makeError(`ENOTDIR`, `not a directory, ${reason}`); } exports.ENOTDIR = ENOTDIR; function EISDIR(reason) { return makeError(`EISDIR`, `illegal operation on a directory, ${reason}`); } exports.EISDIR = EISDIR; function EEXIST(reason) { return makeError(`EEXIST`, `file already exists, ${reason}`); } exports.EEXIST = EEXIST; function EROFS(reason) { return makeError(`EROFS`, `read-only filesystem, ${reason}`); } exports.EROFS = EROFS; function ENOTEMPTY(reason) { return makeError(`ENOTEMPTY`, `directory not empty, ${reason}`); } exports.ENOTEMPTY = ENOTEMPTY; function EOPNOTSUPP(reason) { return makeError(`EOPNOTSUPP`, `operation not supported, ${reason}`); } exports.EOPNOTSUPP = EOPNOTSUPP; // ------------------------------------------------------------------------ function ERR_DIR_CLOSED() { return makeError(`ERR_DIR_CLOSED`, `Directory handle was closed`); } exports.ERR_DIR_CLOSED = ERR_DIR_CLOSED; // ------------------------------------------------------------------------ class LibzipError extends Error { constructor(message, code) { super(message); this.name = `Libzip Error`; this.code = code; } } exports.LibzipError = LibzipError; /***/ }), /***/ 91794: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.xfs = exports.extendFs = exports.patchFs = exports.ZipOpenFS = exports.ZipFS = exports.VirtualFS = exports.ProxiedFS = exports.PosixFS = exports.NodeFS = exports.NoFS = exports.LazyFS = exports.JailFS = exports.CwdFS = exports.FakeFS = exports.AliasFS = exports.toFilename = exports.ppath = exports.npath = exports.Filename = exports.PortablePath = exports.DEFAULT_COMPRESSION_LEVEL = exports.normalizeLineEndings = exports.statUtils = exports.opendir = exports.LinkStrategy = void 0; const tslib_1 = __webpack_require__(70655); const statUtils = tslib_1.__importStar(__webpack_require__(62576)); exports.statUtils = statUtils; var copyPromise_1 = __webpack_require__(9867); Object.defineProperty(exports, "LinkStrategy", ({ enumerable: true, get: function () { return copyPromise_1.LinkStrategy; } })); var opendir_1 = __webpack_require__(74694); Object.defineProperty(exports, "opendir", ({ enumerable: true, get: function () { return opendir_1.opendir; } })); var FakeFS_1 = __webpack_require__(86936); Object.defineProperty(exports, "normalizeLineEndings", ({ enumerable: true, get: function () { return FakeFS_1.normalizeLineEndings; } })); var ZipFS_1 = __webpack_require__(56970); Object.defineProperty(exports, "DEFAULT_COMPRESSION_LEVEL", ({ enumerable: true, get: function () { return ZipFS_1.DEFAULT_COMPRESSION_LEVEL; } })); var path_1 = __webpack_require__(7194); Object.defineProperty(exports, "PortablePath", ({ enumerable: true, get: function () { return path_1.PortablePath; } })); Object.defineProperty(exports, "Filename", ({ enumerable: true, get: function () { return path_1.Filename; } })); var path_2 = __webpack_require__(7194); Object.defineProperty(exports, "npath", ({ enumerable: true, get: function () { return path_2.npath; } })); Object.defineProperty(exports, "ppath", ({ enumerable: true, get: function () { return path_2.ppath; } })); Object.defineProperty(exports, "toFilename", ({ enumerable: true, get: function () { return path_2.toFilename; } })); var AliasFS_1 = __webpack_require__(11473); Object.defineProperty(exports, "AliasFS", ({ enumerable: true, get: function () { return AliasFS_1.AliasFS; } })); var FakeFS_2 = __webpack_require__(86936); Object.defineProperty(exports, "FakeFS", ({ enumerable: true, get: function () { return FakeFS_2.FakeFS; } })); var CwdFS_1 = __webpack_require__(79918); Object.defineProperty(exports, "CwdFS", ({ enumerable: true, get: function () { return CwdFS_1.CwdFS; } })); var JailFS_1 = __webpack_require__(73266); Object.defineProperty(exports, "JailFS", ({ enumerable: true, get: function () { return JailFS_1.JailFS; } })); var LazyFS_1 = __webpack_require__(44242); Object.defineProperty(exports, "LazyFS", ({ enumerable: true, get: function () { return LazyFS_1.LazyFS; } })); var NoFS_1 = __webpack_require__(74585); Object.defineProperty(exports, "NoFS", ({ enumerable: true, get: function () { return NoFS_1.NoFS; } })); var NodeFS_1 = __webpack_require__(78633); Object.defineProperty(exports, "NodeFS", ({ enumerable: true, get: function () { return NodeFS_1.NodeFS; } })); var PosixFS_1 = __webpack_require__(22155); Object.defineProperty(exports, "PosixFS", ({ enumerable: true, get: function () { return PosixFS_1.PosixFS; } })); var ProxiedFS_1 = __webpack_require__(93334); Object.defineProperty(exports, "ProxiedFS", ({ enumerable: true, get: function () { return ProxiedFS_1.ProxiedFS; } })); var VirtualFS_1 = __webpack_require__(65013); Object.defineProperty(exports, "VirtualFS", ({ enumerable: true, get: function () { return VirtualFS_1.VirtualFS; } })); var ZipFS_2 = __webpack_require__(56970); Object.defineProperty(exports, "ZipFS", ({ enumerable: true, get: function () { return ZipFS_2.ZipFS; } })); var ZipOpenFS_1 = __webpack_require__(32031); Object.defineProperty(exports, "ZipOpenFS", ({ enumerable: true, get: function () { return ZipOpenFS_1.ZipOpenFS; } })); var patchFs_1 = __webpack_require__(98068); Object.defineProperty(exports, "patchFs", ({ enumerable: true, get: function () { return patchFs_1.patchFs; } })); Object.defineProperty(exports, "extendFs", ({ enumerable: true, get: function () { return patchFs_1.extendFs; } })); var xfs_1 = __webpack_require__(34513); Object.defineProperty(exports, "xfs", ({ enumerable: true, get: function () { return xfs_1.xfs; } })); /***/ }), /***/ 98068: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.extendFs = exports.patchFs = void 0; const util_1 = __webpack_require__(73837); const URLFS_1 = __webpack_require__(81894); const SYNC_IMPLEMENTATIONS = new Set([ `accessSync`, `appendFileSync`, `createReadStream`, `chmodSync`, `chownSync`, `closeSync`, `copyFileSync`, `linkSync`, `lstatSync`, `fstatSync`, `lutimesSync`, `mkdirSync`, `openSync`, `opendirSync`, `readSync`, `readlinkSync`, `readFileSync`, `readdirSync`, `readlinkSync`, `realpathSync`, `renameSync`, `rmdirSync`, `statSync`, `symlinkSync`, `truncateSync`, `unlinkSync`, `unwatchFile`, `utimesSync`, `watch`, `watchFile`, `writeFileSync`, `writeSync`, ]); const ASYNC_IMPLEMENTATIONS = new Set([ `accessPromise`, `appendFilePromise`, `chmodPromise`, `chownPromise`, `closePromise`, `copyFilePromise`, `linkPromise`, `fstatPromise`, `lstatPromise`, `lutimesPromise`, `mkdirPromise`, `openPromise`, `opendirPromise`, `readdirPromise`, `realpathPromise`, `readFilePromise`, `readdirPromise`, `readlinkPromise`, `renamePromise`, `rmdirPromise`, `statPromise`, `symlinkPromise`, `truncatePromise`, `unlinkPromise`, `utimesPromise`, `writeFilePromise`, `writeSync`, ]); const FILEHANDLE_IMPLEMENTATIONS = new Set([ `appendFilePromise`, `chmodPromise`, `chownPromise`, `closePromise`, `readPromise`, `readFilePromise`, `statPromise`, `truncatePromise`, `utimesPromise`, `writePromise`, `writeFilePromise`, ]); function patchFs(patchedFs, fakeFs) { // We wrap the `fakeFs` with a `URLFS` to add support for URL instances fakeFs = new URLFS_1.URLFS(fakeFs); const setupFn = (target, name, replacement) => { const orig = target[name]; target[name] = replacement; // Preserve any util.promisify implementations if (typeof (orig === null || orig === void 0 ? void 0 : orig[util_1.promisify.custom]) !== `undefined`) { replacement[util_1.promisify.custom] = orig[util_1.promisify.custom]; } }; /** Callback implementations */ { setupFn(patchedFs, `exists`, (p, ...args) => { const hasCallback = typeof args[args.length - 1] === `function`; const callback = hasCallback ? args.pop() : () => { }; process.nextTick(() => { fakeFs.existsPromise(p).then(exists => { callback(exists); }, () => { callback(false); }); }); }); setupFn(patchedFs, `read`, (p, buffer, ...args) => { const hasCallback = typeof args[args.length - 1] === `function`; const callback = hasCallback ? args.pop() : () => { }; process.nextTick(() => { fakeFs.readPromise(p, buffer, ...args).then(bytesRead => { callback(null, bytesRead, buffer); }, error => { // https://github.com/nodejs/node/blob/1317252dfe8824fd9cfee125d2aaa94004db2f3b/lib/fs.js#L655-L658 // Known issue: bytesRead could theoretically be > than 0, but we currently always return 0 callback(error, 0, buffer); }); }); }); for (const fnName of ASYNC_IMPLEMENTATIONS) { const origName = fnName.replace(/Promise$/, ``); if (typeof patchedFs[origName] === `undefined`) continue; const fakeImpl = fakeFs[fnName]; if (typeof fakeImpl === `undefined`) continue; const wrapper = (...args) => { const hasCallback = typeof args[args.length - 1] === `function`; const callback = hasCallback ? args.pop() : () => { }; process.nextTick(() => { fakeImpl.apply(fakeFs, args).then((result) => { callback(null, result); }, (error) => { callback(error); }); }); }; setupFn(patchedFs, origName, wrapper); } patchedFs.realpath.native = patchedFs.realpath; } /** Sync implementations */ { setupFn(patchedFs, `existsSync`, (p) => { try { return fakeFs.existsSync(p); } catch (error) { return false; } }); for (const fnName of SYNC_IMPLEMENTATIONS) { const origName = fnName; if (typeof patchedFs[origName] === `undefined`) continue; const fakeImpl = fakeFs[fnName]; if (typeof fakeImpl === `undefined`) continue; setupFn(patchedFs, origName, fakeImpl.bind(fakeFs)); } patchedFs.realpathSync.native = patchedFs.realpathSync; } /** Promise implementations */ { // `fs.promises` is a getter that returns a reference to require(`fs/promises`), // so we can just patch `fs.promises` and both will be updated const origEmitWarning = process.emitWarning; process.emitWarning = () => { }; let patchedFsPromises; try { patchedFsPromises = patchedFs.promises; } finally { process.emitWarning = origEmitWarning; } if (typeof patchedFsPromises !== `undefined`) { // `fs.promises.exists` doesn't exist for (const fnName of ASYNC_IMPLEMENTATIONS) { const origName = fnName.replace(/Promise$/, ``); if (typeof patchedFsPromises[origName] === `undefined`) continue; const fakeImpl = fakeFs[fnName]; if (typeof fakeImpl === `undefined`) continue; // Open is a bit particular with fs.promises: it returns a file handle // instance instead of the traditional file descriptor number if (fnName === `open`) continue; setupFn(patchedFsPromises, origName, fakeImpl.bind(fakeFs)); } class FileHandle { constructor(fd) { this.fd = fd; } } for (const fnName of FILEHANDLE_IMPLEMENTATIONS) { const origName = fnName.replace(/Promise$/, ``); const fakeImpl = fakeFs[fnName]; if (typeof fakeImpl === `undefined`) continue; setupFn(FileHandle.prototype, origName, function (...args) { return fakeImpl.call(fakeFs, this.fd, ...args); }); } setupFn(patchedFsPromises, `open`, async (...args) => { // @ts-expect-error const fd = await fakeFs.openPromise(...args); return new FileHandle(fd); }); // `fs.promises.realpath` doesn't have a `native` property } } /** util.promisify implementations */ { // Override the promisified version of `fs.read` to return an object as per // https://github.com/nodejs/node/blob/dc79f3f37caf6f25b8efee4623bec31e2c20f595/lib/fs.js#L559-L560 // and // https://github.com/nodejs/node/blob/ba684805b6c0eded76e5cd89ee00328ac7a59365/lib/internal/util.js#L293 // @ts-expect-error patchedFs.read[util_1.promisify.custom] = async (p, buffer, ...args) => { const res = fakeFs.readPromise(p, buffer, ...args); return { bytesRead: await res, buffer }; }; } } exports.patchFs = patchFs; function extendFs(realFs, fakeFs) { const patchedFs = Object.create(realFs); patchFs(patchedFs, fakeFs); return patchedFs; } exports.extendFs = extendFs; /***/ }), /***/ 7194: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toFilename = exports.convertPath = exports.ppath = exports.npath = exports.Filename = exports.PortablePath = void 0; const tslib_1 = __webpack_require__(70655); const path_1 = tslib_1.__importDefault(__webpack_require__(71017)); var PathType; (function (PathType) { PathType[PathType["File"] = 0] = "File"; PathType[PathType["Portable"] = 1] = "Portable"; PathType[PathType["Native"] = 2] = "Native"; })(PathType || (PathType = {})); exports.PortablePath = { root: `/`, dot: `.`, }; exports.Filename = { nodeModules: `node_modules`, manifest: `package.json`, lockfile: `yarn.lock`, virtual: `__virtual__`, /** * @deprecated */ pnpJs: `.pnp.js`, pnpCjs: `.pnp.cjs`, rc: `.yarnrc.yml`, }; exports.npath = Object.create(path_1.default); exports.ppath = Object.create(path_1.default.posix); exports.npath.cwd = () => process.cwd(); exports.ppath.cwd = () => toPortablePath(process.cwd()); exports.ppath.resolve = (...segments) => { if (segments.length > 0 && exports.ppath.isAbsolute(segments[0])) { return path_1.default.posix.resolve(...segments); } else { return path_1.default.posix.resolve(exports.ppath.cwd(), ...segments); } }; const contains = function (pathUtils, from, to) { from = pathUtils.normalize(from); to = pathUtils.normalize(to); if (from === to) return `.`; if (!from.endsWith(pathUtils.sep)) from = (from + pathUtils.sep); if (to.startsWith(from)) { return to.slice(from.length); } else { return null; } }; exports.npath.fromPortablePath = fromPortablePath; exports.npath.toPortablePath = toPortablePath; exports.npath.contains = (from, to) => contains(exports.npath, from, to); exports.ppath.contains = (from, to) => contains(exports.ppath, from, to); const WINDOWS_PATH_REGEXP = /^([a-zA-Z]:.*)$/; const UNC_WINDOWS_PATH_REGEXP = /^\\\\(\.\\)?(.*)$/; const PORTABLE_PATH_REGEXP = /^\/([a-zA-Z]:.*)$/; const UNC_PORTABLE_PATH_REGEXP = /^\/unc\/(\.dot\/)?(.*)$/; // Path should look like "/N:/berry/scripts/plugin-pack.js" // And transform to "N:\berry\scripts\plugin-pack.js" function fromPortablePath(p) { if (process.platform !== `win32`) return p; if (p.match(PORTABLE_PATH_REGEXP)) p = p.replace(PORTABLE_PATH_REGEXP, `$1`); else if (p.match(UNC_PORTABLE_PATH_REGEXP)) p = p.replace(UNC_PORTABLE_PATH_REGEXP, (match, p1, p2) => `\\\\${p1 ? `.\\` : ``}${p2}`); else return p; return p.replace(/\//g, `\\`); } // Path should look like "N:/berry/scripts/plugin-pack.js" // And transform to "/N:/berry/scripts/plugin-pack.js" function toPortablePath(p) { if (process.platform !== `win32`) return p; if (p.match(WINDOWS_PATH_REGEXP)) p = p.replace(WINDOWS_PATH_REGEXP, `/$1`); else if (p.match(UNC_WINDOWS_PATH_REGEXP)) p = p.replace(UNC_WINDOWS_PATH_REGEXP, (match, p1, p2) => `/unc/${p1 ? `.dot/` : ``}${p2}`); return p.replace(/\\/g, `/`); } function convertPath(targetPathUtils, sourcePath) { return (targetPathUtils === exports.npath ? fromPortablePath(sourcePath) : toPortablePath(sourcePath)); } exports.convertPath = convertPath; function toFilename(filename) { if (exports.npath.parse(filename).dir !== `` || exports.ppath.parse(filename).dir !== ``) throw new Error(`Invalid filename: "${filename}"`); return filename; } exports.toFilename = toFilename; /***/ }), /***/ 62576: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.areStatsEqual = exports.convertToBigIntStats = exports.clearStats = exports.makeEmptyStats = exports.makeDefaultStats = exports.BigIntStatsEntry = exports.StatEntry = exports.DirEntry = void 0; const tslib_1 = __webpack_require__(70655); const nodeUtils = tslib_1.__importStar(__webpack_require__(73837)); const constants_1 = __webpack_require__(92775); class DirEntry { constructor() { this.name = ``; this.mode = 0; } isBlockDevice() { return false; } isCharacterDevice() { return false; } isDirectory() { return (this.mode & constants_1.S_IFMT) === constants_1.S_IFDIR; } isFIFO() { return false; } isFile() { return (this.mode & constants_1.S_IFMT) === constants_1.S_IFREG; } isSocket() { return false; } isSymbolicLink() { return (this.mode & constants_1.S_IFMT) === constants_1.S_IFLNK; } } exports.DirEntry = DirEntry; class StatEntry { constructor() { this.uid = 0; this.gid = 0; this.size = 0; this.blksize = 0; this.atimeMs = 0; this.mtimeMs = 0; this.ctimeMs = 0; this.birthtimeMs = 0; this.atime = new Date(0); this.mtime = new Date(0); this.ctime = new Date(0); this.birthtime = new Date(0); this.dev = 0; this.ino = 0; this.mode = constants_1.S_IFREG | 0o644; this.nlink = 1; this.rdev = 0; this.blocks = 1; } isBlockDevice() { return false; } isCharacterDevice() { return false; } isDirectory() { return (this.mode & constants_1.S_IFMT) === constants_1.S_IFDIR; } isFIFO() { return false; } isFile() { return (this.mode & constants_1.S_IFMT) === constants_1.S_IFREG; } isSocket() { return false; } isSymbolicLink() { return (this.mode & constants_1.S_IFMT) === constants_1.S_IFLNK; } } exports.StatEntry = StatEntry; class BigIntStatsEntry { constructor() { this.uid = BigInt(0); this.gid = BigInt(0); this.size = BigInt(0); this.blksize = BigInt(0); this.atimeMs = BigInt(0); this.mtimeMs = BigInt(0); this.ctimeMs = BigInt(0); this.birthtimeMs = BigInt(0); this.atimeNs = BigInt(0); this.mtimeNs = BigInt(0); this.ctimeNs = BigInt(0); this.birthtimeNs = BigInt(0); this.atime = new Date(0); this.mtime = new Date(0); this.ctime = new Date(0); this.birthtime = new Date(0); this.dev = BigInt(0); this.ino = BigInt(0); this.mode = BigInt(constants_1.S_IFREG | 0o644); this.nlink = BigInt(1); this.rdev = BigInt(0); this.blocks = BigInt(1); } isBlockDevice() { return false; } isCharacterDevice() { return false; } isDirectory() { return (this.mode & BigInt(constants_1.S_IFMT)) === BigInt(constants_1.S_IFDIR); } isFIFO() { return false; } isFile() { return (this.mode & BigInt(constants_1.S_IFMT)) === BigInt(constants_1.S_IFREG); } isSocket() { return false; } isSymbolicLink() { return (this.mode & BigInt(constants_1.S_IFMT)) === BigInt(constants_1.S_IFLNK); } } exports.BigIntStatsEntry = BigIntStatsEntry; function makeDefaultStats() { return new StatEntry(); } exports.makeDefaultStats = makeDefaultStats; function makeEmptyStats() { return clearStats(makeDefaultStats()); } exports.makeEmptyStats = makeEmptyStats; /** * Mutates the provided stats object to zero it out then returns it for convenience */ function clearStats(stats) { for (const key in stats) { if (Object.prototype.hasOwnProperty.call(stats, key)) { const element = stats[key]; if (typeof element === `number`) { // @ts-expect-error Typescript can't tell that stats[key] is a number stats[key] = 0; } else if (typeof element === `bigint`) { // @ts-expect-error Typescript can't tell that stats[key] is a bigint stats[key] = BigInt(0); } else if (nodeUtils.types.isDate(element)) { // @ts-expect-error Typescript can't tell that stats[key] is a bigint stats[key] = new Date(0); } } } return stats; } exports.clearStats = clearStats; function convertToBigIntStats(stats) { const bigintStats = new BigIntStatsEntry(); for (const key in stats) { if (Object.prototype.hasOwnProperty.call(stats, key)) { const element = stats[key]; if (typeof element === `number`) { // @ts-expect-error Typescript isn't able to tell this is valid bigintStats[key] = BigInt(element); } else if (nodeUtils.types.isDate(element)) { // @ts-expect-error Typescript isn't able to tell this is valid bigintStats[key] = new Date(element); } } } bigintStats.atimeNs = bigintStats.atimeMs * BigInt(1e6); bigintStats.mtimeNs = bigintStats.mtimeMs * BigInt(1e6); bigintStats.ctimeNs = bigintStats.ctimeMs * BigInt(1e6); bigintStats.birthtimeNs = bigintStats.birthtimeMs * BigInt(1e6); return bigintStats; } exports.convertToBigIntStats = convertToBigIntStats; function areStatsEqual(a, b) { if (a.atimeMs !== b.atimeMs) return false; if (a.birthtimeMs !== b.birthtimeMs) return false; if (a.blksize !== b.blksize) return false; if (a.blocks !== b.blocks) return false; if (a.ctimeMs !== b.ctimeMs) return false; if (a.dev !== b.dev) return false; if (a.gid !== b.gid) return false; if (a.ino !== b.ino) return false; if (a.isBlockDevice() !== b.isBlockDevice()) return false; if (a.isCharacterDevice() !== b.isCharacterDevice()) return false; if (a.isDirectory() !== b.isDirectory()) return false; if (a.isFIFO() !== b.isFIFO()) return false; if (a.isFile() !== b.isFile()) return false; if (a.isSocket() !== b.isSocket()) return false; if (a.isSymbolicLink() !== b.isSymbolicLink()) return false; if (a.mode !== b.mode) return false; if (a.mtimeMs !== b.mtimeMs) return false; if (a.nlink !== b.nlink) return false; if (a.rdev !== b.rdev) return false; if (a.size !== b.size) return false; if (a.uid !== b.uid) return false; const aN = a; const bN = b; if (aN.atimeNs !== bN.atimeNs) return false; if (aN.mtimeNs !== bN.mtimeNs) return false; if (aN.ctimeNs !== bN.ctimeNs) return false; if (aN.birthtimeNs !== bN.birthtimeNs) return false; return true; } exports.areStatsEqual = areStatsEqual; /***/ }), /***/ 34513: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.xfs = void 0; const tslib_1 = __webpack_require__(70655); const os_1 = tslib_1.__importDefault(__webpack_require__(22037)); const NodeFS_1 = __webpack_require__(78633); const path_1 = __webpack_require__(7194); function getTempName(prefix) { const tmpdir = path_1.npath.toPortablePath(os_1.default.tmpdir()); const hash = Math.ceil(Math.random() * 0x100000000).toString(16).padStart(8, `0`); return path_1.ppath.join(tmpdir, `${prefix}${hash}`); } const tmpdirs = new Set(); let cleanExitRegistered = false; function registerCleanExit() { if (cleanExitRegistered) return; cleanExitRegistered = true; process.once(`exit`, () => { exports.xfs.rmtempSync(); }); } exports.xfs = Object.assign(new NodeFS_1.NodeFS(), { detachTemp(p) { tmpdirs.delete(p); }, mktempSync(cb) { registerCleanExit(); while (true) { const p = getTempName(`xfs-`); try { this.mkdirSync(p); } catch (error) { if (error.code === `EEXIST`) { continue; } else { throw error; } } const realP = this.realpathSync(p); tmpdirs.add(realP); if (typeof cb !== `undefined`) { try { return cb(realP); } finally { if (tmpdirs.has(realP)) { tmpdirs.delete(realP); try { this.removeSync(realP); } catch (_a) { // Too bad if there's an error } } } } else { return realP; } } }, async mktempPromise(cb) { registerCleanExit(); while (true) { const p = getTempName(`xfs-`); try { await this.mkdirPromise(p); } catch (error) { if (error.code === `EEXIST`) { continue; } else { throw error; } } const realP = await this.realpathPromise(p); tmpdirs.add(realP); if (typeof cb !== `undefined`) { try { return await cb(realP); } finally { if (tmpdirs.has(realP)) { tmpdirs.delete(realP); try { await this.removePromise(realP); } catch (_a) { // Too bad if there's an error } } } } else { return realP; } } }, async rmtempPromise() { await Promise.all(Array.from(tmpdirs.values()).map(async (p) => { try { await exports.xfs.removePromise(p, { maxRetries: 0 }); tmpdirs.delete(p); } catch (_a) { // Too bad if there's an error } })); }, rmtempSync() { for (const p of tmpdirs) { try { exports.xfs.removeSync(p); tmpdirs.delete(p); } catch (_a) { // Too bad if there's an error } } }, }); /***/ }), /***/ 7861: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var frozenFs = Object.assign({}, __webpack_require__(57147)); var Module = typeof Module !== "undefined" ? Module : {}; var moduleOverrides = {}; var key; for (key in Module) { if (Module.hasOwnProperty(key)) { moduleOverrides[key] = Module[key]; } } var arguments_ = []; var thisProgram = "./this.program"; var quit_ = function(status, toThrow) { throw toThrow; }; var ENVIRONMENT_IS_WORKER = false; var ENVIRONMENT_IS_NODE = true; var scriptDirectory = ""; function locateFile(path) { if (Module["locateFile"]) { return Module["locateFile"](path, scriptDirectory); } return scriptDirectory + path; } var read_, readBinary; var nodeFS; var nodePath; if (ENVIRONMENT_IS_NODE) { if (ENVIRONMENT_IS_WORKER) { scriptDirectory = __webpack_require__(71017).dirname(scriptDirectory) + "/"; } else { scriptDirectory = __dirname + "/"; } read_ = function shell_read(filename, binary) { var ret = tryParseAsDataURI(filename); if (ret) { return binary ? ret : ret.toString(); } if (!nodeFS) nodeFS = frozenFs; if (!nodePath) nodePath = __webpack_require__(71017); filename = nodePath["normalize"](filename); return nodeFS["readFileSync"](filename, binary ? null : "utf8"); }; readBinary = function readBinary(filename) { var ret = read_(filename, true); if (!ret.buffer) { ret = new Uint8Array(ret); } assert(ret.buffer); return ret; }; if (process["argv"].length > 1) { thisProgram = process["argv"][1].replace(/\\/g, "/"); } arguments_ = process["argv"].slice(2); if (true) { module["exports"] = Module; } quit_ = function(status) { process["exit"](status); }; Module["inspect"] = function() { return "[Emscripten Module object]"; }; } else { } var out = Module["print"] || console.log.bind(console); var err = Module["printErr"] || console.warn.bind(console); for (key in moduleOverrides) { if (moduleOverrides.hasOwnProperty(key)) { Module[key] = moduleOverrides[key]; } } moduleOverrides = null; if (Module["arguments"]) arguments_ = Module["arguments"]; if (Module["thisProgram"]) thisProgram = Module["thisProgram"]; if (Module["quit"]) quit_ = Module["quit"]; var STACK_ALIGN = 16; function alignMemory(size, factor) { if (!factor) factor = STACK_ALIGN; return Math.ceil(size / factor) * factor; } var tempRet0 = 0; var setTempRet0 = function(value) { tempRet0 = value; }; var wasmBinary; if (Module["wasmBinary"]) wasmBinary = Module["wasmBinary"]; var noExitRuntime = Module["noExitRuntime"] || true; if (typeof WebAssembly !== "object") { abort("no native wasm support detected"); } function getValue(ptr, type, noSafe) { type = type || "i8"; if (type.charAt(type.length - 1) === "*") type = "i32"; 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]; default: abort("invalid type for getValue: " + type); } return null; } var wasmMemory; var ABORT = false; var EXITSTATUS; function assert(condition, text) { if (!condition) { abort("Assertion failed: " + text); } } function getCFunc(ident) { var func = Module["_" + ident]; assert( func, "Cannot call unknown function " + ident + ", make sure it is exported" ); return func; } function ccall(ident, returnType, argTypes, args, opts) { var toC = { string: function(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: function(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; i < args.length; i++) { var converter = toC[argTypes[i]]; if (converter) { if (stack === 0) stack = stackSave(); cArgs[i] = converter(args[i]); } else { cArgs[i] = args[i]; } } } var ret = func.apply(null, cArgs); ret = convertReturnValue(ret); if (stack !== 0) stackRestore(stack); return ret; } function cwrap(ident, returnType, argTypes, opts) { argTypes = argTypes || []; var numericArgs = argTypes.every(function(type) { return type === "number"; }); var numericRet = returnType !== "string"; if (numericRet && numericArgs && !opts) { return getCFunc(ident); } return function() { return ccall(ident, returnType, argTypes, arguments, opts); }; } var UTF8Decoder = typeof TextDecoder !== "undefined" ? new TextDecoder("utf8") : undefined; function UTF8ArrayToString(heap, idx, maxBytesToRead) { var endIdx = idx + maxBytesToRead; var endPtr = idx; while (heap[endPtr] && !(endPtr >= endIdx)) ++endPtr; if (endPtr - idx > 16 && heap.subarray && UTF8Decoder) { return UTF8Decoder.decode(heap.subarray(idx, endPtr)); } else { var str = ""; while (idx < endPtr) { var u0 = heap[idx++]; if (!(u0 & 128)) { str += String.fromCharCode(u0); continue; } var u1 = heap[idx++] & 63; if ((u0 & 224) == 192) { str += String.fromCharCode(((u0 & 31) << 6) | u1); continue; } var u2 = heap[idx++] & 63; if ((u0 & 240) == 224) { u0 = ((u0 & 15) << 12) | (u1 << 6) | u2; } else { u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (heap[idx++] & 63); } if (u0 < 65536) { str += String.fromCharCode(u0); } else { var ch = u0 - 65536; str += String.fromCharCode(55296 | (ch >> 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 < str.length; ++i) { var u = str.charCodeAt(i); if (u >= 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 < str.length; ++i) { var u = str.charCodeAt(i); if (u >= 55296 && u <= 57343) u = (65536 + ((u & 1023) << 10)) | (str.charCodeAt(++i) & 1023); if (u <= 127) ++len; else if (u <= 2047) len += 2; else if (u <= 65535) len += 3; else len += 4; } return len; } function allocateUTF8(str) { var size = lengthBytesUTF8(str) + 1; var ret = _malloc(size); if (ret) stringToUTF8Array(str, HEAP8, ret, size); return ret; } function writeArrayToMemory(array, buffer) { HEAP8.set(array, buffer); } function alignUp(x, multiple) { if (x % multiple > 0) { x += multiple - (x % multiple); } return x; } 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"] || 16777216; var wasmTable; var __ATPRERUN__ = []; var __ATINIT__ = []; var __ATPOSTRUN__ = []; var runtimeInitialized = false; 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; if (!Module["noFSInit"] && !FS.init.initialized) FS.init(); TTY.init(); callRuntimeCallbacks(__ATINIT__); } 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(); } } } Module["preloadedImages"] = {}; Module["preloadedAudios"] = {}; function abort(what) { if (Module["onAbort"]) { Module["onAbort"](what); } what += ""; err(what); ABORT = true; EXITSTATUS = 1; what = "abort(" + what + "). Build with -s ASSERTIONS=1 for more info."; var e = new WebAssembly.RuntimeError(what); throw e; } var dataURIPrefix = "data:application/octet-stream;base64,"; function isDataURI(filename) { return filename.startsWith(dataURIPrefix); } var wasmBinaryFile = "data:application/octet-stream;base64,AGFzbQEAAAABlAInYAF/AX9gA39/fwF/YAF/AGACf38Bf2ACf38AYAV/f39/fwF/YAR/f39/AX9gA39/fwBgBH9+f38Bf2AAAX9gBX9/f35/AX5gA39+fwF/YAF/AX5gAn9+AX9gBH9/fn8BfmADf35/AX5gA39/fgF/YAR/f35/AX9gBn9/f39/fwF/YAR/f39/AGADf39+AX5gAn5/AX9gA398fwBgBH9/f38BfmADf39/AX5gBn98f39/fwF/YAV/f35/fwF/YAV/fn9/fwF/YAV/f39/fwBgAn9+AGACf38BfmACf3wAYAh/fn5/f39+fwF/YAV/f39+fwBgAABgBX5+f35/AX5gAnx/AXxgAn9+AX5gBX9/f39/AX4CeRQBYQFhAAIBYQFiAAABYQFjAAMBYQFkAAYBYQFlAAEBYQFmAAABYQFnAAYBYQFoAAABYQFpAAMBYQFqAAMBYQFrAAMBYQFsAAMBYQFtAAABYQFuAAUBYQFvAAEBYQFwAAMBYQFxAAEBYQFyAAABYQFzAAEBYQF0AAADggKAAgcCAgQAAQECAgANBAQOBwICAhwLEw0AAA0dFAwMAAcCDBAeAgMCAwIAAgEABwgUBBUIBgADAAwABAgIAgEGBgABAB8XAQEDAhMCAwUFEQICIA8GAgMYAQgCAQAABwUBGAAaAxIBAAcEAyERCCIHAQsVAQMABQMDAwAFBAACIwYAAQEAGw0bFw0BBAALCwMDDAwAAwAHJAMBBAgaAQECBQMBAwMABwcHAgICAiURCwgICwEmCQkAAAAKAAIABQAGBgUFBQEDBgYGBRISBgQBAQEAAAIJBgABAA4AAQEPCQABBBkJCQkAAAADCgoBAQIQAAAAAgEDAwkEAQoABQ4AAAkEBQFwAR8fBQcBAYACgIACBgkBfwFB0KDBAgsHvgI8AXUCAAF2AIABAXcAkwIBeADxAQF5AM8BAXoAzQEBQQDLAQFCAMoBAUMAyQEBRADIAQFFAMcBAUYAkgIBRwCRAgFIAI4CAUkA6QEBSgDiAQFLAOEBAUwAPQFNAOABAU4A+gEBTwD5AQFQAPIBAVEA+wEBUgDfAQFTAN4BAVQA3QEBVQDcAQFWAOMBAVcA2wEBWADaAQFZANkBAVoA2AEBXwDXAQEkAOoBAmFhAJwBAmJhANYBAmNhANUBAmRhANQBAmVhADECZmEA6wECZ2EAGwJoYQDOAQJpYQBJAmphANMBAmthANIBAmxhAGgCbWEA0QECbmEA6AECb2EA0AECcGEA5AECcWEAigICcmEA+AECc2EA9wECdGEA9gECdWEA5wECdmEA5gECd2EA5QECeGEAGAJ5YQAVAnphAQAJQQEAQQELHswBkAKNAo8CjAKLArYBiQKIAocChgKFAoQCgwKCAoECgAL/Af4B/QH8AVr1AfQB8wHwAe8B7gHtAewBCq2RCYACQAEBfyMAQRBrIgMgADYCDCADIAE2AgggAyACNgIEIAMoAgwEQCADKAIMIAMoAgg2AgAgAygCDCADKAIENgIECwvMDAEHfwJAIABFDQAgAEEIayIDIABBBGsoAgAiAUF4cSIAaiEFAkAgAUEBcQ0AIAFBA3FFDQEgAyADKAIAIgFrIgNByJsBKAIASQ0BIAAgAWohACADQcybASgCAEcEQCABQf8BTQRAIAMoAggiAiABQQN2IgRBA3RB4JsBakYaIAIgAygCDCIBRgRAQbibAUG4mwEoAgBBfiAEd3E2AgAMAwsgAiABNgIMIAEgAjYCCAwCCyADKAIYIQYCQCADIAMoAgwiAUcEQCADKAIIIgIgATYCDCABIAI2AggMAQsCQCADQRRqIgIoAgAiBA0AIANBEGoiAigCACIEDQBBACEBDAELA0AgAiEHIAQiAUEUaiICKAIAIgQNACABQRBqIQIgASgCECIEDQALIAdBADYCAAsgBkUNAQJAIAMgAygCHCICQQJ0QeidAWoiBCgCAEYEQCAEIAE2AgAgAQ0BQbybAUG8mwEoAgBBfiACd3E2AgAMAwsgBkEQQRQgBigCECADRhtqIAE2AgAgAUUNAgsgASAGNgIYIAMoAhAiAgRAIAEgAjYCECACIAE2AhgLIAMoAhQiAkUNASABIAI2AhQgAiABNgIYDAELIAUoAgQiAUEDcUEDRw0AQcCbASAANgIAIAUgAUF+cTYCBCADIABBAXI2AgQgACADaiAANgIADwsgAyAFTw0AIAUoAgQiAUEBcUUNAAJAIAFBAnFFBEAgBUHQmwEoAgBGBEBB0JsBIAM2AgBBxJsBQcSbASgCACAAaiIANgIAIAMgAEEBcjYCBCADQcybASgCAEcNA0HAmwFBADYCAEHMmwFBADYCAA8LIAVBzJsBKAIARgRAQcybASADNgIAQcCbAUHAmwEoAgAgAGoiADYCACADIABBAXI2AgQgACADaiAANgIADwsgAUF4cSAAaiEAAkAgAUH/AU0EQCAFKAIIIgIgAUEDdiIEQQN0QeCbAWpGGiACIAUoAgwiAUYEQEG4mwFBuJsBKAIAQX4gBHdxNgIADAILIAIgATYCDCABIAI2AggMAQsgBSgCGCEGAkAgBSAFKAIMIgFHBEAgBSgCCCICQcibASgCAEkaIAIgATYCDCABIAI2AggMAQsCQCAFQRRqIgIoAgAiBA0AIAVBEGoiAigCACIEDQBBACEBDAELA0AgAiEHIAQiAUEUaiICKAIAIgQNACABQRBqIQIgASgCECIEDQALIAdBADYCAAsgBkUNAAJAIAUgBSgCHCICQQJ0QeidAWoiBCgCAEYEQCAEIAE2AgAgAQ0BQbybAUG8mwEoAgBBfiACd3E2AgAMAgsgBkEQQRQgBigCECAFRhtqIAE2AgAgAUUNAQsgASAGNgIYIAUoAhAiAgRAIAEgAjYCECACIAE2AhgLIAUoAhQiAkUNACABIAI2AhQgAiABNgIYCyADIABBAXI2AgQgACADaiAANgIAIANBzJsBKAIARw0BQcCbASAANgIADwsgBSABQX5xNgIEIAMgAEEBcjYCBCAAIANqIAA2AgALIABB/wFNBEAgAEEDdiIBQQN0QeCbAWohAAJ/QbibASgCACICQQEgAXQiAXFFBEBBuJsBIAEgAnI2AgAgAAwBCyAAKAIICyECIAAgAzYCCCACIAM2AgwgAyAANgIMIAMgAjYCCA8LQR8hAiADQgA3AhAgAEH///8HTQRAIABBCHYiASABQYD+P2pBEHZBCHEiAXQiAiACQYDgH2pBEHZBBHEiAnQiBCAEQYCAD2pBEHZBAnEiBHRBD3YgASACciAEcmsiAUEBdCAAIAFBFWp2QQFxckEcaiECCyADIAI2AhwgAkECdEHonQFqIQECQAJAAkBBvJsBKAIAIgRBASACdCIHcUUEQEG8mwEgBCAHcjYCACABIAM2AgAgAyABNgIYDAELIABBAEEZIAJBAXZrIAJBH0YbdCECIAEoAgAhAQNAIAEiBCgCBEF4cSAARg0CIAJBHXYhASACQQF0IQIgBCABQQRxaiIHQRBqKAIAIgENAAsgByADNgIQIAMgBDYCGAsgAyADNgIMIAMgAzYCCAwBCyAEKAIIIgAgAzYCDCAEIAM2AgggA0EANgIYIAMgBDYCDCADIAA2AggLQdibAUHYmwEoAgBBAWsiAEF/IAAbNgIACwtCAQF/IwBBEGsiASQAIAEgADYCDCABKAIMBEAgASgCDC0AAUEBcQRAIAEoAgwoAgQQFQsgASgCDBAVCyABQRBqJAALQwEBfyMAQRBrIgIkACACIAA2AgwgAiABNgIIIAIoAgwCfyMAQRBrIgAgAigCCDYCDCAAKAIMQQxqCxBDIAJBEGokAAuiLgEMfyMAQRBrIgwkAAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAAQfQBTQRAQbibASgCACIFQRAgAEELakF4cSAAQQtJGyIIQQN2IgJ2IgFBA3EEQCABQX9zQQFxIAJqIgNBA3QiAUHomwFqKAIAIgRBCGohAAJAIAQoAggiAiABQeCbAWoiAUYEQEG4mwEgBUF+IAN3cTYCAAwBCyACIAE2AgwgASACNgIICyAEIANBA3QiAUEDcjYCBCABIARqIgEgASgCBEEBcjYCBAwNCyAIQcCbASgCACIKTQ0BIAEEQAJAQQIgAnQiAEEAIABrciABIAJ0cSIAQQAgAGtxQQFrIgAgAEEMdkEQcSICdiIBQQV2QQhxIgAgAnIgASAAdiIBQQJ2QQRxIgByIAEgAHYiAUEBdkECcSIAciABIAB2IgFBAXZBAXEiAHIgASAAdmoiA0EDdCIAQeibAWooAgAiBCgCCCIBIABB4JsBaiIARgRAQbibASAFQX4gA3dxIgU2AgAMAQsgASAANgIMIAAgATYCCAsgBEEIaiEAIAQgCEEDcjYCBCAEIAhqIgIgA0EDdCIBIAhrIgNBAXI2AgQgASAEaiADNgIAIAoEQCAKQQN2IgFBA3RB4JsBaiEHQcybASgCACEEAn8gBUEBIAF0IgFxRQRAQbibASABIAVyNgIAIAcMAQsgBygCCAshASAHIAQ2AgggASAENgIMIAQgBzYCDCAEIAE2AggLQcybASACNgIAQcCbASADNgIADA0LQbybASgCACIGRQ0BIAZBACAGa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2akECdEHonQFqKAIAIgEoAgRBeHEgCGshAyABIQIDQAJAIAIoAhAiAEUEQCACKAIUIgBFDQELIAAoAgRBeHEgCGsiAiADIAIgA0kiAhshAyAAIAEgAhshASAAIQIMAQsLIAEgCGoiCSABTQ0CIAEoAhghCyABIAEoAgwiBEcEQCABKAIIIgBByJsBKAIASRogACAENgIMIAQgADYCCAwMCyABQRRqIgIoAgAiAEUEQCABKAIQIgBFDQQgAUEQaiECCwNAIAIhByAAIgRBFGoiAigCACIADQAgBEEQaiECIAQoAhAiAA0ACyAHQQA2AgAMCwtBfyEIIABBv39LDQAgAEELaiIAQXhxIQhBvJsBKAIAIglFDQBBACAIayEDAkACQAJAAn9BACAIQYACSQ0AGkEfIAhB////B0sNABogAEEIdiIAIABBgP4/akEQdkEIcSICdCIAIABBgOAfakEQdkEEcSIBdCIAIABBgIAPakEQdkECcSIAdEEPdiABIAJyIAByayIAQQF0IAggAEEVanZBAXFyQRxqCyIFQQJ0QeidAWooAgAiAkUEQEEAIQAMAQtBACEAIAhBAEEZIAVBAXZrIAVBH0YbdCEBA0ACQCACKAIEQXhxIAhrIgcgA08NACACIQQgByIDDQBBACEDIAIhAAwDCyAAIAIoAhQiByAHIAIgAUEddkEEcWooAhAiAkYbIAAgBxshACABQQF0IQEgAg0ACwsgACAEckUEQEECIAV0IgBBACAAa3IgCXEiAEUNAyAAQQAgAGtxQQFrIgAgAEEMdkEQcSICdiIBQQV2QQhxIgAgAnIgASAAdiIBQQJ2QQRxIgByIAEgAHYiAUEBdkECcSIAciABIAB2IgFBAXZBAXEiAHIgASAAdmpBAnRB6J0BaigCACEACyAARQ0BCwNAIAAoAgRBeHEgCGsiASADSSECIAEgAyACGyEDIAAgBCACGyEEIAAoAhAiAQR/IAEFIAAoAhQLIgANAAsLIARFDQAgA0HAmwEoAgAgCGtPDQAgBCAIaiIGIARNDQEgBCgCGCEFIAQgBCgCDCIBRwRAIAQoAggiAEHImwEoAgBJGiAAIAE2AgwgASAANgIIDAoLIARBFGoiAigCACIARQRAIAQoAhAiAEUNBCAEQRBqIQILA0AgAiEHIAAiAUEUaiICKAIAIgANACABQRBqIQIgASgCECIADQALIAdBADYCAAwJCyAIQcCbASgCACICTQRAQcybASgCACEDAkAgAiAIayIBQRBPBEBBwJsBIAE2AgBBzJsBIAMgCGoiADYCACAAIAFBAXI2AgQgAiADaiABNgIAIAMgCEEDcjYCBAwBC0HMmwFBADYCAEHAmwFBADYCACADIAJBA3I2AgQgAiADaiIAIAAoAgRBAXI2AgQLIANBCGohAAwLCyAIQcSbASgCACIGSQRAQcSbASAGIAhrIgE2AgBB0JsBQdCbASgCACICIAhqIgA2AgAgACABQQFyNgIEIAIgCEEDcjYCBCACQQhqIQAMCwtBACEAIAhBL2oiCQJ/QZCfASgCAARAQZifASgCAAwBC0GcnwFCfzcCAEGUnwFCgKCAgICABDcCAEGQnwEgDEEMakFwcUHYqtWqBXM2AgBBpJ8BQQA2AgBB9J4BQQA2AgBBgCALIgFqIgVBACABayIHcSICIAhNDQpB8J4BKAIAIgQEQEHongEoAgAiAyACaiIBIANNDQsgASAESw0LC0H0ngEtAABBBHENBQJAAkBB0JsBKAIAIgMEQEH4ngEhAANAIAMgACgCACIBTwRAIAEgACgCBGogA0sNAwsgACgCCCIADQALC0EAEDwiAUF/Rg0GIAIhBUGUnwEoAgAiA0EBayIAIAFxBEAgAiABayAAIAFqQQAgA2txaiEFCyAFIAhNDQYgBUH+////B0sNBkHwngEoAgAiBARAQeieASgCACIDIAVqIgAgA00NByAAIARLDQcLIAUQPCIAIAFHDQEMCAsgBSAGayAHcSIFQf7///8HSw0FIAUQPCIBIAAoAgAgACgCBGpGDQQgASEACwJAIABBf0YNACAIQTBqIAVNDQBBmJ8BKAIAIgEgCSAFa2pBACABa3EiAUH+////B0sEQCAAIQEMCAsgARA8QX9HBEAgASAFaiEFIAAhAQwIC0EAIAVrEDwaDAULIAAiAUF/Rw0GDAQLAAtBACEEDAcLQQAhAQwFCyABQX9HDQILQfSeAUH0ngEoAgBBBHI2AgALIAJB/v///wdLDQEgAhA8IQFBABA8IQAgAUF/Rg0BIABBf0YNASAAIAFNDQEgACABayIFIAhBKGpNDQELQeieAUHongEoAgAgBWoiADYCAEHsngEoAgAgAEkEQEHsngEgADYCAAsCQAJAAkBB0JsBKAIAIgcEQEH4ngEhAANAIAEgACgCACIDIAAoAgQiAmpGDQIgACgCCCIADQALDAILQcibASgCACIAQQAgACABTRtFBEBByJsBIAE2AgALQQAhAEH8ngEgBTYCAEH4ngEgATYCAEHYmwFBfzYCAEHcmwFBkJ8BKAIANgIAQYSfAUEANgIAA0AgAEEDdCIDQeibAWogA0HgmwFqIgI2AgAgA0HsmwFqIAI2AgAgAEEBaiIAQSBHDQALQcSbASAFQShrIgNBeCABa0EHcUEAIAFBCGpBB3EbIgBrIgI2AgBB0JsBIAAgAWoiADYCACAAIAJBAXI2AgQgASADakEoNgIEQdSbAUGgnwEoAgA2AgAMAgsgAC0ADEEIcQ0AIAMgB0sNACABIAdNDQAgACACIAVqNgIEQdCbASAHQXggB2tBB3FBACAHQQhqQQdxGyIAaiICNgIAQcSbAUHEmwEoAgAgBWoiASAAayIANgIAIAIgAEEBcjYCBCABIAdqQSg2AgRB1JsBQaCfASgCADYCAAwBC0HImwEoAgAgAUsEQEHImwEgATYCAAsgASAFaiECQfieASEAAkACQAJAAkACQAJAA0AgAiAAKAIARwRAIAAoAggiAA0BDAILCyAALQAMQQhxRQ0BC0H4ngEhAANAIAcgACgCACICTwRAIAIgACgCBGoiBCAHSw0DCyAAKAIIIQAMAAsACyAAIAE2AgAgACAAKAIEIAVqNgIEIAFBeCABa0EHcUEAIAFBCGpBB3EbaiIJIAhBA3I2AgQgAkF4IAJrQQdxQQAgAkEIakEHcRtqIgUgCCAJaiIGayECIAUgB0YEQEHQmwEgBjYCAEHEmwFBxJsBKAIAIAJqIgA2AgAgBiAAQQFyNgIEDAMLIAVBzJsBKAIARgRAQcybASAGNgIAQcCbAUHAmwEoAgAgAmoiADYCACAGIABBAXI2AgQgACAGaiAANgIADAMLIAUoAgQiAEEDcUEBRgRAIABBeHEhBwJAIABB/wFNBEAgBSgCCCIDIABBA3YiAEEDdEHgmwFqRhogAyAFKAIMIgFGBEBBuJsBQbibASgCAEF+IAB3cTYCAAwCCyADIAE2AgwgASADNgIIDAELIAUoAhghCAJAIAUgBSgCDCIBRwRAIAUoAggiACABNgIMIAEgADYCCAwBCwJAIAVBFGoiACgCACIDDQAgBUEQaiIAKAIAIgMNAEEAIQEMAQsDQCAAIQQgAyIBQRRqIgAoAgAiAw0AIAFBEGohACABKAIQIgMNAAsgBEEANgIACyAIRQ0AAkAgBSAFKAIcIgNBAnRB6J0BaiIAKAIARgRAIAAgATYCACABDQFBvJsBQbybASgCAEF+IAN3cTYCAAwCCyAIQRBBFCAIKAIQIAVGG2ogATYCACABRQ0BCyABIAg2AhggBSgCECIABEAgASAANgIQIAAgATYCGAsgBSgCFCIARQ0AIAEgADYCFCAAIAE2AhgLIAUgB2ohBSACIAdqIQILIAUgBSgCBEF+cTYCBCAGIAJBAXI2AgQgAiAGaiACNgIAIAJB/wFNBEAgAkEDdiIAQQN0QeCbAWohAgJ/QbibASgCACIBQQEgAHQiAHFFBEBBuJsBIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwDC0EfIQAgAkH///8HTQRAIAJBCHYiACAAQYD+P2pBEHZBCHEiA3QiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASADciAAcmsiAEEBdCACIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRB6J0BaiEEAkBBvJsBKAIAIgNBASAAdCIBcUUEQEG8mwEgASADcjYCACAEIAY2AgAgBiAENgIYDAELIAJBAEEZIABBAXZrIABBH0YbdCEAIAQoAgAhAQNAIAEiAygCBEF4cSACRg0DIABBHXYhASAAQQF0IQAgAyABQQRxaiIEKAIQIgENAAsgBCAGNgIQIAYgAzYCGAsgBiAGNgIMIAYgBjYCCAwCC0HEmwEgBUEoayIDQXggAWtBB3FBACABQQhqQQdxGyIAayICNgIAQdCbASAAIAFqIgA2AgAgACACQQFyNgIEIAEgA2pBKDYCBEHUmwFBoJ8BKAIANgIAIAcgBEEnIARrQQdxQQAgBEEna0EHcRtqQS9rIgAgACAHQRBqSRsiAkEbNgIEIAJBgJ8BKQIANwIQIAJB+J4BKQIANwIIQYCfASACQQhqNgIAQfyeASAFNgIAQfieASABNgIAQYSfAUEANgIAIAJBGGohAANAIABBBzYCBCAAQQhqIQEgAEEEaiEAIAEgBEkNAAsgAiAHRg0DIAIgAigCBEF+cTYCBCAHIAIgB2siBEEBcjYCBCACIAQ2AgAgBEH/AU0EQCAEQQN2IgBBA3RB4JsBaiECAn9BuJsBKAIAIgFBASAAdCIAcUUEQEG4mwEgACABcjYCACACDAELIAIoAggLIQAgAiAHNgIIIAAgBzYCDCAHIAI2AgwgByAANgIIDAQLQR8hACAHQgA3AhAgBEH///8HTQRAIARBCHYiACAAQYD+P2pBEHZBCHEiAnQiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASACciAAcmsiAEEBdCAEIABBFWp2QQFxckEcaiEACyAHIAA2AhwgAEECdEHonQFqIQMCQEG8mwEoAgAiAkEBIAB0IgFxRQRAQbybASABIAJyNgIAIAMgBzYCACAHIAM2AhgMAQsgBEEAQRkgAEEBdmsgAEEfRht0IQAgAygCACEBA0AgASICKAIEQXhxIARGDQQgAEEddiEBIABBAXQhACACIAFBBHFqIgMoAhAiAQ0ACyADIAc2AhAgByACNgIYCyAHIAc2AgwgByAHNgIIDAMLIAMoAggiACAGNgIMIAMgBjYCCCAGQQA2AhggBiADNgIMIAYgADYCCAsgCUEIaiEADAULIAIoAggiACAHNgIMIAIgBzYCCCAHQQA2AhggByACNgIMIAcgADYCCAtBxJsBKAIAIgAgCE0NAEHEmwEgACAIayIBNgIAQdCbAUHQmwEoAgAiAiAIaiIANgIAIAAgAUEBcjYCBCACIAhBA3I2AgQgAkEIaiEADAMLQbSbAUEwNgIAQQAhAAwCCwJAIAVFDQACQCAEKAIcIgJBAnRB6J0BaiIAKAIAIARGBEAgACABNgIAIAENAUG8mwEgCUF+IAJ3cSIJNgIADAILIAVBEEEUIAUoAhAgBEYbaiABNgIAIAFFDQELIAEgBTYCGCAEKAIQIgAEQCABIAA2AhAgACABNgIYCyAEKAIUIgBFDQAgASAANgIUIAAgATYCGAsCQCADQQ9NBEAgBCADIAhqIgBBA3I2AgQgACAEaiIAIAAoAgRBAXI2AgQMAQsgBCAIQQNyNgIEIAYgA0EBcjYCBCADIAZqIAM2AgAgA0H/AU0EQCADQQN2IgBBA3RB4JsBaiECAn9BuJsBKAIAIgFBASAAdCIAcUUEQEG4mwEgACABcjYCACACDAELIAIoAggLIQAgAiAGNgIIIAAgBjYCDCAGIAI2AgwgBiAANgIIDAELQR8hACADQf///wdNBEAgA0EIdiIAIABBgP4/akEQdkEIcSICdCIAIABBgOAfakEQdkEEcSIBdCIAIABBgIAPakEQdkECcSIAdEEPdiABIAJyIAByayIAQQF0IAMgAEEVanZBAXFyQRxqIQALIAYgADYCHCAGQgA3AhAgAEECdEHonQFqIQICQAJAIAlBASAAdCIBcUUEQEG8mwEgASAJcjYCACACIAY2AgAgBiACNgIYDAELIANBAEEZIABBAXZrIABBH0YbdCEAIAIoAgAhCANAIAgiASgCBEF4cSADRg0CIABBHXYhAiAAQQF0IQAgASACQQRxaiICKAIQIggNAAsgAiAGNgIQIAYgATYCGAsgBiAGNgIMIAYgBjYCCAwBCyABKAIIIgAgBjYCDCABIAY2AgggBkEANgIYIAYgATYCDCAGIAA2AggLIARBCGohAAwBCwJAIAtFDQACQCABKAIcIgJBAnRB6J0BaiIAKAIAIAFGBEAgACAENgIAIAQNAUG8mwEgBkF+IAJ3cTYCAAwCCyALQRBBFCALKAIQIAFGG2ogBDYCACAERQ0BCyAEIAs2AhggASgCECIABEAgBCAANgIQIAAgBDYCGAsgASgCFCIARQ0AIAQgADYCFCAAIAQ2AhgLAkAgA0EPTQRAIAEgAyAIaiIAQQNyNgIEIAAgAWoiACAAKAIEQQFyNgIEDAELIAEgCEEDcjYCBCAJIANBAXI2AgQgAyAJaiADNgIAIAoEQCAKQQN2IgBBA3RB4JsBaiEEQcybASgCACECAn9BASAAdCIAIAVxRQRAQbibASAAIAVyNgIAIAQMAQsgBCgCCAshACAEIAI2AgggACACNgIMIAIgBDYCDCACIAA2AggLQcybASAJNgIAQcCbASADNgIACyABQQhqIQALIAxBEGokACAAC4MEAQN/IAJBgARPBEAgACABIAIQEhogAA8LIAAgAmohAwJAIAAgAXNBA3FFBEACQCAAQQNxRQRAIAAhAgwBCyACQQFIBEAgACECDAELIAAhAgNAIAIgAS0AADoAACABQQFqIQEgAkEBaiICQQNxRQ0BIAIgA0kNAAsLAkAgA0F8cSIEQcAASQ0AIAIgBEFAaiIFSw0AA0AgAiABKAIANgIAIAIgASgCBDYCBCACIAEoAgg2AgggAiABKAIMNgIMIAIgASgCEDYCECACIAEoAhQ2AhQgAiABKAIYNgIYIAIgASgCHDYCHCACIAEoAiA2AiAgAiABKAIkNgIkIAIgASgCKDYCKCACIAEoAiw2AiwgAiABKAIwNgIwIAIgASgCNDYCNCACIAEoAjg2AjggAiABKAI8NgI8IAFBQGshASACQUBrIgIgBU0NAAsLIAIgBE8NAQNAIAIgASgCADYCACABQQRqIQEgAkEEaiICIARJDQALDAELIANBBEkEQCAAIQIMAQsgACADQQRrIgRLBEAgACECDAELIAAhAgNAIAIgAS0AADoAACACIAEtAAE6AAEgAiABLQACOgACIAIgAS0AAzoAAyABQQRqIQEgAkEEaiICIARNDQALCyACIANJBEADQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADRw0ACwsgAAu4GAECfyMAQRBrIgQkACAEIAA2AgwgBCABNgIIIAQgAjYCBCAEKAIMIQAgBCgCCCECIAQoAgQhAyMAQSBrIgEkACABIAA2AhggASACNgIUIAEgAzYCEAJAIAEoAhRFBEAgAUEANgIcDAELIAFBATYCDCABLQAMBEAgASgCFCECIAEoAhAhAyMAQSBrIgAgASgCGDYCHCAAIAI2AhggACADNgIUIAAgACgCHDYCECAAIAAoAhBBf3M2AhADQCAAKAIUBH8gACgCGEEDcUEARwVBAAtBAXEEQCAAKAIQIQIgACAAKAIYIgNBAWo2AhggACADLQAAIAJzQf8BcUECdEGQFWooAgAgACgCEEEIdnM2AhAgACAAKAIUQQFrNgIUDAELCyAAIAAoAhg2AgwDQCAAKAIUQSBPBEAgACAAKAIMIgJBBGo2AgwgACACKAIAIAAoAhBzNgIQIAAgACgCEEEYdkECdEGQFWooAgAgACgCEEEQdkH/AXFBAnRBkB1qKAIAIAAoAhBB/wFxQQJ0QZAtaigCACAAKAIQQQh2Qf8BcUECdEGQJWooAgBzc3M2AhAgACAAKAIMIgJBBGo2AgwgACACKAIAIAAoAhBzNgIQIAAgACgCEEEYdkECdEGQFWooAgAgACgCEEEQdkH/AXFBAnRBkB1qKAIAIAAoAhBB/wFxQQJ0QZAtaigCACAAKAIQQQh2Qf8BcUECdEGQJWooAgBzc3M2AhAgACAAKAIMIgJBBGo2AgwgACACKAIAIAAoAhBzNgIQIAAgACgCEEEYdkECdEGQFWooAgAgACgCEEEQdkH/AXFBAnRBkB1qKAIAIAAoAhBB/wFxQQJ0QZAtaigCACAAKAIQQQh2Qf8BcUECdEGQJWooAgBzc3M2AhAgACAAKAIMIgJBBGo2AgwgACACKAIAIAAoAhBzNgIQIAAgACgCEEEYdkECdEGQFWooAgAgACgCEEEQdkH/AXFBAnRBkB1qKAIAIAAoAhBB/wFxQQJ0QZAtaigCACAAKAIQQQh2Qf8BcUECdEGQJWooAgBzc3M2AhAgACAAKAIMIgJBBGo2AgwgACACKAIAIAAoAhBzNgIQIAAgACgCEEEYdkECdEGQFWooAgAgACgCEEEQdkH/AXFBAnRBkB1qKAIAIAAoAhBB/wFxQQJ0QZAtaigCACAAKAIQQQh2Qf8BcUECdEGQJWooAgBzc3M2AhAgACAAKAIMIgJBBGo2AgwgACACKAIAIAAoAhBzNgIQIAAgACgCEEEYdkECdEGQFWooAgAgACgCEEEQdkH/AXFBAnRBkB1qKAIAIAAoAhBB/wFxQQJ0QZAtaigCACAAKAIQQQh2Qf8BcUECdEGQJWooAgBzc3M2AhAgACAAKAIMIgJBBGo2AgwgACACKAIAIAAoAhBzNgIQIAAgACgCEEEYdkECdEGQFWooAgAgACgCEEEQdkH/AXFBAnRBkB1qKAIAIAAoAhBB/wFxQQJ0QZAtaigCACAAKAIQQQh2Qf8BcUECdEGQJWooAgBzc3M2AhAgACAAKAIMIgJBBGo2AgwgACACKAIAIAAoAhBzNgIQIAAgACgCEEEYdkECdEGQFWooAgAgACgCEEEQdkH/AXFBAnRBkB1qKAIAIAAoAhBB/wFxQQJ0QZAtaigCACAAKAIQQQh2Qf8BcUECdEGQJWooAgBzc3M2AhAgACAAKAIUQSBrNgIUDAELCwNAIAAoAhRBBE8EQCAAIAAoAgwiAkEEajYCDCAAIAIoAgAgACgCEHM2AhAgACAAKAIQQRh2QQJ0QZAVaigCACAAKAIQQRB2Qf8BcUECdEGQHWooAgAgACgCEEH/AXFBAnRBkC1qKAIAIAAoAhBBCHZB/wFxQQJ0QZAlaigCAHNzczYCECAAIAAoAhRBBGs2AhQMAQsLIAAgACgCDDYCGCAAKAIUBEADQCAAKAIQIQIgACAAKAIYIgNBAWo2AhggACADLQAAIAJzQf8BcUECdEGQFWooAgAgACgCEEEIdnM2AhAgACAAKAIUQQFrIgI2AhQgAg0ACwsgACAAKAIQQX9zNgIQIAEgACgCEDYCHAwBCyABKAIUIQIgASgCECEDIwBBIGsiACABKAIYNgIcIAAgAjYCGCAAIAM2AhQgACAAKAIcQQh2QYD+A3EgACgCHEEYdmogACgCHEGA/gNxQQh0aiAAKAIcQf8BcUEYdGo2AhAgACAAKAIQQX9zNgIQA0AgACgCFAR/IAAoAhhBA3FBAEcFQQALQQFxBEAgACgCEEEYdiECIAAgACgCGCIDQQFqNgIYIAAgAy0AACACc0ECdEGQNWooAgAgACgCEEEIdHM2AhAgACAAKAIUQQFrNgIUDAELCyAAIAAoAhg2AgwDQCAAKAIUQSBPBEAgACAAKAIMIgJBBGo2AgwgACACKAIAIAAoAhBzNgIQIAAgACgCEEEYdkECdEGQzQBqKAIAIAAoAhBBEHZB/wFxQQJ0QZDFAGooAgAgACgCEEH/AXFBAnRBkDVqKAIAIAAoAhBBCHZB/wFxQQJ0QZA9aigCAHNzczYCECAAIAAoAgwiAkEEajYCDCAAIAIoAgAgACgCEHM2AhAgACAAKAIQQRh2QQJ0QZDNAGooAgAgACgCEEEQdkH/AXFBAnRBkMUAaigCACAAKAIQQf8BcUECdEGQNWooAgAgACgCEEEIdkH/AXFBAnRBkD1qKAIAc3NzNgIQIAAgACgCDCICQQRqNgIMIAAgAigCACAAKAIQczYCECAAIAAoAhBBGHZBAnRBkM0AaigCACAAKAIQQRB2Qf8BcUECdEGQxQBqKAIAIAAoAhBB/wFxQQJ0QZA1aigCACAAKAIQQQh2Qf8BcUECdEGQPWooAgBzc3M2AhAgACAAKAIMIgJBBGo2AgwgACACKAIAIAAoAhBzNgIQIAAgACgCEEEYdkECdEGQzQBqKAIAIAAoAhBBEHZB/wFxQQJ0QZDFAGooAgAgACgCEEH/AXFBAnRBkDVqKAIAIAAoAhBBCHZB/wFxQQJ0QZA9aigCAHNzczYCECAAIAAoAgwiAkEEajYCDCAAIAIoAgAgACgCEHM2AhAgACAAKAIQQRh2QQJ0QZDNAGooAgAgACgCEEEQdkH/AXFBAnRBkMUAaigCACAAKAIQQf8BcUECdEGQNWooAgAgACgCEEEIdkH/AXFBAnRBkD1qKAIAc3NzNgIQIAAgACgCDCICQQRqNgIMIAAgAigCACAAKAIQczYCECAAIAAoAhBBGHZBAnRBkM0AaigCACAAKAIQQRB2Qf8BcUECdEGQxQBqKAIAIAAoAhBB/wFxQQJ0QZA1aigCACAAKAIQQQh2Qf8BcUECdEGQPWooAgBzc3M2AhAgACAAKAIMIgJBBGo2AgwgACACKAIAIAAoAhBzNgIQIAAgACgCEEEYdkECdEGQzQBqKAIAIAAoAhBBEHZB/wFxQQJ0QZDFAGooAgAgACgCEEH/AXFBAnRBkDVqKAIAIAAoAhBBCHZB/wFxQQJ0QZA9aigCAHNzczYCECAAIAAoAgwiAkEEajYCDCAAIAIoAgAgACgCEHM2AhAgACAAKAIQQRh2QQJ0QZDNAGooAgAgACgCEEEQdkH/AXFBAnRBkMUAaigCACAAKAIQQf8BcUECdEGQNWooAgAgACgCEEEIdkH/AXFBAnRBkD1qKAIAc3NzNgIQIAAgACgCFEEgazYCFAwBCwsDQCAAKAIUQQRPBEAgACAAKAIMIgJBBGo2AgwgACACKAIAIAAoAhBzNgIQIAAgACgCEEEYdkECdEGQzQBqKAIAIAAoAhBBEHZB/wFxQQJ0QZDFAGooAgAgACgCEEH/AXFBAnRBkDVqKAIAIAAoAhBBCHZB/wFxQQJ0QZA9aigCAHNzczYCECAAIAAoAhRBBGs2AhQMAQsLIAAgACgCDDYCGCAAKAIUBEADQCAAKAIQQRh2IQIgACAAKAIYIgNBAWo2AhggACADLQAAIAJzQQJ0QZA1aigCACAAKAIQQQh0czYCECAAIAAoAhRBAWsiAjYCFCACDQALCyAAIAAoAhBBf3M2AhAgASAAKAIQQQh2QYD+A3EgACgCEEEYdmogACgCEEGA/gNxQQh0aiAAKAIQQf8BcUEYdGo2AhwLIAEoAhwhACABQSBqJAAgBEEQaiQAIAAL7AIBAn8jAEEQayIBJAAgASAANgIMAkAgASgCDEUNACABKAIMKAIwBEAgASgCDCIAIAAoAjBBAWs2AjALIAEoAgwoAjANACABKAIMKAIgBEAgASgCDEEBNgIgIAEoAgwQMRoLIAEoAgwoAiRBAUYEQCABKAIMEGcLAkAgASgCDCgCLEUNACABKAIMLQAoQQFxDQAgASgCDCECIwBBEGsiACABKAIMKAIsNgIMIAAgAjYCCCAAQQA2AgQDQCAAKAIEIAAoAgwoAkRJBEAgACgCDCgCTCAAKAIEQQJ0aigCACAAKAIIRgRAIAAoAgwoAkwgACgCBEECdGogACgCDCgCTCAAKAIMKAJEQQFrQQJ0aigCADYCACAAKAIMIgAgACgCREEBazYCRAUgACAAKAIEQQFqNgIEDAILCwsLIAEoAgxBAEIAQQUQIRogASgCDCgCAARAIAEoAgwoAgAQGwsgASgCDBAVCyABQRBqJAALnwIBAn8jAEEQayIBJAAgASAANgIMIAEgASgCDCgCHDYCBCABKAIEIQIjAEEQayIAJAAgACACNgIMIAAoAgwQuwEgAEEQaiQAIAEgASgCBCgCFDYCCCABKAIIIAEoAgwoAhBLBEAgASABKAIMKAIQNgIICwJAIAEoAghFDQAgASgCDCgCDCABKAIEKAIQIAEoAggQGRogASgCDCIAIAEoAgggACgCDGo2AgwgASgCBCIAIAEoAgggACgCEGo2AhAgASgCDCIAIAEoAgggACgCFGo2AhQgASgCDCIAIAAoAhAgASgCCGs2AhAgASgCBCIAIAAoAhQgASgCCGs2AhQgASgCBCgCFA0AIAEoAgQgASgCBCgCCDYCEAsgAUEQaiQAC2ABAX8jAEEQayIBJAAgASAANgIIIAEgASgCCEICEB42AgQCQCABKAIERQRAIAFBADsBDgwBCyABIAEoAgQtAAAgASgCBC0AAUEIdGo7AQ4LIAEvAQ4hACABQRBqJAAgAAvpAQEBfyMAQSBrIgIkACACIAA2AhwgAiABNwMQIAIpAxAhASMAQSBrIgAgAigCHDYCGCAAIAE3AxACQAJAAkAgACgCGC0AAEEBcUUNACAAKQMQIAAoAhgpAxAgACkDEHxWDQAgACgCGCkDCCAAKAIYKQMQIAApAxB8Wg0BCyAAKAIYQQA6AAAgAEEANgIcDAELIAAgACgCGCgCBCAAKAIYKQMQp2o2AgwgACAAKAIMNgIcCyACIAAoAhw2AgwgAigCDARAIAIoAhwiACACKQMQIAApAxB8NwMQCyACKAIMIQAgAkEgaiQAIAALbwEBfyMAQRBrIgIkACACIAA2AgggAiABOwEGIAIgAigCCEICEB42AgACQCACKAIARQRAIAJBfzYCDAwBCyACKAIAIAIvAQY6AAAgAigCACACLwEGQQh2OgABIAJBADYCDAsgAigCDBogAkEQaiQAC48BAQF/IwBBEGsiAiQAIAIgADYCCCACIAE2AgQgAiACKAIIQgQQHjYCAAJAIAIoAgBFBEAgAkF/NgIMDAELIAIoAgAgAigCBDoAACACKAIAIAIoAgRBCHY6AAEgAigCACACKAIEQRB2OgACIAIoAgAgAigCBEEYdjoAAyACQQA2AgwLIAIoAgwaIAJBEGokAAu2AgEBfyMAQTBrIgQkACAEIAA2AiQgBCABNgIgIAQgAjcDGCAEIAM2AhQCQCAEKAIkKQMYQgEgBCgCFK2Gg1AEQCAEKAIkQQxqQRxBABAUIARCfzcDKAwBCwJAIAQoAiQoAgBFBEAgBCAEKAIkKAIIIAQoAiAgBCkDGCAEKAIUIAQoAiQoAgQRDgA3AwgMAQsgBCAEKAIkKAIAIAQoAiQoAgggBCgCICAEKQMYIAQoAhQgBCgCJCgCBBEKADcDCAsgBCkDCEIAUwRAAkAgBCgCFEEERg0AIAQoAhRBDkYNAAJAIAQoAiQgBEIIQQQQIUIAUwRAIAQoAiRBDGpBFEEAEBQMAQsgBCgCJEEMaiAEKAIAIAQoAgQQFAsLCyAEIAQpAwg3AygLIAQpAyghAiAEQTBqJAAgAgsXACAALQAAQSBxRQRAIAEgAiAAEHIaCwtQAQF/IwBBEGsiASQAIAEgADYCDANAIAEoAgwEQCABIAEoAgwoAgA2AgggASgCDCgCDBAVIAEoAgwQFSABIAEoAgg2AgwMAQsLIAFBEGokAAt9AQF/IwBBEGsiASQAIAEgADYCDCABKAIMBEAgAUIANwMAA0AgASkDACABKAIMKQMIWkUEQCABKAIMKAIAIAEpAwCnQQR0ahBiIAEgASkDAEIBfDcDAAwBCwsgASgCDCgCABAVIAEoAgwoAigQJSABKAIMEBULIAFBEGokAAs+AQF/IwBBEGsiASQAIAEgADYCDCABKAIMBEAgASgCDCgCABAVIAEoAgwoAgwQFSABKAIMEBULIAFBEGokAAtuAQF/IwBBgAJrIgUkAAJAIARBgMAEcQ0AIAIgA0wNACAFIAFB/wFxIAIgA2siAkGAAiACQYACSSIBGxAyIAFFBEADQCAAIAVBgAIQIiACQYACayICQf8BSw0ACwsgACAFIAIQIgsgBUGAAmokAAvRAQEBfyMAQTBrIgMkACADIAA2AiggAyABNwMgIAMgAjYCHAJAIAMoAigtAChBAXEEQCADQX82AiwMAQsCQCADKAIoKAIgBEAgAygCHEUNASADKAIcQQFGDQEgAygCHEECRg0BCyADKAIoQQxqQRJBABAUIANBfzYCLAwBCyADIAMpAyA3AwggAyADKAIcNgIQIAMoAiggA0EIakIQQQYQIUIAUwRAIANBfzYCLAwBCyADKAIoQQA6ADQgA0EANgIsCyADKAIsIQAgA0EwaiQAIAALmBcBAn8jAEEwayIEJAAgBCAANgIsIAQgATYCKCAEIAI2AiQgBCADNgIgIARBADYCFAJAIAQoAiwoAoQBQQBKBEAgBCgCLCgCACgCLEECRgRAIwBBEGsiACAEKAIsNgIIIABB/4D/n382AgQgAEEANgIAAkADQCAAKAIAQR9MBEACQCAAKAIEQQFxRQ0AIAAoAghBlAFqIAAoAgBBAnRqLwEARQ0AIABBADYCDAwDCyAAIAAoAgBBAWo2AgAgACAAKAIEQQF2NgIEDAELCwJAAkAgACgCCC8BuAENACAAKAIILwG8AQ0AIAAoAggvAcgBRQ0BCyAAQQE2AgwMAQsgAEEgNgIAA0AgACgCAEGAAkgEQCAAKAIIQZQBaiAAKAIAQQJ0ai8BAARAIABBATYCDAwDBSAAIAAoAgBBAWo2AgAMAgsACwsgAEEANgIMCyAAKAIMIQAgBCgCLCgCACAANgIsCyAEKAIsIAQoAixBmBZqEHsgBCgCLCAEKAIsQaQWahB7IAQoAiwhASMAQRBrIgAkACAAIAE2AgwgACgCDCAAKAIMQZQBaiAAKAIMKAKcFhC5ASAAKAIMIAAoAgxBiBNqIAAoAgwoAqgWELkBIAAoAgwgACgCDEGwFmoQeyAAQRI2AggDQAJAIAAoAghBA0gNACAAKAIMQfwUaiAAKAIILQDgbEECdGovAQINACAAIAAoAghBAWs2AggMAQsLIAAoAgwiASABKAKoLSAAKAIIQQNsQRFqajYCqC0gACgCCCEBIABBEGokACAEIAE2AhQgBCAEKAIsKAKoLUEKakEDdjYCHCAEIAQoAiwoAqwtQQpqQQN2NgIYIAQoAhggBCgCHE0EQCAEIAQoAhg2AhwLDAELIAQgBCgCJEEFaiIANgIYIAQgADYCHAsCQAJAIAQoAhwgBCgCJEEEakkNACAEKAIoRQ0AIAQoAiwgBCgCKCAEKAIkIAQoAiAQXAwBCwJAAkAgBCgCLCgCiAFBBEcEQCAEKAIYIAQoAhxHDQELIARBAzYCEAJAIAQoAiwoArwtQRAgBCgCEGtKBEAgBCAEKAIgQQJqNgIMIAQoAiwiACAALwG4LSAEKAIMQf//A3EgBCgCLCgCvC10cjsBuC0gBCgCLC8BuC1B/wFxIQEgBCgCLCgCCCECIAQoAiwiAygCFCEAIAMgAEEBajYCFCAAIAJqIAE6AAAgBCgCLC8BuC1BCHYhASAEKAIsKAIIIQIgBCgCLCIDKAIUIQAgAyAAQQFqNgIUIAAgAmogAToAACAEKAIsIAQoAgxB//8DcUEQIAQoAiwoArwta3U7AbgtIAQoAiwiACAAKAK8LSAEKAIQQRBrajYCvC0MAQsgBCgCLCIAIAAvAbgtIAQoAiBBAmpB//8DcSAEKAIsKAK8LXRyOwG4LSAEKAIsIgAgBCgCECAAKAK8LWo2ArwtCyAEKAIsQZDgAEGQ6QAQugEMAQsgBEEDNgIIAkAgBCgCLCgCvC1BECAEKAIIa0oEQCAEIAQoAiBBBGo2AgQgBCgCLCIAIAAvAbgtIAQoAgRB//8DcSAEKAIsKAK8LXRyOwG4LSAEKAIsLwG4LUH/AXEhASAEKAIsKAIIIQIgBCgCLCIDKAIUIQAgAyAAQQFqNgIUIAAgAmogAToAACAEKAIsLwG4LUEIdiEBIAQoAiwoAgghAiAEKAIsIgMoAhQhACADIABBAWo2AhQgACACaiABOgAAIAQoAiwgBCgCBEH//wNxQRAgBCgCLCgCvC1rdTsBuC0gBCgCLCIAIAAoArwtIAQoAghBEGtqNgK8LQwBCyAEKAIsIgAgAC8BuC0gBCgCIEEEakH//wNxIAQoAiwoArwtdHI7AbgtIAQoAiwiACAEKAIIIAAoArwtajYCvC0LIAQoAiwhASAEKAIsKAKcFkEBaiECIAQoAiwoAqgWQQFqIQMgBCgCFEEBaiEFIwBBQGoiACQAIAAgATYCPCAAIAI2AjggACADNgI0IAAgBTYCMCAAQQU2AigCQCAAKAI8KAK8LUEQIAAoAihrSgRAIAAgACgCOEGBAms2AiQgACgCPCIBIAEvAbgtIAAoAiRB//8DcSAAKAI8KAK8LXRyOwG4LSAAKAI8LwG4LUH/AXEhAiAAKAI8KAIIIQMgACgCPCIFKAIUIQEgBSABQQFqNgIUIAEgA2ogAjoAACAAKAI8LwG4LUEIdiECIAAoAjwoAgghAyAAKAI8IgUoAhQhASAFIAFBAWo2AhQgASADaiACOgAAIAAoAjwgACgCJEH//wNxQRAgACgCPCgCvC1rdTsBuC0gACgCPCIBIAEoArwtIAAoAihBEGtqNgK8LQwBCyAAKAI8IgEgAS8BuC0gACgCOEGBAmtB//8DcSAAKAI8KAK8LXRyOwG4LSAAKAI8IgEgACgCKCABKAK8LWo2ArwtCyAAQQU2AiACQCAAKAI8KAK8LUEQIAAoAiBrSgRAIAAgACgCNEEBazYCHCAAKAI8IgEgAS8BuC0gACgCHEH//wNxIAAoAjwoArwtdHI7AbgtIAAoAjwvAbgtQf8BcSECIAAoAjwoAgghAyAAKAI8IgUoAhQhASAFIAFBAWo2AhQgASADaiACOgAAIAAoAjwvAbgtQQh2IQIgACgCPCgCCCEDIAAoAjwiBSgCFCEBIAUgAUEBajYCFCABIANqIAI6AAAgACgCPCAAKAIcQf//A3FBECAAKAI8KAK8LWt1OwG4LSAAKAI8IgEgASgCvC0gACgCIEEQa2o2ArwtDAELIAAoAjwiASABLwG4LSAAKAI0QQFrQf//A3EgACgCPCgCvC10cjsBuC0gACgCPCIBIAAoAiAgASgCvC1qNgK8LQsgAEEENgIYAkAgACgCPCgCvC1BECAAKAIYa0oEQCAAIAAoAjBBBGs2AhQgACgCPCIBIAEvAbgtIAAoAhRB//8DcSAAKAI8KAK8LXRyOwG4LSAAKAI8LwG4LUH/AXEhAiAAKAI8KAIIIQMgACgCPCIFKAIUIQEgBSABQQFqNgIUIAEgA2ogAjoAACAAKAI8LwG4LUEIdiECIAAoAjwoAgghAyAAKAI8IgUoAhQhASAFIAFBAWo2AhQgASADaiACOgAAIAAoAjwgACgCFEH//wNxQRAgACgCPCgCvC1rdTsBuC0gACgCPCIBIAEoArwtIAAoAhhBEGtqNgK8LQwBCyAAKAI8IgEgAS8BuC0gACgCMEEEa0H//wNxIAAoAjwoArwtdHI7AbgtIAAoAjwiASAAKAIYIAEoArwtajYCvC0LIABBADYCLANAIAAoAiwgACgCMEgEQCAAQQM2AhACQCAAKAI8KAK8LUEQIAAoAhBrSgRAIAAgACgCPEH8FGogACgCLC0A4GxBAnRqLwECNgIMIAAoAjwiASABLwG4LSAAKAIMQf//A3EgACgCPCgCvC10cjsBuC0gACgCPC8BuC1B/wFxIQIgACgCPCgCCCEDIAAoAjwiBSgCFCEBIAUgAUEBajYCFCABIANqIAI6AAAgACgCPC8BuC1BCHYhAiAAKAI8KAIIIQMgACgCPCIFKAIUIQEgBSABQQFqNgIUIAEgA2ogAjoAACAAKAI8IAAoAgxB//8DcUEQIAAoAjwoArwta3U7AbgtIAAoAjwiASABKAK8LSAAKAIQQRBrajYCvC0MAQsgACgCPCIBIAEvAbgtIAAoAjxB/BRqIAAoAiwtAOBsQQJ0ai8BAiAAKAI8KAK8LXRyOwG4LSAAKAI8IgEgACgCECABKAK8LWo2ArwtCyAAIAAoAixBAWo2AiwMAQsLIAAoAjwgACgCPEGUAWogACgCOEEBaxC4ASAAKAI8IAAoAjxBiBNqIAAoAjRBAWsQuAEgAEFAayQAIAQoAiwgBCgCLEGUAWogBCgCLEGIE2oQugELCyAEKAIsEL0BIAQoAiAEQCAEKAIsELwBCyAEQTBqJAAL1AEBAX8jAEEgayICJAAgAiAANgIYIAIgATcDECACIAIoAhhFOgAPAkAgAigCGEUEQCACIAIpAxCnEBgiADYCGCAARQRAIAJBADYCHAwCCwsgAkEYEBgiADYCCCAARQRAIAItAA9BAXEEQCACKAIYEBULIAJBADYCHAwBCyACKAIIQQE6AAAgAigCCCACKAIYNgIEIAIoAgggAikDEDcDCCACKAIIQgA3AxAgAigCCCACLQAPQQFxOgABIAIgAigCCDYCHAsgAigCHCEAIAJBIGokACAAC3gBAX8jAEEQayIBJAAgASAANgIIIAEgASgCCEIEEB42AgQCQCABKAIERQRAIAFBADYCDAwBCyABIAEoAgQtAAAgASgCBC0AASABKAIELQACIAEoAgQtAANBCHRqQQh0akEIdGo2AgwLIAEoAgwhACABQRBqJAAgAAt/AQN/IAAhAQJAIABBA3EEQANAIAEtAABFDQIgAUEBaiIBQQNxDQALCwNAIAEiAkEEaiEBIAIoAgAiA0F/cyADQYGChAhrcUGAgYKEeHFFDQALIANB/wFxRQRAIAIgAGsPCwNAIAItAAEhAyACQQFqIgEhAiADDQALCyABIABrC2EBAX8jAEEQayICIAA2AgggAiABNwMAAkAgAikDACACKAIIKQMIVgRAIAIoAghBADoAACACQX82AgwMAQsgAigCCEEBOgAAIAIoAgggAikDADcDECACQQA2AgwLIAIoAgwL7wEBAX8jAEEgayICJAAgAiAANgIYIAIgATcDECACIAIoAhhCCBAeNgIMAkAgAigCDEUEQCACQX82AhwMAQsgAigCDCACKQMQQv8BgzwAACACKAIMIAIpAxBCCIhC/wGDPAABIAIoAgwgAikDEEIQiEL/AYM8AAIgAigCDCACKQMQQhiIQv8BgzwAAyACKAIMIAIpAxBCIIhC/wGDPAAEIAIoAgwgAikDEEIoiEL/AYM8AAUgAigCDCACKQMQQjCIQv8BgzwABiACKAIMIAIpAxBCOIhC/wGDPAAHIAJBADYCHAsgAigCHBogAkEgaiQAC4cDAQF/IwBBMGsiAyQAIAMgADYCJCADIAE2AiAgAyACNwMYAkAgAygCJC0AKEEBcQRAIANCfzcDKAwBCwJAAkAgAygCJCgCIEUNACADKQMYQv///////////wBWDQAgAykDGFANASADKAIgDQELIAMoAiRBDGpBEkEAEBQgA0J/NwMoDAELIAMoAiQtADVBAXEEQCADQn83AygMAQsCfyMAQRBrIgAgAygCJDYCDCAAKAIMLQA0QQFxCwRAIANCADcDKAwBCyADKQMYUARAIANCADcDKAwBCyADQgA3AxADQCADKQMQIAMpAxhUBEAgAyADKAIkIAMoAiAgAykDEKdqIAMpAxggAykDEH1BARAhIgI3AwggAkIAUwRAIAMoAiRBAToANSADKQMQUARAIANCfzcDKAwECyADIAMpAxA3AygMAwsgAykDCFAEQCADKAIkQQE6ADQFIAMgAykDCCADKQMQfDcDEAwCCwsLIAMgAykDEDcDKAsgAykDKCECIANBMGokACACCzYBAX8jAEEQayIBIAA2AgwCfiABKAIMLQAAQQFxBEAgASgCDCkDCCABKAIMKQMQfQwBC0IACwuyAQIBfwF+IwBBEGsiASQAIAEgADYCBCABIAEoAgRCCBAeNgIAAkAgASgCAEUEQCABQgA3AwgMAQsgASABKAIALQAArSABKAIALQAHrUI4hiABKAIALQAGrUIwhnwgASgCAC0ABa1CKIZ8IAEoAgAtAAStQiCGfCABKAIALQADrUIYhnwgASgCAC0AAq1CEIZ8IAEoAgAtAAGtQgiGfHw3AwgLIAEpAwghAiABQRBqJAAgAgumAQEBfyMAQRBrIgEkACABIAA2AggCQCABKAIIKAIgRQRAIAEoAghBDGpBEkEAEBQgAUF/NgIMDAELIAEoAggiACAAKAIgQQFrNgIgIAEoAggoAiBFBEAgASgCCEEAQgBBAhAhGiABKAIIKAIABEAgASgCCCgCABAxQQBIBEAgASgCCEEMakEUQQAQFAsLCyABQQA2AgwLIAEoAgwhACABQRBqJAAgAAvwAgICfwF+AkAgAkUNACAAIAJqIgNBAWsgAToAACAAIAE6AAAgAkEDSQ0AIANBAmsgAToAACAAIAE6AAEgA0EDayABOgAAIAAgAToAAiACQQdJDQAgA0EEayABOgAAIAAgAToAAyACQQlJDQAgAEEAIABrQQNxIgRqIgMgAUH/AXFBgYKECGwiADYCACADIAIgBGtBfHEiAmoiAUEEayAANgIAIAJBCUkNACADIAA2AgggAyAANgIEIAFBCGsgADYCACABQQxrIAA2AgAgAkEZSQ0AIAMgADYCGCADIAA2AhQgAyAANgIQIAMgADYCDCABQRBrIAA2AgAgAUEUayAANgIAIAFBGGsgADYCACABQRxrIAA2AgAgAiADQQRxQRhyIgFrIgJBIEkNACAArUKBgICAEH4hBSABIANqIQEDQCABIAU3AxggASAFNwMQIAEgBTcDCCABIAU3AwAgAUEgaiEBIAJBIGsiAkEfSw0ACwsL3AEBAX8jAEEQayIBJAAgASAANgIMIAEoAgwEQCABKAIMKAIoBEAgASgCDCgCKEEANgIoIAEoAgwoAihCADcDICABKAIMAn4gASgCDCkDGCABKAIMKQMgVgRAIAEoAgwpAxgMAQsgASgCDCkDIAs3AxgLIAEgASgCDCkDGDcDAANAIAEpAwAgASgCDCkDCFpFBEAgASgCDCgCACABKQMAp0EEdGooAgAQFSABIAEpAwBCAXw3AwAMAQsLIAEoAgwoAgAQFSABKAIMKAIEEBUgASgCDBAVCyABQRBqJAALYAIBfwF+IwBBEGsiASQAIAEgADYCBAJAIAEoAgQoAiRBAUcEQCABKAIEQQxqQRJBABAUIAFCfzcDCAwBCyABIAEoAgRBAEIAQQ0QITcDCAsgASkDCCECIAFBEGokACACC6UCAQJ/IwBBIGsiAyQAIAMgADYCGCADIAE2AhQgAyACNwMIIAMoAhgoAgAhASADKAIUIQQgAykDCCECIwBBIGsiACQAIAAgATYCFCAAIAQ2AhAgACACNwMIAkACQCAAKAIUKAIkQQFGBEAgACkDCEL///////////8AWA0BCyAAKAIUQQxqQRJBABAUIABCfzcDGAwBCyAAIAAoAhQgACgCECAAKQMIQQsQITcDGAsgACkDGCECIABBIGokACADIAI3AwACQCACQgBTBEAgAygCGEEIaiADKAIYKAIAEBcgA0F/NgIcDAELIAMpAwAgAykDCFIEQCADKAIYQQhqQQZBGxAUIANBfzYCHAwBCyADQQA2AhwLIAMoAhwhACADQSBqJAAgAAtrAQF/IwBBIGsiAiAANgIcIAJCASACKAIcrYY3AxAgAkEMaiABNgIAA0AgAiACKAIMIgBBBGo2AgwgAiAAKAIANgIIIAIoAghBAEhFBEAgAiACKQMQQgEgAigCCK2GhDcDEAwBCwsgAikDEAsvAQF/IwBBEGsiASQAIAEgADYCDCABKAIMKAIIEBUgASgCDEEANgIIIAFBEGokAAvNAQEBfyMAQRBrIgIkACACIAA2AgggAiABNgIEAkAgAigCCC0AKEEBcQRAIAJBfzYCDAwBCyACKAIERQRAIAIoAghBDGpBEkEAEBQgAkF/NgIMDAELIAIoAgQQOyACKAIIKAIABEAgAigCCCgCACACKAIEEDhBAEgEQCACKAIIQQxqIAIoAggoAgAQFyACQX82AgwMAgsLIAIoAgggAigCBEI4QQMQIUIAUwRAIAJBfzYCDAwBCyACQQA2AgwLIAIoAgwhACACQRBqJAAgAAsxAQF/IwBBEGsiASQAIAEgADYCDCABKAIMBEAgASgCDBBdIAEoAgwQFQsgAUEQaiQAC98EAQF/IwBBIGsiAiAANgIYIAIgATYCFAJAIAIoAhhFBEAgAkEBNgIcDAELIAIgAigCGCgCADYCDAJAIAIoAhgoAggEQCACIAIoAhgoAgg2AhAMAQsgAkEBNgIQIAJBADYCCANAAkAgAigCCCACKAIYLwEETw0AAkAgAigCDCACKAIIai0AAEEfSwRAIAIoAgwgAigCCGotAABBgAFJDQELIAIoAgwgAigCCGotAABBDUYNACACKAIMIAIoAghqLQAAQQpGDQAgAigCDCACKAIIai0AAEEJRgRADAELIAJBAzYCEAJAIAIoAgwgAigCCGotAABB4AFxQcABRgRAIAJBATYCAAwBCwJAIAIoAgwgAigCCGotAABB8AFxQeABRgRAIAJBAjYCAAwBCwJAIAIoAgwgAigCCGotAABB+AFxQfABRgRAIAJBAzYCAAwBCyACQQQ2AhAMBAsLCyACKAIYLwEEIAIoAgggAigCAGpNBEAgAkEENgIQDAILIAJBATYCBANAIAIoAgQgAigCAE0EQCACKAIMIAIoAgggAigCBGpqLQAAQcABcUGAAUcEQCACQQQ2AhAMBgUgAiACKAIEQQFqNgIEDAILAAsLIAIgAigCACACKAIIajYCCAsgAiACKAIIQQFqNgIIDAELCwsgAigCGCACKAIQNgIIIAIoAhQEQAJAIAIoAhRBAkcNACACKAIQQQNHDQAgAkECNgIQIAIoAhhBAjYCCAsCQCACKAIUIAIoAhBGDQAgAigCEEEBRg0AIAJBBTYCHAwCCwsgAiACKAIQNgIcCyACKAIcC2oBAX8jAEEQayIBIAA2AgwgASgCDEIANwMAIAEoAgxBADYCCCABKAIMQn83AxAgASgCDEEANgIsIAEoAgxBfzYCKCABKAIMQgA3AxggASgCDEIANwMgIAEoAgxBADsBMCABKAIMQQA7ATILUgECf0GQlwEoAgAiASAAQQNqQXxxIgJqIQACQCACQQAgACABTRsNACAAPwBBEHRLBEAgABATRQ0BC0GQlwEgADYCACABDwtBtJsBQTA2AgBBfwuNBQEDfyMAQRBrIgEkACABIAA2AgwgASgCDARAIAEoAgwoAgAEQCABKAIMKAIAEDEaIAEoAgwoAgAQGwsgASgCDCgCHBAVIAEoAgwoAiAQJSABKAIMKAIkECUgASgCDCgCUCECIwBBEGsiACQAIAAgAjYCDCAAKAIMBEAgACgCDCgCEARAIABBADYCCANAIAAoAgggACgCDCgCAEkEQCAAKAIMKAIQIAAoAghBAnRqKAIABEAgACgCDCgCECAAKAIIQQJ0aigCACEDIwBBEGsiAiQAIAIgAzYCDANAIAIoAgwEQCACIAIoAgwoAhg2AgggAigCDBAVIAIgAigCCDYCDAwBCwsgAkEQaiQACyAAIAAoAghBAWo2AggMAQsLIAAoAgwoAhAQFQsgACgCDBAVCyAAQRBqJAAgASgCDCgCQARAIAFCADcDAANAIAEpAwAgASgCDCkDMFQEQCABKAIMKAJAIAEpAwCnQQR0ahBiIAEgASkDAEIBfDcDAAwBCwsgASgCDCgCQBAVCyABQgA3AwADQCABKQMAIAEoAgwoAkStVARAIAEoAgwoAkwgASkDAKdBAnRqKAIAIQIjAEEQayIAJAAgACACNgIMIAAoAgxBAToAKAJ/IwBBEGsiAiAAKAIMQQxqNgIMIAIoAgwoAgBFCwRAIAAoAgxBDGpBCEEAEBQLIABBEGokACABIAEpAwBCAXw3AwAMAQsLIAEoAgwoAkwQFSABKAIMKAJUIQIjAEEQayIAJAAgACACNgIMIAAoAgwEQCAAKAIMKAIIBEAgACgCDCgCDCAAKAIMKAIIEQIACyAAKAIMEBULIABBEGokACABKAIMQQhqEDcgASgCDBAVCyABQRBqJAALjw4BAX8jAEEQayIDJAAgAyAANgIMIAMgATYCCCADIAI2AgQgAygCCCEBIAMoAgQhAiMAQSBrIgAgAygCDDYCGCAAIAE2AhQgACACNgIQIAAgACgCGEEQdjYCDCAAIAAoAhhB//8DcTYCGAJAIAAoAhBBAUYEQCAAIAAoAhQtAAAgACgCGGo2AhggACgCGEHx/wNPBEAgACAAKAIYQfH/A2s2AhgLIAAgACgCGCAAKAIMajYCDCAAKAIMQfH/A08EQCAAIAAoAgxB8f8DazYCDAsgACAAKAIYIAAoAgxBEHRyNgIcDAELIAAoAhRFBEAgAEEBNgIcDAELIAAoAhBBEEkEQANAIAAgACgCECIBQQFrNgIQIAEEQCAAIAAoAhQiAUEBajYCFCAAIAEtAAAgACgCGGo2AhggACAAKAIYIAAoAgxqNgIMDAELCyAAKAIYQfH/A08EQCAAIAAoAhhB8f8DazYCGAsgACAAKAIMQfH/A3A2AgwgACAAKAIYIAAoAgxBEHRyNgIcDAELA0AgACgCEEGwK08EQCAAIAAoAhBBsCtrNgIQIABB2wI2AggDQCAAIAAoAhQtAAAgACgCGGo2AhggACAAKAIYIAAoAgxqNgIMIAAgACgCFC0AASAAKAIYajYCGCAAIAAoAhggACgCDGo2AgwgACAAKAIULQACIAAoAhhqNgIYIAAgACgCGCAAKAIMajYCDCAAIAAoAhQtAAMgACgCGGo2AhggACAAKAIYIAAoAgxqNgIMIAAgACgCFC0ABCAAKAIYajYCGCAAIAAoAhggACgCDGo2AgwgACAAKAIULQAFIAAoAhhqNgIYIAAgACgCGCAAKAIMajYCDCAAIAAoAhQtAAYgACgCGGo2AhggACAAKAIYIAAoAgxqNgIMIAAgACgCFC0AByAAKAIYajYCGCAAIAAoAhggACgCDGo2AgwgACAAKAIULQAIIAAoAhhqNgIYIAAgACgCGCAAKAIMajYCDCAAIAAoAhQtAAkgACgCGGo2AhggACAAKAIYIAAoAgxqNgIMIAAgACgCFC0ACiAAKAIYajYCGCAAIAAoAhggACgCDGo2AgwgACAAKAIULQALIAAoAhhqNgIYIAAgACgCGCAAKAIMajYCDCAAIAAoAhQtAAwgACgCGGo2AhggACAAKAIYIAAoAgxqNgIMIAAgACgCFC0ADSAAKAIYajYCGCAAIAAoAhggACgCDGo2AgwgACAAKAIULQAOIAAoAhhqNgIYIAAgACgCGCAAKAIMajYCDCAAIAAoAhQtAA8gACgCGGo2AhggACAAKAIYIAAoAgxqNgIMIAAgACgCFEEQajYCFCAAIAAoAghBAWsiATYCCCABDQALIAAgACgCGEHx/wNwNgIYIAAgACgCDEHx/wNwNgIMDAELCyAAKAIQBEADQCAAKAIQQRBPBEAgACAAKAIQQRBrNgIQIAAgACgCFC0AACAAKAIYajYCGCAAIAAoAhggACgCDGo2AgwgACAAKAIULQABIAAoAhhqNgIYIAAgACgCGCAAKAIMajYCDCAAIAAoAhQtAAIgACgCGGo2AhggACAAKAIYIAAoAgxqNgIMIAAgACgCFC0AAyAAKAIYajYCGCAAIAAoAhggACgCDGo2AgwgACAAKAIULQAEIAAoAhhqNgIYIAAgACgCGCAAKAIMajYCDCAAIAAoAhQtAAUgACgCGGo2AhggACAAKAIYIAAoAgxqNgIMIAAgACgCFC0ABiAAKAIYajYCGCAAIAAoAhggACgCDGo2AgwgACAAKAIULQAHIAAoAhhqNgIYIAAgACgCGCAAKAIMajYCDCAAIAAoAhQtAAggACgCGGo2AhggACAAKAIYIAAoAgxqNgIMIAAgACgCFC0ACSAAKAIYajYCGCAAIAAoAhggACgCDGo2AgwgACAAKAIULQAKIAAoAhhqNgIYIAAgACgCGCAAKAIMajYCDCAAIAAoAhQtAAsgACgCGGo2AhggACAAKAIYIAAoAgxqNgIMIAAgACgCFC0ADCAAKAIYajYCGCAAIAAoAhggACgCDGo2AgwgACAAKAIULQANIAAoAhhqNgIYIAAgACgCGCAAKAIMajYCDCAAIAAoAhQtAA4gACgCGGo2AhggACAAKAIYIAAoAgxqNgIMIAAgACgCFC0ADyAAKAIYajYCGCAAIAAoAhggACgCDGo2AgwgACAAKAIUQRBqNgIUDAELCwNAIAAgACgCECIBQQFrNgIQIAEEQCAAIAAoAhQiAUEBajYCFCAAIAEtAAAgACgCGGo2AhggACAAKAIYIAAoAgxqNgIMDAELCyAAIAAoAhhB8f8DcDYCGCAAIAAoAgxB8f8DcDYCDAsgACAAKAIYIAAoAgxBEHRyNgIcCyAAKAIcIQAgA0EQaiQAIAALhAEBAX8jAEEQayIBJAAgASAANgIIIAFB2AAQGCIANgIEAkAgAEUEQCABQQA2AgwMAQsCQCABKAIIBEAgASgCBCABKAIIQdgAEBkaDAELIAEoAgQQTwsgASgCBEEANgIAIAEoAgRBAToABSABIAEoAgQ2AgwLIAEoAgwhACABQRBqJAAgAAtvAQF/IwBBIGsiAyQAIAMgADYCGCADIAE2AhQgAyACNgIQIAMgAygCGCADKAIQrRAeNgIMAkAgAygCDEUEQCADQX82AhwMAQsgAygCDCADKAIUIAMoAhAQGRogA0EANgIcCyADKAIcGiADQSBqJAALogEBAX8jAEEgayIEJAAgBCAANgIYIAQgATcDECAEIAI2AgwgBCADNgIIIAQgBCgCDCAEKQMQECkiADYCBAJAIABFBEAgBCgCCEEOQQAQFCAEQQA2AhwMAQsgBCgCGCAEKAIEKAIEIAQpAxAgBCgCCBBhQQBIBEAgBCgCBBAWIARBADYCHAwBCyAEIAQoAgQ2AhwLIAQoAhwhACAEQSBqJAAgAAugAQEBfyMAQSBrIgMkACADIAA2AhQgAyABNgIQIAMgAjcDCCADIAMoAhA2AgQCQCADKQMIQghUBEAgA0J/NwMYDAELIwBBEGsiACADKAIUNgIMIAAoAgwoAgAhACADKAIEIAA2AgAjAEEQayIAIAMoAhQ2AgwgACgCDCgCBCEAIAMoAgQgADYCBCADQgg3AxgLIAMpAxghAiADQSBqJAAgAgs/AQF/IwBBEGsiAiAANgIMIAIgATYCCCACKAIMBEAgAigCDCACKAIIKAIANgIAIAIoAgwgAigCCCgCBDYCBAsLgwECA38BfgJAIABCgICAgBBUBEAgACEFDAELA0AgAUEBayIBIAAgAEIKgCIFQgp+fadBMHI6AAAgAEL/////nwFWIQIgBSEAIAINAAsLIAWnIgIEQANAIAFBAWsiASACIAJBCm4iA0EKbGtBMHI6AAAgAkEJSyEEIAMhAiAEDQALCyABC7wCAQF/IwBBIGsiBCQAIAQgADYCGCAEIAE3AxAgBCACNgIMIAQgAzYCCCAEKAIIRQRAIAQgBCgCGEEIajYCCAsCQCAEKQMQIAQoAhgpAzBaBEAgBCgCCEESQQAQFCAEQQA2AhwMAQsCQCAEKAIMQQhxRQRAIAQoAhgoAkAgBCkDEKdBBHRqKAIEDQELIAQoAhgoAkAgBCkDEKdBBHRqKAIARQRAIAQoAghBEkEAEBQgBEEANgIcDAILAkAgBCgCGCgCQCAEKQMQp0EEdGotAAxBAXFFDQAgBCgCDEEIcQ0AIAQoAghBF0EAEBQgBEEANgIcDAILIAQgBCgCGCgCQCAEKQMQp0EEdGooAgA2AhwMAQsgBCAEKAIYKAJAIAQpAxCnQQR0aigCBDYCHAsgBCgCHCEAIARBIGokACAAC9kIAQJ/IwBBIGsiBCQAIAQgADYCGCAEIAE2AhQgBCACNgIQIAQgAzYCDAJAIAQoAhhFBEAgBCgCFARAIAQoAhRBADYCAAsgBEGQ2QA2AhwMAQsgBCgCEEHAAHFFBEAgBCgCGCgCCEUEQCAEKAIYQQAQOhoLAkACQAJAIAQoAhBBgAFxRQ0AIAQoAhgoAghBAUYNACAEKAIYKAIIQQJHDQELIAQoAhgoAghBBEcNAQsgBCgCGCgCDEUEQCAEKAIYKAIAIQEgBCgCGC8BBCECIAQoAhhBEGohAyAEKAIMIQUjAEEwayIAJAAgACABNgIoIAAgAjYCJCAAIAM2AiAgACAFNgIcIAAgACgCKDYCGAJAIAAoAiRFBEAgACgCIARAIAAoAiBBADYCAAsgAEEANgIsDAELIABBATYCECAAQQA2AgwDQCAAKAIMIAAoAiRJBEAjAEEQayIBIAAoAhggACgCDGotAABBAXRBkNUAai8BADYCCAJAIAEoAghBgAFJBEAgAUEBNgIMDAELIAEoAghBgBBJBEAgAUECNgIMDAELIAEoAghBgIAESQRAIAFBAzYCDAwBCyABQQQ2AgwLIAAgASgCDCAAKAIQajYCECAAIAAoAgxBAWo2AgwMAQsLIAAgACgCEBAYIgE2AhQgAUUEQCAAKAIcQQ5BABAUIABBADYCLAwBCyAAQQA2AgggAEEANgIMA0AgACgCDCAAKAIkSQRAIAAoAhQgACgCCGohAiMAQRBrIgEgACgCGCAAKAIMai0AAEEBdEGQ1QBqLwEANgIIIAEgAjYCBAJAIAEoAghBgAFJBEAgASgCBCABKAIIOgAAIAFBATYCDAwBCyABKAIIQYAQSQRAIAEoAgQgASgCCEEGdkEfcUHAAXI6AAAgASgCBCABKAIIQT9xQYABcjoAASABQQI2AgwMAQsgASgCCEGAgARJBEAgASgCBCABKAIIQQx2QQ9xQeABcjoAACABKAIEIAEoAghBBnZBP3FBgAFyOgABIAEoAgQgASgCCEE/cUGAAXI6AAIgAUEDNgIMDAELIAEoAgQgASgCCEESdkEHcUHwAXI6AAAgASgCBCABKAIIQQx2QT9xQYABcjoAASABKAIEIAEoAghBBnZBP3FBgAFyOgACIAEoAgQgASgCCEE/cUGAAXI6AAMgAUEENgIMCyAAIAEoAgwgACgCCGo2AgggACAAKAIMQQFqNgIMDAELCyAAKAIUIAAoAhBBAWtqQQA6AAAgACgCIARAIAAoAiAgACgCEEEBazYCAAsgACAAKAIUNgIsCyAAKAIsIQEgAEEwaiQAIAEhACAEKAIYIAA2AgwgAEUEQCAEQQA2AhwMBAsLIAQoAhQEQCAEKAIUIAQoAhgoAhA2AgALIAQgBCgCGCgCDDYCHAwCCwsgBCgCFARAIAQoAhQgBCgCGC8BBDYCAAsgBCAEKAIYKAIANgIcCyAEKAIcIQAgBEEgaiQAIAALOQEBfyMAQRBrIgEgADYCDEEAIQAgASgCDC0AAEEBcQR/IAEoAgwpAxAgASgCDCkDCFEFQQALQQFxC5wIAQt/IABFBEAgARAYDwsgAUFATwRAQbSbAUEwNgIAQQAPCwJ/QRAgAUELakF4cSABQQtJGyEGIABBCGsiBSgCBCIJQXhxIQQCQCAJQQNxRQRAQQAgBkGAAkkNAhogBkEEaiAETQRAIAUhAiAEIAZrQZifASgCAEEBdE0NAgtBAAwCCyAEIAVqIQcCQCAEIAZPBEAgBCAGayIDQRBJDQEgBSAJQQFxIAZyQQJyNgIEIAUgBmoiAiADQQNyNgIEIAcgBygCBEEBcjYCBCACIAMQrAEMAQsgB0HQmwEoAgBGBEBBxJsBKAIAIARqIgQgBk0NAiAFIAlBAXEgBnJBAnI2AgQgBSAGaiIDIAQgBmsiAkEBcjYCBEHEmwEgAjYCAEHQmwEgAzYCAAwBCyAHQcybASgCAEYEQEHAmwEoAgAgBGoiAyAGSQ0CAkAgAyAGayICQRBPBEAgBSAJQQFxIAZyQQJyNgIEIAUgBmoiBCACQQFyNgIEIAMgBWoiAyACNgIAIAMgAygCBEF+cTYCBAwBCyAFIAlBAXEgA3JBAnI2AgQgAyAFaiICIAIoAgRBAXI2AgRBACECQQAhBAtBzJsBIAQ2AgBBwJsBIAI2AgAMAQsgBygCBCIDQQJxDQEgA0F4cSAEaiIKIAZJDQEgCiAGayEMAkAgA0H/AU0EQCAHKAIIIgQgA0EDdiICQQN0QeCbAWpGGiAEIAcoAgwiA0YEQEG4mwFBuJsBKAIAQX4gAndxNgIADAILIAQgAzYCDCADIAQ2AggMAQsgBygCGCELAkAgByAHKAIMIghHBEAgBygCCCICQcibASgCAEkaIAIgCDYCDCAIIAI2AggMAQsCQCAHQRRqIgQoAgAiAg0AIAdBEGoiBCgCACICDQBBACEIDAELA0AgBCEDIAIiCEEUaiIEKAIAIgINACAIQRBqIQQgCCgCECICDQALIANBADYCAAsgC0UNAAJAIAcgBygCHCIDQQJ0QeidAWoiAigCAEYEQCACIAg2AgAgCA0BQbybAUG8mwEoAgBBfiADd3E2AgAMAgsgC0EQQRQgCygCECAHRhtqIAg2AgAgCEUNAQsgCCALNgIYIAcoAhAiAgRAIAggAjYCECACIAg2AhgLIAcoAhQiAkUNACAIIAI2AhQgAiAINgIYCyAMQQ9NBEAgBSAJQQFxIApyQQJyNgIEIAUgCmoiAiACKAIEQQFyNgIEDAELIAUgCUEBcSAGckECcjYCBCAFIAZqIgMgDEEDcjYCBCAFIApqIgIgAigCBEEBcjYCBCADIAwQrAELIAUhAgsgAgsiAgRAIAJBCGoPCyABEBgiBUUEQEEADwsgBSAAQXxBeCAAQQRrKAIAIgJBA3EbIAJBeHFqIgIgASABIAJLGxAZGiAAEBUgBQvvAgEBfyMAQRBrIgEkACABIAA2AggCQCABKAIILQAoQQFxBEAgAUF/NgIMDAELIAEoAggoAiRBA0YEQCABKAIIQQxqQRdBABAUIAFBfzYCDAwBCwJAIAEoAggoAiAEQAJ/IwBBEGsiACABKAIINgIMIAAoAgwpAxhCwACDUAsEQCABKAIIQQxqQR1BABAUIAFBfzYCDAwDCwwBCyABKAIIKAIABEAgASgCCCgCABBJQQBIBEAgASgCCEEMaiABKAIIKAIAEBcgAUF/NgIMDAMLCyABKAIIQQBCAEEAECFCAFMEQCABKAIIKAIABEAgASgCCCgCABAxGgsgAUF/NgIMDAILCyABKAIIQQA6ADQgASgCCEEAOgA1IwBBEGsiACABKAIIQQxqNgIMIAAoAgwEQCAAKAIMQQA2AgAgACgCDEEANgIECyABKAIIIgAgACgCIEEBajYCICABQQA2AgwLIAEoAgwhACABQRBqJAAgAAt1AgF/AX4jAEEQayIBJAAgASAANgIEAkAgASgCBC0AKEEBcQRAIAFCfzcDCAwBCyABKAIEKAIgRQRAIAEoAgRBDGpBEkEAEBQgAUJ/NwMIDAELIAEgASgCBEEAQgBBBxAhNwMICyABKQMIIQIgAUEQaiQAIAILnQEBAX8jAEEQayIBIAA2AggCQAJAAkAgASgCCEUNACABKAIIKAIgRQ0AIAEoAggoAiQNAQsgAUEBNgIMDAELIAEgASgCCCgCHDYCBAJAAkAgASgCBEUNACABKAIEKAIAIAEoAghHDQAgASgCBCgCBEG0/gBJDQAgASgCBCgCBEHT/gBNDQELIAFBATYCDAwBCyABQQA2AgwLIAEoAgwLgAEBA38jAEEQayICIAA2AgwgAiABNgIIIAIoAghBCHYhASACKAIMKAIIIQMgAigCDCIEKAIUIQAgBCAAQQFqNgIUIAAgA2ogAToAACACKAIIQf8BcSEBIAIoAgwoAgghAyACKAIMIgIoAhQhACACIABBAWo2AhQgACADaiABOgAAC5kFAQF/IwBBQGoiBCQAIAQgADYCOCAEIAE3AzAgBCACNgIsIAQgAzYCKCAEQcgAEBgiADYCJAJAIABFBEAgBEEANgI8DAELIAQoAiRCADcDOCAEKAIkQgA3AxggBCgCJEIANwMwIAQoAiRBADYCACAEKAIkQQA2AgQgBCgCJEIANwMIIAQoAiRCADcDECAEKAIkQQA2AiggBCgCJEIANwMgAkAgBCkDMFAEQEEIEBghACAEKAIkIAA2AgQgAEUEQCAEKAIkEBUgBCgCKEEOQQAQFCAEQQA2AjwMAwsgBCgCJCgCBEIANwMADAELIAQoAiQgBCkDMEEAEMEBQQFxRQRAIAQoAihBDkEAEBQgBCgCJBAzIARBADYCPAwCCyAEQgA3AwggBEIANwMYIARCADcDEANAIAQpAxggBCkDMFQEQCAEKAI4IAQpAxinQQR0aikDCFBFBEAgBCgCOCAEKQMYp0EEdGooAgBFBEAgBCgCKEESQQAQFCAEKAIkEDMgBEEANgI8DAULIAQoAiQoAgAgBCkDEKdBBHRqIAQoAjggBCkDGKdBBHRqKAIANgIAIAQoAiQoAgAgBCkDEKdBBHRqIAQoAjggBCkDGKdBBHRqKQMINwMIIAQoAiQoAgQgBCkDGKdBA3RqIAQpAwg3AwAgBCAEKAI4IAQpAxinQQR0aikDCCAEKQMIfDcDCCAEIAQpAxBCAXw3AxALIAQgBCkDGEIBfDcDGAwBCwsgBCgCJCAEKQMQNwMIIAQoAiQgBCgCLAR+QgAFIAQoAiQpAwgLNwMYIAQoAiQoAgQgBCgCJCkDCKdBA3RqIAQpAwg3AwAgBCgCJCAEKQMINwMwCyAEIAQoAiQ2AjwLIAQoAjwhACAEQUBrJAAgAAueAQEBfyMAQSBrIgQkACAEIAA2AhggBCABNwMQIAQgAjYCDCAEIAM2AgggBCAEKAIYIAQpAxAgBCgCDCAEKAIIEEUiADYCBAJAIABFBEAgBEEANgIcDAELIAQgBCgCBCgCMEEAIAQoAgwgBCgCCBBGIgA2AgAgAEUEQCAEQQA2AhwMAQsgBCAEKAIANgIcCyAEKAIcIQAgBEEgaiQAIAAL8QEBAX8jAEEQayIBIAA2AgwgASgCDEEANgIAIAEoAgxBADoABCABKAIMQQA6AAUgASgCDEEBOgAGIAEoAgxBvwY7AQggASgCDEEKOwEKIAEoAgxBADsBDCABKAIMQX82AhAgASgCDEEANgIUIAEoAgxBADYCGCABKAIMQgA3AyAgASgCDEIANwMoIAEoAgxBADYCMCABKAIMQQA2AjQgASgCDEEANgI4IAEoAgxBADYCPCABKAIMQQA7AUAgASgCDEGAgNiNeDYCRCABKAIMQgA3A0ggASgCDEEAOwFQIAEoAgxBADsBUiABKAIMQQA2AlQL0hMBAX8jAEGwAWsiAyQAIAMgADYCqAEgAyABNgKkASADIAI2AqABIANBADYCkAEgAyADKAKkASgCMEEAEDo2ApQBIAMgAygCpAEoAjhBABA6NgKYAQJAAkACQAJAIAMoApQBQQJGBEAgAygCmAFBAUYNAQsgAygClAFBAUYEQCADKAKYAUECRg0BCyADKAKUAUECRw0BIAMoApgBQQJHDQELIAMoAqQBIgAgAC8BDEGAEHI7AQwMAQsgAygCpAEiACAALwEMQf/vA3E7AQwgAygClAFBAkYEQCADQfXgASADKAKkASgCMCADKAKoAUEIahCCATYCkAEgAygCkAFFBEAgA0F/NgKsAQwDCwsCQCADKAKgAUGAAnENACADKAKYAUECRw0AIANB9cYBIAMoAqQBKAI4IAMoAqgBQQhqEIIBNgJIIAMoAkhFBEAgAygCkAEQIyADQX82AqwBDAMLIAMoAkggAygCkAE2AgAgAyADKAJINgKQAQsLAkAgAygCpAEvAVJFBEAgAygCpAEiACAALwEMQf7/A3E7AQwMAQsgAygCpAEiACAALwEMQQFyOwEMCyADIAMoAqQBIAMoAqABEF5BAXE6AIYBIAMgAygCoAFBgApxQYAKRwR/IAMtAIYBBUEBC0EBcToAhwEgAwJ/QQEgAygCpAEvAVJBgQJGDQAaQQEgAygCpAEvAVJBggJGDQAaIAMoAqQBLwFSQYMCRgtBAXE6AIUBIAMtAIcBQQFxBEAgAyADQSBqQhwQKTYCHCADKAIcRQRAIAMoAqgBQQhqQQ5BABAUIAMoApABECMgA0F/NgKsAQwCCwJAIAMoAqABQYACcQRAAkAgAygCoAFBgAhxDQAgAygCpAEpAyBC/////w9WDQAgAygCpAEpAyhC/////w9YDQILIAMoAhwgAygCpAEpAygQLSADKAIcIAMoAqQBKQMgEC0MAQsCQAJAIAMoAqABQYAIcQ0AIAMoAqQBKQMgQv////8PVg0AIAMoAqQBKQMoQv////8PVg0AIAMoAqQBKQNIQv////8PWA0BCyADKAKkASkDKEL/////D1oEQCADKAIcIAMoAqQBKQMoEC0LIAMoAqQBKQMgQv////8PWgRAIAMoAhwgAygCpAEpAyAQLQsgAygCpAEpA0hC/////w9aBEAgAygCHCADKAKkASkDSBAtCwsLAn8jAEEQayIAIAMoAhw2AgwgACgCDC0AAEEBcUULBEAgAygCqAFBCGpBFEEAEBQgAygCHBAWIAMoApABECMgA0F/NgKsAQwCCyADQQECfyMAQRBrIgAgAygCHDYCDAJ+IAAoAgwtAABBAXEEQCAAKAIMKQMQDAELQgALp0H//wNxCyADQSBqQYAGEFE2AowBIAMoAhwQFiADKAKMASADKAKQATYCACADIAMoAowBNgKQAQsgAy0AhQFBAXEEQCADIANBFWpCBxApNgIQIAMoAhBFBEAgAygCqAFBCGpBDkEAEBQgAygCkAEQIyADQX82AqwBDAILIAMoAhBBAhAfIAMoAhBBvRJBAhBAIAMoAhAgAygCpAEvAVJB/wFxEI4BIAMoAhAgAygCpAEoAhBB//8DcRAfAn8jAEEQayIAIAMoAhA2AgwgACgCDC0AAEEBcUULBEAgAygCqAFBCGpBFEEAEBQgAygCEBAWIAMoApABECMgA0F/NgKsAQwCCyADQYGyAkEHIANBFWpBgAYQUTYCDCADKAIQEBYgAygCDCADKAKQATYCACADIAMoAgw2ApABCyADIANB0ABqQi4QKSIANgJMIABFBEAgAygCqAFBCGpBDkEAEBQgAygCkAEQIyADQX82AqwBDAELIAMoAkxB8RJB9hIgAygCoAFBgAJxG0EEEEAgAygCoAFBgAJxRQRAIAMoAkwgAy0AhgFBAXEEf0EtBSADKAKkAS8BCAtB//8DcRAfCyADKAJMIAMtAIYBQQFxBH9BLQUgAygCpAEvAQoLQf//A3EQHyADKAJMIAMoAqQBLwEMEB8CQCADLQCFAUEBcQRAIAMoAkxB4wAQHwwBCyADKAJMIAMoAqQBKAIQQf//A3EQHwsgAygCpAEoAhQgA0GeAWogA0GcAWoQgQEgAygCTCADLwGeARAfIAMoAkwgAy8BnAEQHwJAAkAgAy0AhQFBAXFFDQAgAygCpAEpAyhCFFoNACADKAJMQQAQIAwBCyADKAJMIAMoAqQBKAIYECALAkACQCADKAKgAUGAAnFBgAJHDQAgAygCpAEpAyBC/////w9UBEAgAygCpAEpAyhC/////w9UDQELIAMoAkxBfxAgIAMoAkxBfxAgDAELAkAgAygCpAEpAyBC/////w9UBEAgAygCTCADKAKkASkDIKcQIAwBCyADKAJMQX8QIAsCQCADKAKkASkDKEL/////D1QEQCADKAJMIAMoAqQBKQMopxAgDAELIAMoAkxBfxAgCwsgAygCTCADKAKkASgCMBBTQf//A3EQHyADIAMoAqQBKAI0IAMoAqABEIYBQf//A3EgAygCkAFBgAYQhgFB//8DcWo2AogBIAMoAkwgAygCiAFB//8DcRAfIAMoAqABQYACcUUEQCADKAJMIAMoAqQBKAI4EFNB//8DcRAfIAMoAkwgAygCpAEoAjxB//8DcRAfIAMoAkwgAygCpAEvAUAQHyADKAJMIAMoAqQBKAJEECACQCADKAKkASkDSEL/////D1QEQCADKAJMIAMoAqQBKQNIpxAgDAELIAMoAkxBfxAgCwsCfyMAQRBrIgAgAygCTDYCDCAAKAIMLQAAQQFxRQsEQCADKAKoAUEIakEUQQAQFCADKAJMEBYgAygCkAEQIyADQX82AqwBDAELIAMoAqgBIANB0ABqAn4jAEEQayIAIAMoAkw2AgwCfiAAKAIMLQAAQQFxBEAgACgCDCkDEAwBC0IACwsQNUEASARAIAMoAkwQFiADKAKQARAjIANBfzYCrAEMAQsgAygCTBAWIAMoAqQBKAIwBEAgAygCqAEgAygCpAEoAjAQigFBAEgEQCADKAKQARAjIANBfzYCrAEMAgsLIAMoApABBEAgAygCqAEgAygCkAFBgAYQhQFBAEgEQCADKAKQARAjIANBfzYCrAEMAgsLIAMoApABECMgAygCpAEoAjQEQCADKAKoASADKAKkASgCNCADKAKgARCFAUEASARAIANBfzYCrAEMAgsLIAMoAqABQYACcUUEQCADKAKkASgCOARAIAMoAqgBIAMoAqQBKAI4EIoBQQBIBEAgA0F/NgKsAQwDCwsLIAMgAy0AhwFBAXE2AqwBCyADKAKsASEAIANBsAFqJAAgAAvgAgEBfyMAQSBrIgQkACAEIAA7ARogBCABOwEYIAQgAjYCFCAEIAM2AhAgBEEQEBgiADYCDAJAIABFBEAgBEEANgIcDAELIAQoAgxBADYCACAEKAIMIAQoAhA2AgQgBCgCDCAELwEaOwEIIAQoAgwgBC8BGDsBCgJAIAQvARgEQCAEKAIUIQEgBC8BGCECIwBBIGsiACQAIAAgATYCGCAAIAI2AhQgAEEANgIQAkAgACgCFEUEQCAAQQA2AhwMAQsgACAAKAIUEBg2AgwgACgCDEUEQCAAKAIQQQ5BABAUIABBADYCHAwBCyAAKAIMIAAoAhggACgCFBAZGiAAIAAoAgw2AhwLIAAoAhwhASAAQSBqJAAgASEAIAQoAgwgADYCDCAARQRAIAQoAgwQFSAEQQA2AhwMAwsMAQsgBCgCDEEANgIMCyAEIAQoAgw2AhwLIAQoAhwhACAEQSBqJAAgAAuMAwEBfyMAQSBrIgQkACAEIAA2AhggBCABOwEWIAQgAjYCECAEIAM2AgwCQCAELwEWRQRAIARBADYCHAwBCwJAAkACQAJAIAQoAhBBgDBxIgAEQCAAQYAQRg0BIABBgCBGDQIMAwsgBEEANgIEDAMLIARBAjYCBAwCCyAEQQQ2AgQMAQsgBCgCDEESQQAQFCAEQQA2AhwMAQsgBEEUEBgiADYCCCAARQRAIAQoAgxBDkEAEBQgBEEANgIcDAELIAQvARZBAWoQGCEAIAQoAgggADYCACAARQRAIAQoAggQFSAEQQA2AhwMAQsgBCgCCCgCACAEKAIYIAQvARYQGRogBCgCCCgCACAELwEWakEAOgAAIAQoAgggBC8BFjsBBCAEKAIIQQA2AgggBCgCCEEANgIMIAQoAghBADYCECAEKAIEBEAgBCgCCCAEKAIEEDpBBUYEQCAEKAIIECUgBCgCDEESQQAQFCAEQQA2AhwMAgsLIAQgBCgCCDYCHAsgBCgCHCEAIARBIGokACAACzcBAX8jAEEQayIBIAA2AggCQCABKAIIRQRAIAFBADsBDgwBCyABIAEoAggvAQQ7AQ4LIAEvAQ4LQwEDfwJAIAJFDQADQCAALQAAIgQgAS0AACIFRgRAIAFBAWohASAAQQFqIQAgAkEBayICDQEMAgsLIAQgBWshAwsgAwuRAQEFfyAAKAJMQQBOIQMgACgCAEEBcSIERQRAIAAoAjQiAQRAIAEgACgCODYCOAsgACgCOCICBEAgAiABNgI0CyAAQaygASgCAEYEQEGsoAEgAjYCAAsLIAAQpQEhASAAIAAoAgwRAAAhAiAAKAJgIgUEQCAFEBULAkAgBEUEQCAAEBUMAQsgA0UNAAsgASACcgv5AQEBfyMAQSBrIgIkACACIAA2AhwgAiABOQMQAkAgAigCHEUNACACAnwCfCACKwMQRAAAAAAAAAAAZARAIAIrAxAMAQtEAAAAAAAAAAALRAAAAAAAAPA/YwRAAnwgAisDEEQAAAAAAAAAAGQEQCACKwMQDAELRAAAAAAAAAAACwwBC0QAAAAAAADwPwsgAigCHCsDKCACKAIcKwMgoaIgAigCHCsDIKA5AwggAigCHCsDECACKwMIIAIoAhwrAxihY0UNACACKAIcKAIAIAIrAwggAigCHCgCDCACKAIcKAIEERYAIAIoAhwgAisDCDkDGAsgAkEgaiQAC+EFAgJ/AX4jAEEwayIEJAAgBCAANgIkIAQgATYCICAEIAI2AhwgBCADNgIYAkAgBCgCJEUEQCAEQn83AygMAQsgBCgCIEUEQCAEKAIYQRJBABAUIARCfzcDKAwBCyAEKAIcQYMgcQRAIARBFUEWIAQoAhxBAXEbNgIUIARCADcDAANAIAQpAwAgBCgCJCkDMFQEQCAEIAQoAiQgBCkDACAEKAIcIAQoAhgQTjYCECAEKAIQBEAgBCgCHEECcQRAIAQCfyAEKAIQIgEQK0EBaiEAA0BBACAARQ0BGiABIABBAWsiAGoiAi0AAEEvRw0ACyACCzYCDCAEKAIMBEAgBCAEKAIMQQFqNgIQCwsgBCgCICAEKAIQIAQoAhQRAwBFBEAjAEEQayIAIAQoAhg2AgwgACgCDARAIAAoAgxBADYCACAAKAIMQQA2AgQLIAQgBCkDADcDKAwFCwsgBCAEKQMAQgF8NwMADAELCyAEKAIYQQlBABAUIARCfzcDKAwBCyAEKAIkKAJQIQEgBCgCICECIAQoAhwhAyAEKAIYIQUjAEEwayIAJAAgACABNgIkIAAgAjYCICAAIAM2AhwgACAFNgIYAkACQCAAKAIkBEAgACgCIA0BCyAAKAIYQRJBABAUIABCfzcDKAwBCyAAKAIkKQMIQgBSBEAgACAAKAIgEHQ2AhQgACAAKAIUIAAoAiQoAgBwNgIQIAAgACgCJCgCECAAKAIQQQJ0aigCADYCDANAAkAgACgCDEUNACAAKAIgIAAoAgwoAgAQWgRAIAAgACgCDCgCGDYCDAwCBSAAKAIcQQhxBEAgACgCDCkDCEJ/UgRAIAAgACgCDCkDCDcDKAwGCwwCCyAAKAIMKQMQQn9SBEAgACAAKAIMKQMQNwMoDAULCwsLCyAAKAIYQQlBABAUIABCfzcDKAsgACkDKCEGIABBMGokACAEIAY3AygLIAQpAyghBiAEQTBqJAAgBgvUAwEBfyMAQSBrIgMkACADIAA2AhggAyABNgIUIAMgAjYCEAJAAkAgAygCGARAIAMoAhQNAQsgAygCEEESQQAQFCADQQA6AB8MAQsgAygCGCkDCEIAUgRAIAMgAygCFBB0NgIMIAMgAygCDCADKAIYKAIAcDYCCCADQQA2AgAgAyADKAIYKAIQIAMoAghBAnRqKAIANgIEA0AgAygCBARAAkAgAygCBCgCHCADKAIMRw0AIAMoAhQgAygCBCgCABBaDQACQCADKAIEKQMIQn9RBEACQCADKAIABEAgAygCACADKAIEKAIYNgIYDAELIAMoAhgoAhAgAygCCEECdGogAygCBCgCGDYCAAsgAygCBBAVIAMoAhgiACAAKQMIQgF9NwMIAkAgAygCGCIAKQMIuiAAKAIAuER7FK5H4XqEP6JjRQ0AIAMoAhgoAgBBgAJNDQAgAygCGCADKAIYKAIAQQF2IAMoAhAQWUEBcUUEQCADQQA6AB8MCAsLDAELIAMoAgRCfzcDEAsgA0EBOgAfDAQLIAMgAygCBDYCACADIAMoAgQoAhg2AgQMAQsLCyADKAIQQQlBABAUIANBADoAHwsgAy0AH0EBcSEAIANBIGokACAAC98CAQF/IwBBMGsiAyQAIAMgADYCKCADIAE2AiQgAyACNgIgAkAgAygCJCADKAIoKAIARgRAIANBAToALwwBCyADIAMoAiRBBBB2IgA2AhwgAEUEQCADKAIgQQ5BABAUIANBADoALwwBCyADKAIoKQMIQgBSBEAgA0EANgIYA0AgAygCGCADKAIoKAIAT0UEQCADIAMoAigoAhAgAygCGEECdGooAgA2AhQDQCADKAIUBEAgAyADKAIUKAIYNgIQIAMgAygCFCgCHCADKAIkcDYCDCADKAIUIAMoAhwgAygCDEECdGooAgA2AhggAygCHCADKAIMQQJ0aiADKAIUNgIAIAMgAygCEDYCFAwBCwsgAyADKAIYQQFqNgIYDAELCwsgAygCKCgCEBAVIAMoAiggAygCHDYCECADKAIoIAMoAiQ2AgAgA0EBOgAvCyADLQAvQQFxIQAgA0EwaiQAIAALTQECfyABLQAAIQICQCAALQAAIgNFDQAgAiADRw0AA0AgAS0AASECIAAtAAEiA0UNASABQQFqIQEgAEEBaiEAIAIgA0YNAAsLIAMgAmsL0QkBAn8jAEEgayIBJAAgASAANgIcIAEgASgCHCgCLDYCEANAIAEgASgCHCgCPCABKAIcKAJ0ayABKAIcKAJsazYCFCABKAIcKAJsIAEoAhAgASgCHCgCLEGGAmtqTwRAIAEoAhwoAjggASgCHCgCOCABKAIQaiABKAIQIAEoAhRrEBkaIAEoAhwiACAAKAJwIAEoAhBrNgJwIAEoAhwiACAAKAJsIAEoAhBrNgJsIAEoAhwiACAAKAJcIAEoAhBrNgJcIwBBIGsiACABKAIcNgIcIAAgACgCHCgCLDYCDCAAIAAoAhwoAkw2AhggACAAKAIcKAJEIAAoAhhBAXRqNgIQA0AgACAAKAIQQQJrIgI2AhAgACACLwEANgIUIAAoAhACfyAAKAIUIAAoAgxPBEAgACgCFCAAKAIMawwBC0EACzsBACAAIAAoAhhBAWsiAjYCGCACDQALIAAgACgCDDYCGCAAIAAoAhwoAkAgACgCGEEBdGo2AhADQCAAIAAoAhBBAmsiAjYCECAAIAIvAQA2AhQgACgCEAJ/IAAoAhQgACgCDE8EQCAAKAIUIAAoAgxrDAELQQALOwEAIAAgACgCGEEBayICNgIYIAINAAsgASABKAIQIAEoAhRqNgIUCyABKAIcKAIAKAIEBEAgASABKAIcKAIAIAEoAhwoAnQgASgCHCgCOCABKAIcKAJsamogASgCFBB4NgIYIAEoAhwiACABKAIYIAAoAnRqNgJ0IAEoAhwoAnQgASgCHCgCtC1qQQNPBEAgASABKAIcKAJsIAEoAhwoArQtazYCDCABKAIcIAEoAhwoAjggASgCDGotAAA2AkggASgCHCABKAIcKAJUIAEoAhwoAjggASgCDEEBamotAAAgASgCHCgCSCABKAIcKAJYdHNxNgJIA0AgASgCHCgCtC0EQCABKAIcIAEoAhwoAlQgASgCHCgCOCABKAIMQQJqai0AACABKAIcKAJIIAEoAhwoAlh0c3E2AkggASgCHCgCQCABKAIMIAEoAhwoAjRxQQF0aiABKAIcKAJEIAEoAhwoAkhBAXRqLwEAOwEAIAEoAhwoAkQgASgCHCgCSEEBdGogASgCDDsBACABIAEoAgxBAWo2AgwgASgCHCIAIAAoArQtQQFrNgK0LSABKAIcKAJ0IAEoAhwoArQtakEDTw0BCwsLIAEoAhwoAnRBhgJJBH8gASgCHCgCACgCBEEARwVBAAtBAXENAQsLIAEoAhwoAsAtIAEoAhwoAjxJBEAgASABKAIcKAJsIAEoAhwoAnRqNgIIAkAgASgCHCgCwC0gASgCCEkEQCABIAEoAhwoAjwgASgCCGs2AgQgASgCBEGCAksEQCABQYICNgIECyABKAIcKAI4IAEoAghqQQAgASgCBBAyIAEoAhwgASgCCCABKAIEajYCwC0MAQsgASgCHCgCwC0gASgCCEGCAmpJBEAgASABKAIIQYICaiABKAIcKALALWs2AgQgASgCBCABKAIcKAI8IAEoAhwoAsAta0sEQCABIAEoAhwoAjwgASgCHCgCwC1rNgIECyABKAIcKAI4IAEoAhwoAsAtakEAIAEoAgQQMiABKAIcIgAgASgCBCAAKALALWo2AsAtCwsLIAFBIGokAAuGBQEBfyMAQSBrIgQkACAEIAA2AhwgBCABNgIYIAQgAjYCFCAEIAM2AhAgBEEDNgIMAkAgBCgCHCgCvC1BECAEKAIMa0oEQCAEIAQoAhA2AgggBCgCHCIAIAAvAbgtIAQoAghB//8DcSAEKAIcKAK8LXRyOwG4LSAEKAIcLwG4LUH/AXEhASAEKAIcKAIIIQIgBCgCHCIDKAIUIQAgAyAAQQFqNgIUIAAgAmogAToAACAEKAIcLwG4LUEIdiEBIAQoAhwoAgghAiAEKAIcIgMoAhQhACADIABBAWo2AhQgACACaiABOgAAIAQoAhwgBCgCCEH//wNxQRAgBCgCHCgCvC1rdTsBuC0gBCgCHCIAIAAoArwtIAQoAgxBEGtqNgK8LQwBCyAEKAIcIgAgAC8BuC0gBCgCEEH//wNxIAQoAhwoArwtdHI7AbgtIAQoAhwiACAEKAIMIAAoArwtajYCvC0LIAQoAhwQvAEgBCgCFEH/AXEhASAEKAIcKAIIIQIgBCgCHCIDKAIUIQAgAyAAQQFqNgIUIAAgAmogAToAACAEKAIUQf//A3FBCHYhASAEKAIcKAIIIQIgBCgCHCIDKAIUIQAgAyAAQQFqNgIUIAAgAmogAToAACAEKAIUQX9zQf8BcSEBIAQoAhwoAgghAiAEKAIcIgMoAhQhACADIABBAWo2AhQgACACaiABOgAAIAQoAhRBf3NB//8DcUEIdiEBIAQoAhwoAgghAiAEKAIcIgMoAhQhACADIABBAWo2AhQgACACaiABOgAAIAQoAhwoAgggBCgCHCgCFGogBCgCGCAEKAIUEBkaIAQoAhwiACAEKAIUIAAoAhRqNgIUIARBIGokAAuJAgEBfyMAQRBrIgEkACABIAA2AgwCQCABKAIMLQAFQQFxBEAgASgCDCgCAEECcUUNAQsgASgCDCgCMBAlIAEoAgxBADYCMAsCQCABKAIMLQAFQQFxBEAgASgCDCgCAEEIcUUNAQsgASgCDCgCNBAjIAEoAgxBADYCNAsCQCABKAIMLQAFQQFxBEAgASgCDCgCAEEEcUUNAQsgASgCDCgCOBAlIAEoAgxBADYCOAsCQCABKAIMLQAFQQFxBEAgASgCDCgCAEGAAXFFDQELIAEoAgwoAlQEQCABKAIMKAJUQQAgASgCDCgCVBArEDILIAEoAgwoAlQQFSABKAIMQQA2AlQLIAFBEGokAAt3AQF/IwBBEGsiAiAANgIIIAIgATYCBAJAAkACQCACKAIIKQMoQv////8PWg0AIAIoAggpAyBC/////w9aDQAgAigCBEGABHFFDQEgAigCCCkDSEL/////D1QNAQsgAkEBOgAPDAELIAJBADoADwsgAi0AD0EBcQv/AQEBfyMAQSBrIgUkACAFIAA2AhggBSABNgIUIAUgAjsBEiAFQQA7ARAgBSADNgIMIAUgBDYCCCAFQQA2AgQCQANAIAUoAhgEQAJAIAUoAhgvAQggBS8BEkcNACAFKAIYKAIEIAUoAgxxQYAGcUUNACAFKAIEIAUvARBIBEAgBSAFKAIEQQFqNgIEDAELIAUoAhQEQCAFKAIUIAUoAhgvAQo7AQALIAUoAhgvAQoEQCAFIAUoAhgoAgw2AhwMBAsgBUGR2QA2AhwMAwsgBSAFKAIYKAIANgIYDAELCyAFKAIIQQlBABAUIAVBADYCHAsgBSgCHCEAIAVBIGokACAAC/8CAQF/IwBBMGsiBSQAIAUgADYCKCAFIAE2AiQgBSACNgIgIAUgAzoAHyAFIAQ2AhgCQAJAIAUoAiANACAFLQAfQQFxDQAgBUEANgIsDAELIAUgBSgCICAFLQAfQQFxahAYNgIUIAUoAhRFBEAgBSgCGEEOQQAQFCAFQQA2AiwMAQsCQCAFKAIoBEAgBSAFKAIoIAUoAiCtEB42AhAgBSgCEEUEQCAFKAIYQQ5BABAUIAUoAhQQFSAFQQA2AiwMAwsgBSgCFCAFKAIQIAUoAiAQGRoMAQsgBSgCJCAFKAIUIAUoAiCtIAUoAhgQYUEASARAIAUoAhQQFSAFQQA2AiwMAgsLIAUtAB9BAXEEQCAFKAIUIAUoAiBqQQA6AAAgBSAFKAIUNgIMA0AgBSgCDCAFKAIUIAUoAiBqSQRAIAUoAgwtAABFBEAgBSgCDEEgOgAACyAFIAUoAgxBAWo2AgwMAQsLCyAFIAUoAhQ2AiwLIAUoAiwhACAFQTBqJAAgAAvCAQEBfyMAQTBrIgQkACAEIAA2AiggBCABNgIkIAQgAjcDGCAEIAM2AhQCQCAEKQMYQv///////////wBWBEAgBCgCFEEUQQAQFCAEQX82AiwMAQsgBCAEKAIoIAQoAiQgBCkDGBAuIgI3AwggAkIAUwRAIAQoAhQgBCgCKBAXIARBfzYCLAwBCyAEKQMIIAQpAxhTBEAgBCgCFEERQQAQFCAEQX82AiwMAQsgBEEANgIsCyAEKAIsIQAgBEEwaiQAIAALNgEBfyMAQRBrIgEkACABIAA2AgwgASgCDBBjIAEoAgwoAgAQOSABKAIMKAIEEDkgAUEQaiQAC6sBAQF/IwBBEGsiASQAIAEgADYCDCABKAIMKAIIBEAgASgCDCgCCBAbIAEoAgxBADYCCAsCQCABKAIMKAIERQ0AIAEoAgwoAgQoAgBBAXFFDQAgASgCDCgCBCgCEEF+Rw0AIAEoAgwoAgQiACAAKAIAQX5xNgIAIAEoAgwoAgQoAgBFBEAgASgCDCgCBBA5IAEoAgxBADYCBAsLIAEoAgxBADoADCABQRBqJAAL8QMBAX8jAEHQAGsiCCQAIAggADYCSCAIIAE3A0AgCCACNwM4IAggAzYCNCAIIAQ6ADMgCCAFNgIsIAggBjcDICAIIAc2AhwCQAJAAkAgCCgCSEUNACAIKQNAIAgpA0AgCCkDOHxWDQAgCCgCLA0BIAgpAyBQDQELIAgoAhxBEkEAEBQgCEEANgJMDAELIAhBgAEQGCIANgIYIABFBEAgCCgCHEEOQQAQFCAIQQA2AkwMAQsgCCgCGCAIKQNANwMAIAgoAhggCCkDQCAIKQM4fDcDCCAIKAIYQShqEDsgCCgCGCAILQAzOgBgIAgoAhggCCgCLDYCECAIKAIYIAgpAyA3AxgjAEEQayIAIAgoAhhB5ABqNgIMIAAoAgxBADYCACAAKAIMQQA2AgQgACgCDEEANgIIIwBBEGsiACAIKAJINgIMIAAoAgwpAxhC/4EBgyEBIAhBfzYCCCAIQQc2AgQgCEEONgIAQRAgCBA2IAGEIQEgCCgCGCABNwNwIAgoAhggCCgCGCkDcELAAINCAFI6AHggCCgCNARAIAgoAhhBKGogCCgCNCAIKAIcEJUBQQBIBEAgCCgCGBAVIAhBADYCTAwCCwsgCCAIKAJIQQEgCCgCGCAIKAIcEJIBNgJMCyAIKAJMIQAgCEHQAGokACAAC9MEAQJ/IwBBMGsiAyQAIAMgADYCJCADIAE3AxggAyACNgIUAkAgAygCJCgCQCADKQMYp0EEdGooAgBFBEAgAygCFEEUQQAQFCADQgA3AygMAQsgAyADKAIkKAJAIAMpAxinQQR0aigCACkDSDcDCCADKAIkKAIAIAMpAwhBABAnQQBIBEAgAygCFCADKAIkKAIAEBcgA0IANwMoDAELIAMoAiQoAgAhAiADKAIUIQQjAEEwayIAJAAgACACNgIoIABBgAI7ASYgACAENgIgIAAgAC8BJkGAAnFBAEc6ABsgAEEeQS4gAC0AG0EBcRs2AhwCQCAAKAIoQRpBHCAALQAbQQFxG6xBARAnQQBIBEAgACgCICAAKAIoEBcgAEF/NgIsDAELIAAgACgCKEEEQQYgAC0AG0EBcRusIABBDmogACgCIBBBIgI2AgggAkUEQCAAQX82AiwMAQsgAEEANgIUA0AgACgCFEECQQMgAC0AG0EBcRtIBEAgACAAKAIIEB1B//8DcSAAKAIcajYCHCAAIAAoAhRBAWo2AhQMAQsLIAAoAggQR0EBcUUEQCAAKAIgQRRBABAUIAAoAggQFiAAQX82AiwMAQsgACgCCBAWIAAgACgCHDYCLAsgACgCLCECIABBMGokACADIAIiADYCBCAAQQBIBEAgA0IANwMoDAELIAMpAwggAygCBK18Qv///////////wBWBEAgAygCFEEEQRYQFCADQgA3AygMAQsgAyADKQMIIAMoAgStfDcDKAsgAykDKCEBIANBMGokACABC20BAX8jAEEgayIEJAAgBCAANgIYIAQgATYCFCAEIAI2AhAgBCADNgIMAkAgBCgCGEUEQCAEQQA2AhwMAQsgBCAEKAIUIAQoAhAgBCgCDCAEKAIYQQhqEJIBNgIcCyAEKAIcIQAgBEEgaiQAIAALVQEBfyMAQRBrIgEkACABIAA2AgwCQAJAIAEoAgwoAiRBAUYNACABKAIMKAIkQQJGDQAMAQsgASgCDEEAQgBBChAhGiABKAIMQQA2AiQLIAFBEGokAAumAQEBfyMAQRBrIgIkACACIAA2AgggAiABNgIEAkAgAigCCC0AKEEBcQRAIAJBfzYCDAwBCyACKAIIKAIABEAgAigCCCgCACACKAIEEGhBAEgEQCACKAIIQQxqIAIoAggoAgAQFyACQX82AgwMAgsLIAIoAgggAkEEakIEQRMQIUIAUwRAIAJBfzYCDAwBCyACQQA2AgwLIAIoAgwhACACQRBqJAAgAAuNCAIBfwF+IwBBkAFrIgMkACADIAA2AoQBIAMgATYCgAEgAyACNgJ8IAMQTwJAIAMoAoABKQMIQgBSBEAgAyADKAKAASgCACgCACkDSDcDYCADIAMoAoABKAIAKAIAKQNINwNoDAELIANCADcDYCADQgA3A2gLIANCADcDcAJAA0AgAykDcCADKAKAASkDCFQEQCADKAKAASgCACADKQNwp0EEdGooAgApA0ggAykDaFQEQCADIAMoAoABKAIAIAMpA3CnQQR0aigCACkDSDcDaAsgAykDaCADKAKAASkDIFYEQCADKAJ8QRNBABAUIANCfzcDiAEMAwsgAyADKAKAASgCACADKQNwp0EEdGooAgApA0ggAygCgAEoAgAgAykDcKdBBHRqKAIAKQMgfCADKAKAASgCACADKQNwp0EEdGooAgAoAjAQU0H//wNxrXxCHnw3A1ggAykDWCADKQNgVgRAIAMgAykDWDcDYAsgAykDYCADKAKAASkDIFYEQCADKAJ8QRNBABAUIANCfzcDiAEMAwsgAygChAEoAgAgAygCgAEoAgAgAykDcKdBBHRqKAIAKQNIQQAQJ0EASARAIAMoAnwgAygChAEoAgAQFyADQn83A4gBDAMLIAMgAygChAEoAgBBAEEBIAMoAnwQxgFCf1EEQCADEF0gA0J/NwOIAQwDCwJ/IAMoAoABKAIAIAMpA3CnQQR0aigCACEBIwBBEGsiACQAIAAgATYCCCAAIAM2AgQCQAJAAkAgACgCCC8BCiAAKAIELwEKSA0AIAAoAggoAhAgACgCBCgCEEcNACAAKAIIKAIUIAAoAgQoAhRHDQAgACgCCCgCMCAAKAIEKAIwEIsBDQELIABBfzYCDAwBCwJAAkAgACgCCCgCGCAAKAIEKAIYRw0AIAAoAggpAyAgACgCBCkDIFINACAAKAIIKQMoIAAoAgQpAyhRDQELAkACQCAAKAIELwEMQQhxRQ0AIAAoAgQoAhgNACAAKAIEKQMgQgBSDQAgACgCBCkDKFANAQsgAEF/NgIMDAILCyAAQQA2AgwLIAAoAgwhASAAQRBqJAAgAQsEQCADKAJ8QRVBABAUIAMQXSADQn83A4gBDAMFIAMoAoABKAIAIAMpA3CnQQR0aigCACgCNCADKAI0EIkBIQAgAygCgAEoAgAgAykDcKdBBHRqKAIAIAA2AjQgAygCgAEoAgAgAykDcKdBBHRqKAIAQQE6AAQgA0EANgI0IAMQXSADIAMpA3BCAXw3A3AMAgsACwsgAwJ+IAMpA2AgAykDaH1C////////////AFQEQCADKQNgIAMpA2h9DAELQv///////////wALNwOIAQsgAykDiAEhBCADQZABaiQAIAQL1AQBAX8jAEEgayIDJAAgAyAANgIYIAMgATYCFCADIAI2AhAgAygCECEBIwBBEGsiACQAIAAgATYCCCAAQdgAEBg2AgQCQCAAKAIERQRAIAAoAghBDkEAEBQgAEEANgIMDAELIAAoAgghAiMAQRBrIgEkACABIAI2AgggAUEYEBgiAjYCBAJAIAJFBEAgASgCCEEOQQAQFCABQQA2AgwMAQsgASgCBEEANgIAIAEoAgRCADcDCCABKAIEQQA2AhAgASABKAIENgIMCyABKAIMIQIgAUEQaiQAIAAoAgQgAjYCUCACRQRAIAAoAgQQFSAAQQA2AgwMAQsgACgCBEEANgIAIAAoAgRBADYCBCMAQRBrIgEgACgCBEEIajYCDCABKAIMQQA2AgAgASgCDEEANgIEIAEoAgxBADYCCCAAKAIEQQA2AhggACgCBEEANgIUIAAoAgRBADYCHCAAKAIEQQA2AiQgACgCBEEANgIgIAAoAgRBADoAKCAAKAIEQgA3AzggACgCBEIANwMwIAAoAgRBADYCQCAAKAIEQQA2AkggACgCBEEANgJEIAAoAgRBADYCTCAAKAIEQQA2AlQgACAAKAIENgIMCyAAKAIMIQEgAEEQaiQAIAMgASIANgIMAkAgAEUEQCADQQA2AhwMAQsgAygCDCADKAIYNgIAIAMoAgwgAygCFDYCBCADKAIUQRBxBEAgAygCDCIAIAAoAhRBAnI2AhQgAygCDCIAIAAoAhhBAnI2AhgLIAMgAygCDDYCHAsgAygCHCEAIANBIGokACAAC9UBAQF/IwBBIGsiBCQAIAQgADYCGCAEIAE3AxAgBCACNgIMIAQgAzYCCAJAAkAgBCkDEEL///////////8AVwRAIAQpAxBCgICAgICAgICAf1kNAQsgBCgCCEEEQT0QFCAEQX82AhwMAQsCfyAEKQMQIQEgBCgCDCEAIAQoAhgiAigCTEF/TARAIAIgASAAEKABDAELIAIgASAAEKABC0EASARAIAQoAghBBEG0mwEoAgAQFCAEQX82AhwMAQsgBEEANgIcCyAEKAIcIQAgBEEgaiQAIAALJABBACAAEAUiACAAQRtGGyIABH9BtJsBIAA2AgBBAAVBAAsaC3ABAX8jAEEQayIDJAAgAwJ/IAFBwABxRQRAQQAgAUGAgIQCcUGAgIQCRw0BGgsgAyACQQRqNgIMIAIoAgALNgIAIAAgAUGAgAJyIAMQECIAQYFgTwRAQbSbAUEAIABrNgIAQX8hAAsgA0EQaiQAIAALMwEBfwJ/IAAQByIBQWFGBEAgABARIQELIAFBgWBPCwR/QbSbAUEAIAFrNgIAQX8FIAELC2kBAn8CQCAAKAIUIAAoAhxNDQAgAEEAQQAgACgCJBEBABogACgCFA0AQX8PCyAAKAIEIgEgACgCCCICSQRAIAAgASACa6xBASAAKAIoEQ8AGgsgAEEANgIcIABCADcDECAAQgA3AgRBAAvaAwEGfyMAQRBrIgUkACAFIAI2AgwjAEGgAWsiBCQAIARBCGpBkIcBQZABEBkaIAQgADYCNCAEIAA2AhwgBEF+IABrIgNB/////wcgA0H/////B0kbIgY2AjggBCAAIAZqIgA2AiQgBCAANgIYIARBCGohACMAQdABayIDJAAgAyACNgLMASADQaABakEAQSgQMiADIAMoAswBNgLIAQJAQQAgASADQcgBaiADQdAAaiADQaABahBxQQBIDQAgACgCTEEATiEHIAAoAgAhAiAALABKQQBMBEAgACACQV9xNgIACyACQSBxIQgCfyAAKAIwBEAgACABIANByAFqIANB0ABqIANBoAFqEHEMAQsgAEHQADYCMCAAIANB0ABqNgIQIAAgAzYCHCAAIAM2AhQgACgCLCECIAAgAzYCLCAAIAEgA0HIAWogA0HQAGogA0GgAWoQcSACRQ0AGiAAQQBBACAAKAIkEQEAGiAAQQA2AjAgACACNgIsIABBADYCHCAAQQA2AhAgACgCFBogAEEANgIUQQALGiAAIAAoAgAgCHI2AgAgB0UNAAsgA0HQAWokACAGBEAgBCgCHCIAIAAgBCgCGEZrQQA6AAALIARBoAFqJAAgBUEQaiQAC4wSAg9/AX4jAEHQAGsiBSQAIAUgATYCTCAFQTdqIRMgBUE4aiEQQQAhAQNAAkAgDUEASA0AQf////8HIA1rIAFIBEBBtJsBQT02AgBBfyENDAELIAEgDWohDQsgBSgCTCIHIQECQAJAAkACQAJAAkACQAJAIAUCfwJAIActAAAiBgRAA0ACQAJAIAZB/wFxIgZFBEAgASEGDAELIAZBJUcNASABIQYDQCABLQABQSVHDQEgBSABQQJqIgg2AkwgBkEBaiEGIAEtAAIhDiAIIQEgDkElRg0ACwsgBiAHayEBIAAEQCAAIAcgARAiCyABDQ0gBSgCTCEBIAUoAkwsAAFBMGtBCk8NAyABLQACQSRHDQMgASwAAUEwayEPQQEhESABQQNqDAQLIAUgAUEBaiIINgJMIAEtAAEhBiAIIQEMAAsACyANIQsgAA0IIBFFDQJBASEBA0AgBCABQQJ0aigCACIABEAgAyABQQN0aiAAIAIQqAFBASELIAFBAWoiAUEKRw0BDAoLC0EBIQsgAUEKTw0IA0AgBCABQQJ0aigCAA0IIAFBAWoiAUEKRw0ACwwIC0F/IQ8gAUEBagsiATYCTEEAIQgCQCABLAAAIgxBIGsiBkEfSw0AQQEgBnQiBkGJ0QRxRQ0AA0ACQCAFIAFBAWoiCDYCTCABLAABIgxBIGsiAUEgTw0AQQEgAXQiAUGJ0QRxRQ0AIAEgBnIhBiAIIQEMAQsLIAghASAGIQgLAkAgDEEqRgRAIAUCfwJAIAEsAAFBMGtBCk8NACAFKAJMIgEtAAJBJEcNACABLAABQQJ0IARqQcABa0EKNgIAIAEsAAFBA3QgA2pBgANrKAIAIQpBASERIAFBA2oMAQsgEQ0IQQAhEUEAIQogAARAIAIgAigCACIBQQRqNgIAIAEoAgAhCgsgBSgCTEEBagsiATYCTCAKQX9KDQFBACAKayEKIAhBgMAAciEIDAELIAVBzABqEKcBIgpBAEgNBiAFKAJMIQELQX8hCQJAIAEtAABBLkcNACABLQABQSpGBEACQCABLAACQTBrQQpPDQAgBSgCTCIBLQADQSRHDQAgASwAAkECdCAEakHAAWtBCjYCACABLAACQQN0IANqQYADaygCACEJIAUgAUEEaiIBNgJMDAILIBENByAABH8gAiACKAIAIgFBBGo2AgAgASgCAAVBAAshCSAFIAUoAkxBAmoiATYCTAwBCyAFIAFBAWo2AkwgBUHMAGoQpwEhCSAFKAJMIQELQQAhBgNAIAYhEkF/IQsgASwAAEHBAGtBOUsNByAFIAFBAWoiDDYCTCABLAAAIQYgDCEBIAYgEkE6bGpB74IBai0AACIGQQFrQQhJDQALIAZBE0YNAiAGRQ0GIA9BAE4EQCAEIA9BAnRqIAY2AgAgBSADIA9BA3RqKQMANwNADAQLIAANAQtBACELDAULIAVBQGsgBiACEKgBIAUoAkwhDAwCCyAPQX9KDQMLQQAhASAARQ0ECyAIQf//e3EiDiAIIAhBgMAAcRshBkEAIQtBpAghDyAQIQgCQAJAAkACfwJAAkACQAJAAn8CQAJAAkACQAJAAkACQCAMQQFrLAAAIgFBX3EgASABQQ9xQQNGGyABIBIbIgFB2ABrDiEEEhISEhISEhIOEg8GDg4OEgYSEhISAgUDEhIJEgESEgQACwJAIAFBwQBrDgcOEgsSDg4OAAsgAUHTAEYNCQwRCyAFKQNAIRRBpAgMBQtBACEBAkACQAJAAkACQAJAAkAgEkH/AXEOCAABAgMEFwUGFwsgBSgCQCANNgIADBYLIAUoAkAgDTYCAAwVCyAFKAJAIA2sNwMADBQLIAUoAkAgDTsBAAwTCyAFKAJAIA06AAAMEgsgBSgCQCANNgIADBELIAUoAkAgDaw3AwAMEAsgCUEIIAlBCEsbIQkgBkEIciEGQfgAIQELIBAhByABQSBxIQ4gBSkDQCIUUEUEQANAIAdBAWsiByAUp0EPcUGAhwFqLQAAIA5yOgAAIBRCD1YhDCAUQgSIIRQgDA0ACwsgBSkDQFANAyAGQQhxRQ0DIAFBBHZBpAhqIQ9BAiELDAMLIBAhASAFKQNAIhRQRQRAA0AgAUEBayIBIBSnQQdxQTByOgAAIBRCB1YhByAUQgOIIRQgBw0ACwsgASEHIAZBCHFFDQIgCSAQIAdrIgFBAWogASAJSBshCQwCCyAFKQNAIhRCf1cEQCAFQgAgFH0iFDcDQEEBIQtBpAgMAQsgBkGAEHEEQEEBIQtBpQgMAQtBpghBpAggBkEBcSILGwshDyAUIBAQRCEHCyAGQf//e3EgBiAJQX9KGyEGAkAgBSkDQCIUQgBSDQAgCQ0AQQAhCSAQIQcMCgsgCSAUUCAQIAdraiIBIAEgCUgbIQkMCQsgBSgCQCIBQdgSIAEbIgdBACAJEKsBIgEgByAJaiABGyEIIA4hBiABIAdrIAkgARshCQwICyAJBEAgBSgCQAwCC0EAIQEgAEEgIApBACAGECYMAgsgBUEANgIMIAUgBSkDQD4CCCAFIAVBCGo2AkBBfyEJIAVBCGoLIQhBACEBAkADQCAIKAIAIgdFDQECQCAFQQRqIAcQqgEiB0EASCIODQAgByAJIAFrSw0AIAhBBGohCCAJIAEgB2oiAUsNAQwCCwtBfyELIA4NBQsgAEEgIAogASAGECYgAUUEQEEAIQEMAQtBACEIIAUoAkAhDANAIAwoAgAiB0UNASAFQQRqIAcQqgEiByAIaiIIIAFKDQEgACAFQQRqIAcQIiAMQQRqIQwgASAISw0ACwsgAEEgIAogASAGQYDAAHMQJiAKIAEgASAKSBshAQwFCyAAIAUrA0AgCiAJIAYgAUEXERkAIQEMBAsgBSAFKQNAPAA3QQEhCSATIQcgDiEGDAILQX8hCwsgBUHQAGokACALDwsgAEEgIAsgCCAHayIOIAkgCSAOSBsiDGoiCCAKIAggCkobIgEgCCAGECYgACAPIAsQIiAAQTAgASAIIAZBgIAEcxAmIABBMCAMIA5BABAmIAAgByAOECIgAEEgIAEgCCAGQYDAAHMQJgwACwALkAIBA38CQCABIAIoAhAiBAR/IAQFQQAhBAJ/IAIgAi0ASiIDQQFrIANyOgBKIAIoAgAiA0EIcQRAIAIgA0EgcjYCAEF/DAELIAJCADcCBCACIAIoAiwiAzYCHCACIAM2AhQgAiADIAIoAjBqNgIQQQALDQEgAigCEAsgAigCFCIFa0sEQCACIAAgASACKAIkEQEADwsCfyACLABLQX9KBEAgASEEA0AgASAEIgNFDQIaIAAgA0EBayIEai0AAEEKRw0ACyACIAAgAyACKAIkEQEAIgQgA0kNAiAAIANqIQAgAigCFCEFIAEgA2sMAQsgAQshBCAFIAAgBBAZGiACIAIoAhQgBGo2AhQgASEECyAEC0gCAX8BfiMAQRBrIgMkACADIAA2AgwgAyABNgIIIAMgAjYCBCADKAIMIAMoAgggAygCBCADKAIMQQhqEFchBCADQRBqJAAgBAt3AQF/IwBBEGsiASAANgIIIAFChSo3AwACQCABKAIIRQRAIAFBADYCDAwBCwNAIAEoAggtAAAEQCABIAEoAggtAACtIAEpAwBCIX58Qv////8PgzcDACABIAEoAghBAWo2AggMAQsLIAEgASkDAD4CDAsgASgCDAuHBQEBfyMAQTBrIgUkACAFIAA2AiggBSABNgIkIAUgAjcDGCAFIAM2AhQgBSAENgIQAkACQAJAIAUoAihFDQAgBSgCJEUNACAFKQMYQv///////////wBYDQELIAUoAhBBEkEAEBQgBUEAOgAvDAELIAUoAigoAgBFBEAgBSgCKEGAAiAFKAIQEFlBAXFFBEAgBUEAOgAvDAILCyAFIAUoAiQQdDYCDCAFIAUoAgwgBSgCKCgCAHA2AgggBSAFKAIoKAIQIAUoAghBAnRqKAIANgIEA0ACQCAFKAIERQ0AAkAgBSgCBCgCHCAFKAIMRw0AIAUoAiQgBSgCBCgCABBaDQACQAJAIAUoAhRBCHEEQCAFKAIEKQMIQn9SDQELIAUoAgQpAxBCf1ENAQsgBSgCEEEKQQAQFCAFQQA6AC8MBAsMAQsgBSAFKAIEKAIYNgIEDAELCyAFKAIERQRAIAVBIBAYIgA2AgQgAEUEQCAFKAIQQQ5BABAUIAVBADoALwwCCyAFKAIEIAUoAiQ2AgAgBSgCBCAFKAIoKAIQIAUoAghBAnRqKAIANgIYIAUoAigoAhAgBSgCCEECdGogBSgCBDYCACAFKAIEIAUoAgw2AhwgBSgCBEJ/NwMIIAUoAigiACAAKQMIQgF8NwMIAkAgBSgCKCIAKQMIuiAAKAIAuEQAAAAAAADoP6JkRQ0AIAUoAigoAgBBgICAgHhPDQAgBSgCKCAFKAIoKAIAQQF0IAUoAhAQWUEBcUUEQCAFQQA6AC8MAwsLCyAFKAIUQQhxBEAgBSgCBCAFKQMYNwMICyAFKAIEIAUpAxg3AxAgBUEBOgAvCyAFLQAvQQFxIQAgBUEwaiQAIAALWQIBfwF+AkACf0EAIABFDQAaIACtIAGtfiIDpyICIAAgAXJBgIAESQ0AGkF/IAIgA0IgiKcbCyICEBgiAEUNACAAQQRrLQAAQQNxRQ0AIABBACACEDILIAAL1BEBAX8jAEGwAWsiBiQAIAYgADYCqAEgBiABNgKkASAGIAI2AqABIAYgAzYCnAEgBiAENgKYASAGIAU2ApQBIAZBADYCkAEDQCAGKAKQAUEPS0UEQCAGQSBqIAYoApABQQF0akEAOwEAIAYgBigCkAFBAWo2ApABDAELCyAGQQA2AowBA0AgBigCjAEgBigCoAFPRQRAIAZBIGogBigCpAEgBigCjAFBAXRqLwEAQQF0aiIAIAAvAQBBAWo7AQAgBiAGKAKMAUEBajYCjAEMAQsLIAYgBigCmAEoAgA2AoABIAZBDzYChAEDQAJAIAYoAoQBQQFJDQAgBkEgaiAGKAKEAUEBdGovAQANACAGIAYoAoQBQQFrNgKEAQwBCwsgBigCgAEgBigChAFLBEAgBiAGKAKEATYCgAELAkAgBigChAFFBEAgBkHAADoAWCAGQQE6AFkgBkEAOwFaIAYoApwBIgEoAgAhACABIABBBGo2AgAgACAGQdgAaigBADYBACAGKAKcASIBKAIAIQAgASAAQQRqNgIAIAAgBkHYAGooAQA2AQAgBigCmAFBATYCACAGQQA2AqwBDAELIAZBATYCiAEDQAJAIAYoAogBIAYoAoQBTw0AIAZBIGogBigCiAFBAXRqLwEADQAgBiAGKAKIAUEBajYCiAEMAQsLIAYoAoABIAYoAogBSQRAIAYgBigCiAE2AoABCyAGQQE2AnQgBkEBNgKQAQNAIAYoApABQQ9NBEAgBiAGKAJ0QQF0NgJ0IAYgBigCdCAGQSBqIAYoApABQQF0ai8BAGs2AnQgBigCdEEASARAIAZBfzYCrAEMAwUgBiAGKAKQAUEBajYCkAEMAgsACwsCQCAGKAJ0QQBMDQAgBigCqAEEQCAGKAKEAUEBRg0BCyAGQX82AqwBDAELIAZBADsBAiAGQQE2ApABA0AgBigCkAFBD09FBEAgBigCkAFBAWpBAXQgBmogBigCkAFBAXQgBmovAQAgBkEgaiAGKAKQAUEBdGovAQBqOwEAIAYgBigCkAFBAWo2ApABDAELCyAGQQA2AowBA0AgBigCjAEgBigCoAFJBEAgBigCpAEgBigCjAFBAXRqLwEABEAgBigClAEhASAGKAKkASAGKAKMASICQQF0ai8BAEEBdCAGaiIDLwEAIQAgAyAAQQFqOwEAIABB//8DcUEBdCABaiACOwEACyAGIAYoAowBQQFqNgKMAQwBCwsCQAJAAkACQCAGKAKoAQ4CAAECCyAGIAYoApQBIgA2AkwgBiAANgJQIAZBFDYCSAwCCyAGQYDwADYCUCAGQcDwADYCTCAGQYECNgJIDAELIAZBgPEANgJQIAZBwPEANgJMIAZBADYCSAsgBkEANgJsIAZBADYCjAEgBiAGKAKIATYCkAEgBiAGKAKcASgCADYCVCAGIAYoAoABNgJ8IAZBADYCeCAGQX82AmAgBkEBIAYoAoABdDYCcCAGIAYoAnBBAWs2AlwCQAJAIAYoAqgBQQFGBEAgBigCcEHUBksNAQsgBigCqAFBAkcNASAGKAJwQdAETQ0BCyAGQQE2AqwBDAELA0AgBiAGKAKQASAGKAJ4azoAWQJAIAYoAkggBigClAEgBigCjAFBAXRqLwEAQQFqSwRAIAZBADoAWCAGIAYoApQBIAYoAowBQQF0ai8BADsBWgwBCwJAIAYoApQBIAYoAowBQQF0ai8BACAGKAJITwRAIAYgBigCTCAGKAKUASAGKAKMAUEBdGovAQAgBigCSGtBAXRqLwEAOgBYIAYgBigCUCAGKAKUASAGKAKMAUEBdGovAQAgBigCSGtBAXRqLwEAOwFaDAELIAZB4AA6AFggBkEAOwFaCwsgBkEBIAYoApABIAYoAnhrdDYCaCAGQQEgBigCfHQ2AmQgBiAGKAJkNgKIAQNAIAYgBigCZCAGKAJoazYCZCAGKAJUIAYoAmQgBigCbCAGKAJ4dmpBAnRqIAZB2ABqKAEANgEAIAYoAmQNAAsgBkEBIAYoApABQQFrdDYCaANAIAYoAmwgBigCaHEEQCAGIAYoAmhBAXY2AmgMAQsLAkAgBigCaARAIAYgBigCbCAGKAJoQQFrcTYCbCAGIAYoAmggBigCbGo2AmwMAQsgBkEANgJsCyAGIAYoAowBQQFqNgKMASAGQSBqIAYoApABQQF0aiIBLwEAQQFrIQAgASAAOwEAAkAgAEH//wNxRQRAIAYoApABIAYoAoQBRg0BIAYgBigCpAEgBigClAEgBigCjAFBAXRqLwEAQQF0ai8BADYCkAELAkAgBigCkAEgBigCgAFNDQAgBigCYCAGKAJsIAYoAlxxRg0AIAYoAnhFBEAgBiAGKAKAATYCeAsgBiAGKAJUIAYoAogBQQJ0ajYCVCAGIAYoApABIAYoAnhrNgJ8IAZBASAGKAJ8dDYCdANAAkAgBigChAEgBigCfCAGKAJ4ak0NACAGIAYoAnQgBkEgaiAGKAJ8IAYoAnhqQQF0ai8BAGs2AnQgBigCdEEATA0AIAYgBigCfEEBajYCfCAGIAYoAnRBAXQ2AnQMAQsLIAYgBigCcEEBIAYoAnx0ajYCcAJAAkAgBigCqAFBAUYEQCAGKAJwQdQGSw0BCyAGKAKoAUECRw0BIAYoAnBB0ARNDQELIAZBATYCrAEMBAsgBiAGKAJsIAYoAlxxNgJgIAYoApwBKAIAIAYoAmBBAnRqIAYoAnw6AAAgBigCnAEoAgAgBigCYEECdGogBigCgAE6AAEgBigCnAEoAgAgBigCYEECdGogBigCVCAGKAKcASgCAGtBAnU7AQILDAELCyAGKAJsBEAgBkHAADoAWCAGIAYoApABIAYoAnhrOgBZIAZBADsBWiAGKAJUIAYoAmxBAnRqIAZB2ABqKAEANgEACyAGKAKcASIAIAAoAgAgBigCcEECdGo2AgAgBigCmAEgBigCgAE2AgAgBkEANgKsAQsgBigCrAEhACAGQbABaiQAIAALsQIBAX8jAEEgayIDJAAgAyAANgIYIAMgATYCFCADIAI2AhAgAyADKAIYKAIENgIMIAMoAgwgAygCEEsEQCADIAMoAhA2AgwLAkAgAygCDEUEQCADQQA2AhwMAQsgAygCGCIAIAAoAgQgAygCDGs2AgQgAygCFCADKAIYKAIAIAMoAgwQGRoCQCADKAIYKAIcKAIYQQFGBEAgAygCGCgCMCADKAIUIAMoAgwQPiEAIAMoAhggADYCMAwBCyADKAIYKAIcKAIYQQJGBEAgAygCGCgCMCADKAIUIAMoAgwQGiEAIAMoAhggADYCMAsLIAMoAhgiACADKAIMIAAoAgBqNgIAIAMoAhgiACADKAIMIAAoAghqNgIIIAMgAygCDDYCHAsgAygCHCEAIANBIGokACAAC+0BAQF/IwBBEGsiASAANgIIAkACQAJAIAEoAghFDQAgASgCCCgCIEUNACABKAIIKAIkDQELIAFBATYCDAwBCyABIAEoAggoAhw2AgQCQAJAIAEoAgRFDQAgASgCBCgCACABKAIIRw0AIAEoAgQoAgRBKkYNASABKAIEKAIEQTlGDQEgASgCBCgCBEHFAEYNASABKAIEKAIEQckARg0BIAEoAgQoAgRB2wBGDQEgASgCBCgCBEHnAEYNASABKAIEKAIEQfEARg0BIAEoAgQoAgRBmgVGDQELIAFBATYCDAwBCyABQQA2AgwLIAEoAgwL0gQBAX8jAEEgayIDIAA2AhwgAyABNgIYIAMgAjYCFCADIAMoAhxB3BZqIAMoAhRBAnRqKAIANgIQIAMgAygCFEEBdDYCDANAAkAgAygCDCADKAIcKALQKEoNAAJAIAMoAgwgAygCHCgC0ChODQAgAygCGCADKAIcIAMoAgxBAnRqQeAWaigCAEECdGovAQAgAygCGCADKAIcQdwWaiADKAIMQQJ0aigCAEECdGovAQBOBEAgAygCGCADKAIcIAMoAgxBAnRqQeAWaigCAEECdGovAQAgAygCGCADKAIcQdwWaiADKAIMQQJ0aigCAEECdGovAQBHDQEgAygCHCADKAIMQQJ0akHgFmooAgAgAygCHEHYKGpqLQAAIAMoAhxB3BZqIAMoAgxBAnRqKAIAIAMoAhxB2Chqai0AAEoNAQsgAyADKAIMQQFqNgIMCyADKAIYIAMoAhBBAnRqLwEAIAMoAhggAygCHEHcFmogAygCDEECdGooAgBBAnRqLwEASA0AAkAgAygCGCADKAIQQQJ0ai8BACADKAIYIAMoAhxB3BZqIAMoAgxBAnRqKAIAQQJ0ai8BAEcNACADKAIQIAMoAhxB2Chqai0AACADKAIcQdwWaiADKAIMQQJ0aigCACADKAIcQdgoamotAABKDQAMAQsgAygCHEHcFmogAygCFEECdGogAygCHEHcFmogAygCDEECdGooAgA2AgAgAyADKAIMNgIUIAMgAygCDEEBdDYCDAwBCwsgAygCHEHcFmogAygCFEECdGogAygCEDYCAAvXEwEDfyMAQTBrIgIkACACIAA2AiwgAiABNgIoIAIgAigCKCgCADYCJCACIAIoAigoAggoAgA2AiAgAiACKAIoKAIIKAIMNgIcIAJBfzYCECACKAIsQQA2AtAoIAIoAixBvQQ2AtQoIAJBADYCGANAIAIoAhggAigCHEgEQAJAIAIoAiQgAigCGEECdGovAQAEQCACIAIoAhgiATYCECACKAIsQdwWaiEDIAIoAiwiBCgC0ChBAWohACAEIAA2AtAoIABBAnQgA2ogATYCACACKAIYIAIoAixB2ChqakEAOgAADAELIAIoAiQgAigCGEECdGpBADsBAgsgAiACKAIYQQFqNgIYDAELCwNAIAIoAiwoAtAoQQJIBEACQCACKAIQQQJIBEAgAiACKAIQQQFqIgA2AhAMAQtBACEACyACKAIsQdwWaiEDIAIoAiwiBCgC0ChBAWohASAEIAE2AtAoIAFBAnQgA2ogADYCACACIAA2AgwgAigCJCACKAIMQQJ0akEBOwEAIAIoAgwgAigCLEHYKGpqQQA6AAAgAigCLCIAIAAoAqgtQQFrNgKoLSACKAIgBEAgAigCLCIAIAAoAqwtIAIoAiAgAigCDEECdGovAQJrNgKsLQsMAQsLIAIoAiggAigCEDYCBCACIAIoAiwoAtAoQQJtNgIYA0AgAigCGEEBTgRAIAIoAiwgAigCJCACKAIYEHogAiACKAIYQQFrNgIYDAELCyACIAIoAhw2AgwDQCACIAIoAiwoAuAWNgIYIAIoAixB3BZqIQEgAigCLCIDKALQKCEAIAMgAEEBazYC0CggAigCLCAAQQJ0IAFqKAIANgLgFiACKAIsIAIoAiRBARB6IAIgAigCLCgC4BY2AhQgAigCGCEBIAIoAixB3BZqIQMgAigCLCIEKALUKEEBayEAIAQgADYC1CggAEECdCADaiABNgIAIAIoAhQhASACKAIsQdwWaiEDIAIoAiwiBCgC1ChBAWshACAEIAA2AtQoIABBAnQgA2ogATYCACACKAIkIAIoAgxBAnRqIAIoAiQgAigCGEECdGovAQAgAigCJCACKAIUQQJ0ai8BAGo7AQAgAigCDCACKAIsQdgoamoCfyACKAIYIAIoAixB2Chqai0AACACKAIUIAIoAixB2Chqai0AAE4EQCACKAIYIAIoAixB2Chqai0AAAwBCyACKAIUIAIoAixB2Chqai0AAAtBAWo6AAAgAigCJCACKAIUQQJ0aiACKAIMIgA7AQIgAigCJCACKAIYQQJ0aiAAOwECIAIgAigCDCIAQQFqNgIMIAIoAiwgADYC4BYgAigCLCACKAIkQQEQeiACKAIsKALQKEECTg0ACyACKAIsKALgFiEBIAIoAixB3BZqIQMgAigCLCIEKALUKEEBayEAIAQgADYC1CggAEECdCADaiABNgIAIAIoAighASMAQUBqIgAgAigCLDYCPCAAIAE2AjggACAAKAI4KAIANgI0IAAgACgCOCgCBDYCMCAAIAAoAjgoAggoAgA2AiwgACAAKAI4KAIIKAIENgIoIAAgACgCOCgCCCgCCDYCJCAAIAAoAjgoAggoAhA2AiAgAEEANgIEIABBADYCEANAIAAoAhBBD0wEQCAAKAI8QbwWaiAAKAIQQQF0akEAOwEAIAAgACgCEEEBajYCEAwBCwsgACgCNCAAKAI8QdwWaiAAKAI8KALUKEECdGooAgBBAnRqQQA7AQIgACAAKAI8KALUKEEBajYCHANAIAAoAhxBvQRIBEAgACAAKAI8QdwWaiAAKAIcQQJ0aigCADYCGCAAIAAoAjQgACgCNCAAKAIYQQJ0ai8BAkECdGovAQJBAWo2AhAgACgCECAAKAIgSgRAIAAgACgCIDYCECAAIAAoAgRBAWo2AgQLIAAoAjQgACgCGEECdGogACgCEDsBAiAAKAIYIAAoAjBMBEAgACgCPCAAKAIQQQF0akG8FmoiASABLwEAQQFqOwEAIABBADYCDCAAKAIYIAAoAiROBEAgACAAKAIoIAAoAhggACgCJGtBAnRqKAIANgIMCyAAIAAoAjQgACgCGEECdGovAQA7AQogACgCPCIBIAEoAqgtIAAvAQogACgCECAAKAIMamxqNgKoLSAAKAIsBEAgACgCPCIBIAEoAqwtIAAvAQogACgCLCAAKAIYQQJ0ai8BAiAAKAIMamxqNgKsLQsLIAAgACgCHEEBajYCHAwBCwsCQCAAKAIERQ0AA0AgACAAKAIgQQFrNgIQA0AgACgCPEG8FmogACgCEEEBdGovAQBFBEAgACAAKAIQQQFrNgIQDAELCyAAKAI8IAAoAhBBAXRqQbwWaiIBIAEvAQBBAWs7AQAgACgCPCAAKAIQQQF0akG+FmoiASABLwEAQQJqOwEAIAAoAjwgACgCIEEBdGpBvBZqIgEgAS8BAEEBazsBACAAIAAoAgRBAms2AgQgACgCBEEASg0ACyAAIAAoAiA2AhADQCAAKAIQRQ0BIAAgACgCPEG8FmogACgCEEEBdGovAQA2AhgDQCAAKAIYBEAgACgCPEHcFmohASAAIAAoAhxBAWsiAzYCHCAAIANBAnQgAWooAgA2AhQgACgCFCAAKAIwSg0BIAAoAjQgACgCFEECdGovAQIgACgCEEcEQCAAKAI8IgEgASgCqC0gACgCNCAAKAIUQQJ0ai8BACAAKAIQIAAoAjQgACgCFEECdGovAQJrbGo2AqgtIAAoAjQgACgCFEECdGogACgCEDsBAgsgACAAKAIYQQFrNgIYDAELCyAAIAAoAhBBAWs2AhAMAAsACyACKAIkIQEgAigCECEDIAIoAixBvBZqIQQjAEFAaiIAJAAgACABNgI8IAAgAzYCOCAAIAQ2AjQgAEEANgIMIABBATYCCANAIAAoAghBD0wEQCAAIAAoAgwgACgCNCAAKAIIQQFrQQF0ai8BAGpBAXQ2AgwgAEEQaiAAKAIIQQF0aiAAKAIMOwEAIAAgACgCCEEBajYCCAwBCwsgAEEANgIEA0AgACgCBCAAKAI4TARAIAAgACgCPCAAKAIEQQJ0ai8BAjYCACAAKAIABEAgAEEQaiAAKAIAQQF0aiIBLwEAIQMgASADQQFqOwEAIAAoAgAhBCMAQRBrIgEgAzYCDCABIAQ2AgggAUEANgIEA0AgASABKAIEIAEoAgxBAXFyNgIEIAEgASgCDEEBdjYCDCABIAEoAgRBAXQ2AgQgASABKAIIQQFrIgM2AgggA0EASg0ACyABKAIEQQF2IQEgACgCPCAAKAIEQQJ0aiABOwEACyAAIAAoAgRBAWo2AgQMAQsLIABBQGskACACQTBqJAALTgEBfyMAQRBrIgIgADsBCiACIAE2AgQCQCACLwEKQQFGBEAgAigCBEEBRgRAIAJBADYCDAwCCyACQQQ2AgwMAQsgAkEANgIMCyACKAIMC84CAQF/IwBBMGsiBSQAIAUgADYCLCAFIAE2AiggBSACNgIkIAUgAzcDGCAFIAQ2AhQgBUIANwMIA0AgBSkDCCAFKQMYVARAIAUgBSgCJCAFKQMIp2otAAA6AAcgBSgCFEUEQCAFIAUoAiwoAhRBAnI7ARIgBSAFLwESIAUvARJBAXNsQQh2OwESIAUgBS0AByAFLwESQf8BcXM6AAcLIAUoAigEQCAFKAIoIAUpAwinaiAFLQAHOgAACyAFKAIsKAIMQX9zIAVBB2pBARAaQX9zIQAgBSgCLCAANgIMIAUoAiwgBSgCLCgCECAFKAIsKAIMQf8BcWpBhYiiwABsQQFqNgIQIAUgBSgCLCgCEEEYdjoAByAFKAIsKAIUQX9zIAVBB2pBARAaQX9zIQAgBSgCLCAANgIUIAUgBSkDCEIBfDcDCAwBCwsgBUEwaiQAC20BAX8jAEEgayIEJAAgBCAANgIYIAQgATYCFCAEIAI3AwggBCADNgIEAkAgBCgCGEUEQCAEQQA2AhwMAQsgBCAEKAIUIAQpAwggBCgCBCAEKAIYQQhqEMMBNgIcCyAEKAIcIQAgBEEgaiQAIAALpwMBAX8jAEEgayIEJAAgBCAANgIYIAQgATcDECAEIAI2AgwgBCADNgIIIAQgBCgCGCAEKQMQIAQoAgxBABBFIgA2AgACQCAARQRAIARBfzYCHAwBCyAEIAQoAhggBCkDECAEKAIMEMQBIgA2AgQgAEUEQCAEQX82AhwMAQsCQAJAIAQoAgxBCHENACAEKAIYKAJAIAQpAxCnQQR0aigCCEUNACAEKAIYKAJAIAQpAxCnQQR0aigCCCAEKAIIEDhBAEgEQCAEKAIYQQhqQQ9BABAUIARBfzYCHAwDCwwBCyAEKAIIEDsgBCgCCCAEKAIAKAIYNgIsIAQoAgggBCgCACkDKDcDGCAEKAIIIAQoAgAoAhQ2AiggBCgCCCAEKAIAKQMgNwMgIAQoAgggBCgCACgCEDsBMCAEKAIIIAQoAgAvAVI7ATIgBCgCCEEgQQAgBCgCAC0ABkEBcRtB3AFyrTcDAAsgBCgCCCAEKQMQNwMQIAQoAgggBCgCBDYCCCAEKAIIIgAgACkDAEIDhDcDACAEQQA2AhwLIAQoAhwhACAEQSBqJAAgAAsDAAELzQEBAX8jAEEQayIDJAAgAyAANgIMIAMgATYCCCADIAI2AgQgAyADQQxqQaifARALNgIAAkAgAygCAEUEQCADKAIEQSE7AQAgAygCCEEAOwEADAELIAMoAgAoAhRB0ABIBEAgAygCAEHQADYCFAsgAygCBCADKAIAKAIMIAMoAgAoAhRBCXQgAygCACgCEEEFdGpB4L8Ca2o7AQAgAygCCCADKAIAKAIIQQt0IAMoAgAoAgRBBXRqIAMoAgAoAgBBAXVqOwEACyADQRBqJAALgwMBAX8jAEEgayIDJAAgAyAAOwEaIAMgATYCFCADIAI2AhAgAyADKAIUIANBCGpBwABBABBGIgA2AgwCQCAARQRAIANBADYCHAwBCyADKAIIQQVqQf//A0sEQCADKAIQQRJBABAUIANBADYCHAwBCyADQQAgAygCCEEFaq0QKSIANgIEIABFBEAgAygCEEEOQQAQFCADQQA2AhwMAQsgAygCBEEBEI4BIAMoAgQgAygCFBCMARAgIAMoAgQgAygCDCADKAIIEEACfyMAQRBrIgAgAygCBDYCDCAAKAIMLQAAQQFxRQsEQCADKAIQQRRBABAUIAMoAgQQFiADQQA2AhwMAQsgAyADLwEaAn8jAEEQayIAIAMoAgQ2AgwCfiAAKAIMLQAAQQFxBEAgACgCDCkDEAwBC0IAC6dB//8DcQsCfyMAQRBrIgAgAygCBDYCDCAAKAIMKAIEC0GABhBRNgIAIAMoAgQQFiADIAMoAgA2AhwLIAMoAhwhACADQSBqJAAgAAu0AgEBfyMAQTBrIgMkACADIAA2AiggAyABNwMgIAMgAjYCHAJAIAMpAyBQBEAgA0EBOgAvDAELIAMgAygCKCkDECADKQMgfDcDCAJAIAMpAwggAykDIFoEQCADKQMIQv////8AWA0BCyADKAIcQQ5BABAUIANBADoALwwBCyADIAMoAigoAgAgAykDCKdBBHQQSCIANgIEIABFBEAgAygCHEEOQQAQFCADQQA6AC8MAQsgAygCKCADKAIENgIAIAMgAygCKCkDCDcDEANAIAMpAxAgAykDCFpFBEAgAygCKCgCACADKQMQp0EEdGoQkAEgAyADKQMQQgF8NwMQDAELCyADKAIoIAMpAwgiATcDECADKAIoIAE3AwggA0EBOgAvCyADLQAvQQFxIQAgA0EwaiQAIAALzAEBAX8jAEEgayICJAAgAiAANwMQIAIgATYCDCACQTAQGCIBNgIIAkAgAUUEQCACKAIMQQ5BABAUIAJBADYCHAwBCyACKAIIQQA2AgAgAigCCEIANwMQIAIoAghCADcDCCACKAIIQgA3AyAgAigCCEIANwMYIAIoAghBADYCKCACKAIIQQA6ACwgAigCCCACKQMQIAIoAgwQgwFBAXFFBEAgAigCCBAkIAJBADYCHAwBCyACIAIoAgg2AhwLIAIoAhwhASACQSBqJAAgAQvWAgEBfyMAQSBrIgMkACADIAA2AhggAyABNgIUIAMgAjYCECADIANBDGpCBBApNgIIAkAgAygCCEUEQCADQX82AhwMAQsDQCADKAIUBEAgAygCFCgCBCADKAIQcUGABnEEQCADKAIIQgAQLBogAygCCCADKAIULwEIEB8gAygCCCADKAIULwEKEB8CfyMAQRBrIgAgAygCCDYCDCAAKAIMLQAAQQFxRQsEQCADKAIYQQhqQRRBABAUIAMoAggQFiADQX82AhwMBAsgAygCGCADQQxqQgQQNUEASARAIAMoAggQFiADQX82AhwMBAsgAygCFC8BCgRAIAMoAhggAygCFCgCDCADKAIULwEKrRA1QQBIBEAgAygCCBAWIANBfzYCHAwFCwsLIAMgAygCFCgCADYCFAwBCwsgAygCCBAWIANBADYCHAsgAygCHCEAIANBIGokACAAC2gBAX8jAEEQayICIAA2AgwgAiABNgIIIAJBADsBBgNAIAIoAgwEQCACKAIMKAIEIAIoAghxQYAGcQRAIAIgAigCDC8BCiACLwEGQQRqajsBBgsgAiACKAIMKAIANgIMDAELCyACLwEGC/ABAQF/IwBBEGsiASQAIAEgADYCDCABIAEoAgw2AgggAUEANgIEA0AgASgCDARAAkACQCABKAIMLwEIQfXGAUYNACABKAIMLwEIQfXgAUYNACABKAIMLwEIQYGyAkYNACABKAIMLwEIQQFHDQELIAEgASgCDCgCADYCACABKAIIIAEoAgxGBEAgASABKAIANgIICyABKAIMQQA2AgAgASgCDBAjIAEoAgQEQCABKAIEIAEoAgA2AgALIAEgASgCADYCDAwCCyABIAEoAgw2AgQgASABKAIMKAIANgIMDAELCyABKAIIIQAgAUEQaiQAIAALswQBAX8jAEFAaiIFJAAgBSAANgI4IAUgATsBNiAFIAI2AjAgBSADNgIsIAUgBDYCKCAFIAUoAjggBS8BNq0QKSIANgIkAkAgAEUEQCAFKAIoQQ5BABAUIAVBADoAPwwBCyAFQQA2AiAgBUEANgIYA0ACfyMAQRBrIgAgBSgCJDYCDCAAKAIMLQAAQQFxCwR/IAUoAiQQL0IEWgVBAAtBAXEEQCAFIAUoAiQQHTsBFiAFIAUoAiQQHTsBFCAFIAUoAiQgBS8BFK0QHjYCECAFKAIQRQRAIAUoAihBFUEAEBQgBSgCJBAWIAUoAhgQIyAFQQA6AD8MAwsgBSAFLwEWIAUvARQgBSgCECAFKAIwEFEiADYCHCAARQRAIAUoAihBDkEAEBQgBSgCJBAWIAUoAhgQIyAFQQA6AD8MAwsCQCAFKAIYBEAgBSgCICAFKAIcNgIAIAUgBSgCHDYCIAwBCyAFIAUoAhwiADYCICAFIAA2AhgLDAELCyAFKAIkEEdBAXFFBEAgBSAFKAIkEC8+AgwgBSAFKAIkIAUoAgytEB42AggCQAJAIAUoAgxBBE8NACAFKAIIRQ0AIAUoAghBktkAIAUoAgwQVEUNAQsgBSgCKEEVQQAQFCAFKAIkEBYgBSgCGBAjIAVBADoAPwwCCwsgBSgCJBAWAkAgBSgCLARAIAUoAiwgBSgCGDYCAAwBCyAFKAIYECMLIAVBAToAPwsgBS0AP0EBcSEAIAVBQGskACAAC+8CAQF/IwBBIGsiAiQAIAIgADYCGCACIAE2AhQCQCACKAIYRQRAIAIgAigCFDYCHAwBCyACIAIoAhg2AggDQCACKAIIKAIABEAgAiACKAIIKAIANgIIDAELCwNAIAIoAhQEQCACIAIoAhQoAgA2AhAgAkEANgIEIAIgAigCGDYCDANAAkAgAigCDEUNAAJAIAIoAgwvAQggAigCFC8BCEcNACACKAIMLwEKIAIoAhQvAQpHDQAgAigCDC8BCgRAIAIoAgwoAgwgAigCFCgCDCACKAIMLwEKEFQNAQsgAigCDCIAIAAoAgQgAigCFCgCBEGABnFyNgIEIAJBATYCBAwBCyACIAIoAgwoAgA2AgwMAQsLIAIoAhRBADYCAAJAIAIoAgQEQCACKAIUECMMAQsgAigCCCACKAIUIgA2AgAgAiAANgIICyACIAIoAhA2AhQMAQsLIAIgAigCGDYCHAsgAigCHCEAIAJBIGokACAAC10BAX8jAEEQayICJAAgAiAANgIIIAIgATYCBAJAIAIoAgRFBEAgAkEANgIMDAELIAIgAigCCCACKAIEKAIAIAIoAgQvAQStEDU2AgwLIAIoAgwhACACQRBqJAAgAAuPAQEBfyMAQRBrIgIkACACIAA2AgggAiABNgIEAkACQCACKAIIBEAgAigCBA0BCyACIAIoAgggAigCBEY2AgwMAQsgAigCCC8BBCACKAIELwEERwRAIAJBADYCDAwBCyACIAIoAggoAgAgAigCBCgCACACKAIILwEEEFRFNgIMCyACKAIMIQAgAkEQaiQAIAALVQEBfyMAQRBrIgEkACABIAA2AgwgAUEAQQBBABAaNgIIIAEoAgwEQCABIAEoAgggASgCDCgCACABKAIMLwEEEBo2AggLIAEoAgghACABQRBqJAAgAAugAQEBfyMAQSBrIgUkACAFIAA2AhggBSABNgIUIAUgAjsBEiAFIAM6ABEgBSAENgIMIAUgBSgCGCAFKAIUIAUvARIgBS0AEUEBcSAFKAIMEGAiADYCCAJAIABFBEAgBUEANgIcDAELIAUgBSgCCCAFLwESQQAgBSgCDBBSNgIEIAUoAggQFSAFIAUoAgQ2AhwLIAUoAhwhACAFQSBqJAAgAAtfAQF/IwBBEGsiAiQAIAIgADYCCCACIAE6AAcgAiACKAIIQgEQHjYCAAJAIAIoAgBFBEAgAkF/NgIMDAELIAIoAgAgAi0ABzoAACACQQA2AgwLIAIoAgwaIAJBEGokAAtUAQF/IwBBEGsiASQAIAEgADYCCCABIAEoAghCARAeNgIEAkAgASgCBEUEQCABQQA6AA8MAQsgASABKAIELQAAOgAPCyABLQAPIQAgAUEQaiQAIAALOAEBfyMAQRBrIgEgADYCDCABKAIMQQA2AgAgASgCDEEANgIEIAEoAgxBADYCCCABKAIMQQA6AAwLnwIBAX8jAEFAaiIFJAAgBSAANwMwIAUgATcDKCAFIAI2AiQgBSADNwMYIAUgBDYCFCAFAn8gBSkDGEIQVARAIAUoAhRBEkEAEBRBAAwBCyAFKAIkCzYCBAJAIAUoAgRFBEAgBUJ/NwM4DAELAkACQAJAAkACQCAFKAIEKAIIDgMCAAEDCyAFIAUpAzAgBSgCBCkDAHw3AwgMAwsgBSAFKQMoIAUoAgQpAwB8NwMIDAILIAUgBSgCBCkDADcDCAwBCyAFKAIUQRJBABAUIAVCfzcDOAwBCwJAIAUpAwhCAFkEQCAFKQMIIAUpAyhYDQELIAUoAhRBEkEAEBQgBUJ/NwM4DAELIAUgBSkDCDcDOAsgBSkDOCEAIAVBQGskACAAC+oBAgF/AX4jAEEgayIEJAAgBCAANgIYIAQgATYCFCAEIAI2AhAgBCADNgIMIAQgBCgCDBCTASIANgIIAkAgAEUEQCAEQQA2AhwMAQsjAEEQayIAIAQoAhg2AgwgACgCDCIAIAAoAjBBAWo2AjAgBCgCCCAEKAIYNgIAIAQoAgggBCgCFDYCBCAEKAIIIAQoAhA2AgggBCgCGCAEKAIQQQBCAEEOIAQoAhQRCgAhBSAEKAIIIAU3AxggBCgCCCkDGEIAUwRAIAQoAghCPzcDGAsgBCAEKAIINgIcCyAEKAIcIQAgBEEgaiQAIAAL6gEBAX8jAEEQayIBJAAgASAANgIIIAFBOBAYIgA2AgQCQCAARQRAIAEoAghBDkEAEBQgAUEANgIMDAELIAEoAgRBADYCACABKAIEQQA2AgQgASgCBEEANgIIIAEoAgRBADYCICABKAIEQQA2AiQgASgCBEEAOgAoIAEoAgRBADYCLCABKAIEQQE2AjAjAEEQayIAIAEoAgRBDGo2AgwgACgCDEEANgIAIAAoAgxBADYCBCAAKAIMQQA2AgggASgCBEEAOgA0IAEoAgRBADoANSABIAEoAgQ2AgwLIAEoAgwhACABQRBqJAAgAAuwAQIBfwF+IwBBIGsiAyQAIAMgADYCGCADIAE2AhQgAyACNgIQIAMgAygCEBCTASIANgIMAkAgAEUEQCADQQA2AhwMAQsgAygCDCADKAIYNgIEIAMoAgwgAygCFDYCCCADKAIUQQBCAEEOIAMoAhgRDgAhBCADKAIMIAQ3AxggAygCDCkDGEIAUwRAIAMoAgxCPzcDGAsgAyADKAIMNgIcCyADKAIcIQAgA0EgaiQAIAALwwIBAX8jAEEQayIDIAA2AgwgAyABNgIIIAMgAjYCBCADKAIIKQMAQgKDQgBSBEAgAygCDCADKAIIKQMQNwMQCyADKAIIKQMAQgSDQgBSBEAgAygCDCADKAIIKQMYNwMYCyADKAIIKQMAQgiDQgBSBEAgAygCDCADKAIIKQMgNwMgCyADKAIIKQMAQhCDQgBSBEAgAygCDCADKAIIKAIoNgIoCyADKAIIKQMAQiCDQgBSBEAgAygCDCADKAIIKAIsNgIsCyADKAIIKQMAQsAAg0IAUgRAIAMoAgwgAygCCC8BMDsBMAsgAygCCCkDAEKAAYNCAFIEQCADKAIMIAMoAggvATI7ATILIAMoAggpAwBCgAKDQgBSBEAgAygCDCADKAIIKAI0NgI0CyADKAIMIgAgAygCCCkDACAAKQMAhDcDAEEAC1oBAX8jAEEQayIBIAA2AggCQAJAIAEoAggoAgBBAE4EQCABKAIIKAIAQYAUKAIASA0BCyABQQA2AgwMAQsgASABKAIIKAIAQQJ0QZAUaigCADYCDAsgASgCDAumAQEBfyMAQSBrIgUkACAFIAA2AhggBSABNwMQIAUgAjYCDCAFIAM2AgggBSAENgIEIAUgBSgCGCAFKQMQIAUoAgxBABBFIgA2AgACQCAARQRAIAVBfzYCHAwBCyAFKAIIBEAgBSgCCCAFKAIALwEIQQh2OgAACyAFKAIEBEAgBSgCBCAFKAIAKAJENgIACyAFQQA2AhwLIAUoAhwhACAFQSBqJAAgAAucBgECfyMAQSBrIgIkACACIAA2AhggAiABNwMQAkAgAikDECACKAIYKQMwWgRAIAIoAhhBCGpBEkEAEBQgAkF/NgIcDAELIAIoAhgoAhhBAnEEQCACKAIYQQhqQRlBABAUIAJBfzYCHAwBCyACIAIoAhggAikDEEEAIAIoAhhBCGoQTiIANgIMIABFBEAgAkF/NgIcDAELIAIoAhgoAlAgAigCDCACKAIYQQhqEFhBAXFFBEAgAkF/NgIcDAELAn8gAigCGCEDIAIpAxAhASMAQTBrIgAkACAAIAM2AiggACABNwMgIABBATYCHAJAIAApAyAgACgCKCkDMFoEQCAAKAIoQQhqQRJBABAUIABBfzYCLAwBCwJAIAAoAhwNACAAKAIoKAJAIAApAyCnQQR0aigCBEUNACAAKAIoKAJAIAApAyCnQQR0aigCBCgCAEECcUUNAAJAIAAoAigoAkAgACkDIKdBBHRqKAIABEAgACAAKAIoIAApAyBBCCAAKAIoQQhqEE4iAzYCDCADRQRAIABBfzYCLAwECyAAIAAoAiggACgCDEEAQQAQVzcDEAJAIAApAxBCAFMNACAAKQMQIAApAyBRDQAgACgCKEEIakEKQQAQFCAAQX82AiwMBAsMAQsgAEEANgIMCyAAIAAoAiggACkDIEEAIAAoAihBCGoQTiIDNgIIIANFBEAgAEF/NgIsDAILIAAoAgwEQCAAKAIoKAJQIAAoAgwgACkDIEEAIAAoAihBCGoQdUEBcUUEQCAAQX82AiwMAwsLIAAoAigoAlAgACgCCCAAKAIoQQhqEFhBAXFFBEAgACgCKCgCUCAAKAIMQQAQWBogAEF/NgIsDAILCyAAKAIoKAJAIAApAyCnQQR0aigCBBA5IAAoAigoAkAgACkDIKdBBHRqQQA2AgQgACgCKCgCQCAAKQMgp0EEdGoQYyAAQQA2AiwLIAAoAiwhAyAAQTBqJAAgAwsEQCACQX82AhwMAQsgAigCGCgCQCACKQMQp0EEdGpBAToADCACQQA2AhwLIAIoAhwhACACQSBqJAAgAAulBAEBfyMAQTBrIgUkACAFIAA2AiggBSABNwMgIAUgAjYCHCAFIAM6ABsgBSAENgIUAkAgBSgCKCAFKQMgQQBBABBFRQRAIAVBfzYCLAwBCyAFKAIoKAIYQQJxBEAgBSgCKEEIakEZQQAQFCAFQX82AiwMAQsgBSAFKAIoKAJAIAUpAyCnQQR0ajYCECAFAn8gBSgCECgCAARAIAUoAhAoAgAvAQhBCHYMAQtBAws6AAsgBQJ/IAUoAhAoAgAEQCAFKAIQKAIAKAJEDAELQYCA2I14CzYCBEEBIQAgBSAFLQAbIAUtAAtGBH8gBSgCFCAFKAIERwVBAQtBAXE2AgwCQCAFKAIMBEAgBSgCECgCBEUEQCAFKAIQKAIAED8hACAFKAIQIAA2AgQgAEUEQCAFKAIoQQhqQQ5BABAUIAVBfzYCLAwECwsgBSgCECgCBCAFKAIQKAIELwEIQf8BcSAFLQAbQQh0cjsBCCAFKAIQKAIEIAUoAhQ2AkQgBSgCECgCBCIAIAAoAgBBEHI2AgAMAQsgBSgCECgCBARAIAUoAhAoAgQiACAAKAIAQW9xNgIAAkAgBSgCECgCBCgCAEUEQCAFKAIQKAIEEDkgBSgCEEEANgIEDAELIAUoAhAoAgQgBSgCECgCBC8BCEH/AXEgBS0AC0EIdHI7AQggBSgCECgCBCAFKAIENgJECwsLIAVBADYCLAsgBSgCLCEAIAVBMGokACAAC90PAgF/AX4jAEFAaiIEJAAgBCAANgI0IARCfzcDKCAEIAE2AiQgBCACNgIgIAQgAzYCHAJAIAQoAjQoAhhBAnEEQCAEKAI0QQhqQRlBABAUIARCfzcDOAwBCyAEIAQoAjQpAzA3AxAgBCkDKEJ/UQRAIARCfzcDCCAEKAIcQYDAAHEEQCAEIAQoAjQgBCgCJCAEKAIcQQAQVzcDCAsgBCkDCEJ/UQRAIAQoAjQhASMAQUBqIgAkACAAIAE2AjQCQCAAKAI0KQM4IAAoAjQpAzBCAXxYBEAgACAAKAI0KQM4NwMYIAAgACkDGEIBhjcDEAJAIAApAxBCEFQEQCAAQhA3AxAMAQsgACkDEEKACFYEQCAAQoAINwMQCwsgACAAKQMQIAApAxh8NwMYIAAgACkDGKdBBHStNwMIIAApAwggACgCNCkDOKdBBHStVARAIAAoAjRBCGpBDkEAEBQgAEJ/NwM4DAILIAAgACgCNCgCQCAAKQMYp0EEdBBINgIkIAAoAiRFBEAgACgCNEEIakEOQQAQFCAAQn83AzgMAgsgACgCNCAAKAIkNgJAIAAoAjQgACkDGDcDOAsgACgCNCIBKQMwIQUgASAFQgF8NwMwIAAgBTcDKCAAKAI0KAJAIAApAyinQQR0ahCQASAAIAApAyg3AzgLIAApAzghBSAAQUBrJAAgBCAFNwMIIAVCAFMEQCAEQn83AzgMAwsLIAQgBCkDCDcDKAsCQCAEKAIkRQ0AIAQoAjQhASAEKQMoIQUgBCgCJCECIAQoAhwhAyMAQUBqIgAkACAAIAE2AjggACAFNwMwIAAgAjYCLCAAIAM2AigCQCAAKQMwIAAoAjgpAzBaBEAgACgCOEEIakESQQAQFCAAQX82AjwMAQsgACgCOCgCGEECcQRAIAAoAjhBCGpBGUEAEBQgAEF/NgI8DAELAkACQCAAKAIsRQ0AIAAoAiwsAABFDQAgACAAKAIsIAAoAiwQK0H//wNxIAAoAiggACgCOEEIahBSIgE2AiAgAUUEQCAAQX82AjwMAwsCQCAAKAIoQYAwcQ0AIAAoAiBBABA6QQNHDQAgACgCIEECNgIICwwBCyAAQQA2AiALIAAgACgCOCAAKAIsQQBBABBXIgU3AxACQCAFQgBTDQAgACkDECAAKQMwUQ0AIAAoAiAQJSAAKAI4QQhqQQpBABAUIABBfzYCPAwBCwJAIAApAxBCAFMNACAAKQMQIAApAzBSDQAgACgCIBAlIABBADYCPAwBCyAAIAAoAjgoAkAgACkDMKdBBHRqNgIkAkAgACgCJCgCAARAIAAgACgCJCgCACgCMCAAKAIgEIsBQQBHOgAfDAELIABBADoAHwsCQCAALQAfQQFxDQAgACgCJCgCBA0AIAAoAiQoAgAQPyEBIAAoAiQgATYCBCABRQRAIAAoAjhBCGpBDkEAEBQgACgCIBAlIABBfzYCPAwCCwsgAAJ/IAAtAB9BAXEEQCAAKAIkKAIAKAIwDAELIAAoAiALQQBBACAAKAI4QQhqEEYiATYCCCABRQRAIAAoAiAQJSAAQX82AjwMAQsCQCAAKAIkKAIEBEAgACAAKAIkKAIEKAIwNgIEDAELAkAgACgCJCgCAARAIAAgACgCJCgCACgCMDYCBAwBCyAAQQA2AgQLCwJAIAAoAgQEQCAAIAAoAgRBAEEAIAAoAjhBCGoQRiIBNgIMIAFFBEAgACgCIBAlIABBfzYCPAwDCwwBCyAAQQA2AgwLIAAoAjgoAlAgACgCCCAAKQMwQQAgACgCOEEIahB1QQFxRQRAIAAoAiAQJSAAQX82AjwMAQsgACgCDARAIAAoAjgoAlAgACgCDEEAEFgaCwJAIAAtAB9BAXEEQCAAKAIkKAIEBEAgACgCJCgCBCgCAEECcQRAIAAoAiQoAgQoAjAQJSAAKAIkKAIEIgEgASgCAEF9cTYCAAJAIAAoAiQoAgQoAgBFBEAgACgCJCgCBBA5IAAoAiRBADYCBAwBCyAAKAIkKAIEIAAoAiQoAgAoAjA2AjALCwsgACgCIBAlDAELIAAoAiQoAgQoAgBBAnEEQCAAKAIkKAIEKAIwECULIAAoAiQoAgQiASABKAIAQQJyNgIAIAAoAiQoAgQgACgCIDYCMAsgAEEANgI8CyAAKAI8IQEgAEFAayQAIAFFDQAgBCgCNCkDMCAEKQMQUgRAIAQoAjQoAkAgBCkDKKdBBHRqEGIgBCgCNCAEKQMQNwMwCyAEQn83AzgMAQsgBCgCNCgCQCAEKQMop0EEdGoQYwJAIAQoAjQoAkAgBCkDKKdBBHRqKAIARQ0AIAQoAjQoAkAgBCkDKKdBBHRqKAIEBEAgBCgCNCgCQCAEKQMop0EEdGooAgQoAgBBAXENAQsgBCgCNCgCQCAEKQMop0EEdGooAgRFBEAgBCgCNCgCQCAEKQMop0EEdGooAgAQPyEAIAQoAjQoAkAgBCkDKKdBBHRqIAA2AgQgAEUEQCAEKAI0QQhqQQ5BABAUIARCfzcDOAwDCwsgBCgCNCgCQCAEKQMop0EEdGooAgRBfjYCECAEKAI0KAJAIAQpAyinQQR0aigCBCIAIAAoAgBBAXI2AgALIAQoAjQoAkAgBCkDKKdBBHRqIAQoAiA2AgggBCAEKQMoNwM4CyAEKQM4IQUgBEFAayQAIAULqgEBAX8jAEEwayICJAAgAiAANgIoIAIgATcDICACQQA2AhwCQAJAIAIoAigoAiRBAUYEQCACKAIcRQ0BIAIoAhxBAUYNASACKAIcQQJGDQELIAIoAihBDGpBEkEAEBQgAkF/NgIsDAELIAIgAikDIDcDCCACIAIoAhw2AhAgAkF/QQAgAigCKCACQQhqQhBBDBAhQgBTGzYCLAsgAigCLCEAIAJBMGokACAAC6UyAwZ/AX4BfCMAQeAAayIEJAAgBCAANgJYIAQgATYCVCAEIAI2AlACQAJAIAQoAlRBAE4EQCAEKAJYDQELIAQoAlBBEkEAEBQgBEEANgJcDAELIAQgBCgCVDYCTCMAQRBrIgAgBCgCWDYCDCAEIAAoAgwpAxg3A0BB4JoBKQMAQn9RBEAgBEF/NgIUIARBAzYCECAEQQc2AgwgBEEGNgIIIARBAjYCBCAEQQE2AgBB4JoBQQAgBBA2NwMAIARBfzYCNCAEQQ82AjAgBEENNgIsIARBDDYCKCAEQQo2AiQgBEEJNgIgQeiaAUEIIARBIGoQNjcDAAtB4JoBKQMAIAQpA0BB4JoBKQMAg1IEQCAEKAJQQRxBABAUIARBADYCXAwBC0HomgEpAwAgBCkDQEHomgEpAwCDUgRAIAQgBCgCTEEQcjYCTAsgBCgCTEEYcUEYRgRAIAQoAlBBGUEAEBQgBEEANgJcDAELIAQoAlghASAEKAJQIQIjAEHQAGsiACQAIAAgATYCSCAAIAI2AkQgAEEIahA7AkAgACgCSCAAQQhqEDgEQCMAQRBrIgEgACgCSDYCDCAAIAEoAgxBDGo2AgQjAEEQayIBIAAoAgQ2AgwCQCABKAIMKAIAQQVHDQAjAEEQayIBIAAoAgQ2AgwgASgCDCgCBEEsRw0AIABBADYCTAwCCyAAKAJEIAAoAgQQQyAAQX82AkwMAQsgAEEBNgJMCyAAKAJMIQEgAEHQAGokACAEIAE2AjwCQAJAAkAgBCgCPEEBag4CAAECCyAEQQA2AlwMAgsgBCgCTEEBcUUEQCAEKAJQQQlBABAUIARBADYCXAwCCyAEIAQoAlggBCgCTCAEKAJQEGo2AlwMAQsgBCgCTEECcQRAIAQoAlBBCkEAEBQgBEEANgJcDAELIAQoAlgQSUEASARAIAQoAlAgBCgCWBAXIARBADYCXAwBCwJAIAQoAkxBCHEEQCAEIAQoAlggBCgCTCAEKAJQEGo2AjgMAQsgBCgCWCEAIAQoAkwhASAEKAJQIQIjAEHwAGsiAyQAIAMgADYCaCADIAE2AmQgAyACNgJgIANBIGoQOwJAIAMoAmggA0EgahA4QQBIBEAgAygCYCADKAJoEBcgA0EANgJsDAELIAMpAyBCBINQBEAgAygCYEEEQYoBEBQgA0EANgJsDAELIAMgAykDODcDGCADIAMoAmggAygCZCADKAJgEGoiADYCXCAARQRAIANBADYCbAwBCwJAIAMpAxhQRQ0AIAMoAmgQngFBAXFFDQAgAyADKAJcNgJsDAELIAMoAlwhACADKQMYIQkjAEHgAGsiAiQAIAIgADYCWCACIAk3A1ACQCACKQNQQhZUBEAgAigCWEEIakETQQAQFCACQQA2AlwMAQsgAgJ+IAIpA1BCqoAEVARAIAIpA1AMAQtCqoAECzcDMCACKAJYKAIAQgAgAikDMH1BAhAnQQBIBEAjAEEQayIAIAIoAlgoAgA2AgwgAiAAKAIMQQxqNgIIAkACfyMAQRBrIgAgAigCCDYCDCAAKAIMKAIAQQRGCwRAIwBBEGsiACACKAIINgIMIAAoAgwoAgRBFkYNAQsgAigCWEEIaiACKAIIEEMgAkEANgJcDAILCyACIAIoAlgoAgAQSiIJNwM4IAlCAFMEQCACKAJYQQhqIAIoAlgoAgAQFyACQQA2AlwMAQsgAiACKAJYKAIAIAIpAzBBACACKAJYQQhqEEEiADYCDCAARQRAIAJBADYCXAwBCyACQn83AyAgAkEANgJMIAIpAzBCqoAEWgRAIAIoAgxCFBAsGgsgAkEQakETQQAQFCACIAIoAgxCABAeNgJEA0ACQCACKAJEIQEgAigCDBAvQhJ9pyEFIwBBIGsiACQAIAAgATYCGCAAIAU2AhQgAEHsEjYCECAAQQQ2AgwCQAJAIAAoAhQgACgCDE8EQCAAKAIMDQELIABBADYCHAwBCyAAIAAoAhhBAWs2AggDQAJAIAAgACgCCEEBaiAAKAIQLQAAIAAoAhggACgCCGsgACgCFCAAKAIMa2oQqwEiATYCCCABRQ0AIAAoAghBAWogACgCEEEBaiAAKAIMQQFrEFQNASAAIAAoAgg2AhwMAgsLIABBADYCHAsgACgCHCEBIABBIGokACACIAE2AkQgAUUNACACKAIMIAIoAkQCfyMAQRBrIgAgAigCDDYCDCAAKAIMKAIEC2usECwaIAIoAlghASACKAIMIQUgAikDOCEJIwBB8ABrIgAkACAAIAE2AmggACAFNgJkIAAgCTcDWCAAIAJBEGo2AlQjAEEQayIBIAAoAmQ2AgwgAAJ+IAEoAgwtAABBAXEEQCABKAIMKQMQDAELQgALNwMwAkAgACgCZBAvQhZUBEAgACgCVEETQQAQFCAAQQA2AmwMAQsgACgCZEIEEB4oAABB0JaVMEcEQCAAKAJUQRNBABAUIABBADYCbAwBCwJAAkAgACkDMEIUVA0AIwBBEGsiASAAKAJkNgIMIAEoAgwoAgQgACkDMKdqQRRrKAAAQdCWmThHDQAgACgCZCAAKQMwQhR9ECwaIAAoAmgoAgAhBSAAKAJkIQYgACkDWCEJIAAoAmgoAhQhByAAKAJUIQgjAEGwAWsiASQAIAEgBTYCqAEgASAGNgKkASABIAk3A5gBIAEgBzYClAEgASAINgKQASMAQRBrIgUgASgCpAE2AgwgAQJ+IAUoAgwtAABBAXEEQCAFKAIMKQMQDAELQgALNwMYIAEoAqQBQgQQHhogASABKAKkARAdQf//A3E2AhAgASABKAKkARAdQf//A3E2AgggASABKAKkARAwNwM4AkAgASkDOEL///////////8AVgRAIAEoApABQQRBFhAUIAFBADYCrAEMAQsgASkDOEI4fCABKQMYIAEpA5gBfFYEQCABKAKQAUEVQQAQFCABQQA2AqwBDAELAkACQCABKQM4IAEpA5gBVA0AIAEpAzhCOHwgASkDmAECfiMAQRBrIgUgASgCpAE2AgwgBSgCDCkDCAt8Vg0AIAEoAqQBIAEpAzggASkDmAF9ECwaIAFBADoAFwwBCyABKAKoASABKQM4QQAQJ0EASARAIAEoApABIAEoAqgBEBcgAUEANgKsAQwCCyABIAEoAqgBQjggAUFAayABKAKQARBBIgU2AqQBIAVFBEAgAUEANgKsAQwCCyABQQE6ABcLIAEoAqQBQgQQHigAAEHQlpkwRwRAIAEoApABQRVBABAUIAEtABdBAXEEQCABKAKkARAWCyABQQA2AqwBDAELIAEgASgCpAEQMDcDMAJAIAEoApQBQQRxRQ0AIAEpAzAgASkDOHxCDHwgASkDmAEgASkDGHxRDQAgASgCkAFBFUEAEBQgAS0AF0EBcQRAIAEoAqQBEBYLIAFBADYCrAEMAQsgASgCpAFCBBAeGiABIAEoAqQBECo2AgwgASABKAKkARAqNgIEIAEoAhBB//8DRgRAIAEgASgCDDYCEAsgASgCCEH//wNGBEAgASABKAIENgIICwJAIAEoApQBQQRxRQ0AIAEoAgggASgCBEYEQCABKAIQIAEoAgxGDQELIAEoApABQRVBABAUIAEtABdBAXEEQCABKAKkARAWCyABQQA2AqwBDAELAkAgASgCEEUEQCABKAIIRQ0BCyABKAKQAUEBQQAQFCABLQAXQQFxBEAgASgCpAEQFgsgAUEANgKsAQwBCyABIAEoAqQBEDA3AyggASABKAKkARAwNwMgIAEpAyggASkDIFIEQCABKAKQAUEBQQAQFCABLQAXQQFxBEAgASgCpAEQFgsgAUEANgKsAQwBCyABIAEoAqQBEDA3AzAgASABKAKkARAwNwOAAQJ/IwBBEGsiBSABKAKkATYCDCAFKAIMLQAAQQFxRQsEQCABKAKQAUEUQQAQFCABLQAXQQFxBEAgASgCpAEQFgsgAUEANgKsAQwBCyABLQAXQQFxBEAgASgCpAEQFgsCQCABKQOAAUL///////////8AWARAIAEpA4ABIAEpA4ABIAEpAzB8WA0BCyABKAKQAUEEQRYQFCABQQA2AqwBDAELIAEpA4ABIAEpAzB8IAEpA5gBIAEpAzh8VgRAIAEoApABQRVBABAUIAFBADYCrAEMAQsCQCABKAKUAUEEcUUNACABKQOAASABKQMwfCABKQOYASABKQM4fFENACABKAKQAUEVQQAQFCABQQA2AqwBDAELIAEpAyggASkDMEIugFYEQCABKAKQAUEVQQAQFCABQQA2AqwBDAELIAEgASkDKCABKAKQARCEASIFNgKMASAFRQRAIAFBADYCrAEMAQsgASgCjAFBAToALCABKAKMASABKQMwNwMYIAEoAowBIAEpA4ABNwMgIAEgASgCjAE2AqwBCyABKAKsASEFIAFBsAFqJAAgACAFNgJQDAELIAAoAmQgACkDMBAsGiAAKAJkIQUgACkDWCEJIAAoAmgoAhQhBiAAKAJUIQcjAEHQAGsiASQAIAEgBTYCSCABIAk3A0AgASAGNgI8IAEgBzYCOAJAIAEoAkgQL0IWVARAIAEoAjhBFUEAEBQgAUEANgJMDAELIwBBEGsiBSABKAJINgIMIAECfiAFKAIMLQAAQQFxBEAgBSgCDCkDEAwBC0IACzcDCCABKAJIQgQQHhogASgCSBAqBEAgASgCOEEBQQAQFCABQQA2AkwMAQsgASABKAJIEB1B//8Dca03AyggASABKAJIEB1B//8Dca03AyAgASkDICABKQMoUgRAIAEoAjhBE0EAEBQgAUEANgJMDAELIAEgASgCSBAqrTcDGCABIAEoAkgQKq03AxAgASkDECABKQMQIAEpAxh8VgRAIAEoAjhBBEEWEBQgAUEANgJMDAELIAEpAxAgASkDGHwgASkDQCABKQMIfFYEQCABKAI4QRVBABAUIAFBADYCTAwBCwJAIAEoAjxBBHFFDQAgASkDECABKQMYfCABKQNAIAEpAwh8UQ0AIAEoAjhBFUEAEBQgAUEANgJMDAELIAEgASkDICABKAI4EIQBIgU2AjQgBUUEQCABQQA2AkwMAQsgASgCNEEAOgAsIAEoAjQgASkDGDcDGCABKAI0IAEpAxA3AyAgASABKAI0NgJMCyABKAJMIQUgAUHQAGokACAAIAU2AlALIAAoAlBFBEAgAEEANgJsDAELIAAoAmQgACkDMEIUfBAsGiAAIAAoAmQQHTsBTiAAKAJQKQMgIAAoAlApAxh8IAApA1ggACkDMHxWBEAgACgCVEEVQQAQFCAAKAJQECQgAEEANgJsDAELAkAgAC8BTkUEQCAAKAJoKAIEQQRxRQ0BCyAAKAJkIAApAzBCFnwQLBogACAAKAJkEC83AyACQCAAKQMgIAAvAU6tWgRAIAAoAmgoAgRBBHFFDQEgACkDICAALwFOrVENAQsgACgCVEEVQQAQFCAAKAJQECQgAEEANgJsDAILIAAvAU4EQCAAKAJkIAAvAU6tEB4gAC8BTkEAIAAoAlQQUiEBIAAoAlAgATYCKCABRQRAIAAoAlAQJCAAQQA2AmwMAwsLCwJAIAAoAlApAyAgACkDWFoEQCAAKAJkIAAoAlApAyAgACkDWH0QLBogACAAKAJkIAAoAlApAxgQHiIBNgIcIAFFBEAgACgCVEEVQQAQFCAAKAJQECQgAEEANgJsDAMLIAAgACgCHCAAKAJQKQMYECkiATYCLCABRQRAIAAoAlRBDkEAEBQgACgCUBAkIABBADYCbAwDCwwBCyAAQQA2AiwgACgCaCgCACAAKAJQKQMgQQAQJ0EASARAIAAoAlQgACgCaCgCABAXIAAoAlAQJCAAQQA2AmwMAgsgACgCaCgCABBKIAAoAlApAyBSBEAgACgCVEETQQAQFCAAKAJQECQgAEEANgJsDAILCyAAIAAoAlApAxg3AzggAEIANwNAA0ACQCAAKQM4UA0AIABBADoAGyAAKQNAIAAoAlApAwhRBEAgACgCUC0ALEEBcQ0BIAApAzhCLlQNASAAKAJQQoCABCAAKAJUEIMBQQFxRQRAIAAoAlAQJCAAKAIsEBYgAEEANgJsDAQLIABBAToAGwsjAEEQayIBJAAgAUHYABAYIgU2AggCQCAFRQRAIAFBADYCDAwBCyABKAIIEE8gASABKAIINgIMCyABKAIMIQUgAUEQaiQAIAUhASAAKAJQKAIAIAApA0CnQQR0aiABNgIAAkAgAQRAIAAgACgCUCgCACAAKQNAp0EEdGooAgAgACgCaCgCACAAKAIsQQAgACgCVBDGASIJNwMQIAlCAFkNAQsCQCAALQAbQQFxRQ0AIwBBEGsiASAAKAJUNgIMIAEoAgwoAgBBE0cNACAAKAJUQRVBABAUCyAAKAJQECQgACgCLBAWIABBADYCbAwDCyAAIAApA0BCAXw3A0AgACAAKQM4IAApAxB9NwM4DAELCwJAIAApA0AgACgCUCkDCFEEQCAAKQM4UA0BCyAAKAJUQRVBABAUIAAoAiwQFiAAKAJQECQgAEEANgJsDAELIAAoAmgoAgRBBHEEQAJAIAAoAiwEQCAAIAAoAiwQR0EBcToADwwBCyAAIAAoAmgoAgAQSjcDACAAKQMAQgBTBEAgACgCVCAAKAJoKAIAEBcgACgCUBAkIABBADYCbAwDCyAAIAApAwAgACgCUCkDICAAKAJQKQMYfFE6AA8LIAAtAA9BAXFFBEAgACgCVEEVQQAQFCAAKAIsEBYgACgCUBAkIABBADYCbAwCCwsgACgCLBAWIAAgACgCUDYCbAsgACgCbCEBIABB8ABqJAAgAiABNgJIIAEEQAJAIAIoAkwEQCACKQMgQgBXBEAgAiACKAJYIAIoAkwgAkEQahBpNwMgCyACIAIoAlggAigCSCACQRBqEGk3AygCQCACKQMgIAIpAyhTBEAgAigCTBAkIAIgAigCSDYCTCACIAIpAyg3AyAMAQsgAigCSBAkCwwBCyACIAIoAkg2AkwCQCACKAJYKAIEQQRxBEAgAiACKAJYIAIoAkwgAkEQahBpNwMgDAELIAJCADcDIAsLIAJBADYCSAsgAiACKAJEQQFqNgJEIAIoAgwgAigCRAJ/IwBBEGsiACACKAIMNgIMIAAoAgwoAgQLa6wQLBoMAQsLIAIoAgwQFiACKQMgQgBTBEAgAigCWEEIaiACQRBqEEMgAigCTBAkIAJBADYCXAwBCyACIAIoAkw2AlwLIAIoAlwhACACQeAAaiQAIAMgADYCWCAARQRAIAMoAmAgAygCXEEIahBDIwBBEGsiACADKAJoNgIMIAAoAgwiACAAKAIwQQFqNgIwIAMoAlwQPSADQQA2AmwMAQsgAygCXCADKAJYKAIANgJAIAMoAlwgAygCWCkDCDcDMCADKAJcIAMoAlgpAxA3AzggAygCXCADKAJYKAIoNgIgIAMoAlgQFSADKAJcKAJQIQAgAygCXCkDMCEJIAMoAlxBCGohAiMAQSBrIgEkACABIAA2AhggASAJNwMQIAEgAjYCDAJAIAEpAxBQBEAgAUEBOgAfDAELIwBBIGsiACABKQMQNwMQIAAgACkDELpEAAAAAAAA6D+jOQMIAkAgACsDCEQAAOD////vQWQEQCAAQX82AgQMAQsgAAJ/IAArAwgiCkQAAAAAAADwQWMgCkQAAAAAAAAAAGZxBEAgCqsMAQtBAAs2AgQLAkAgACgCBEGAgICAeEsEQCAAQYCAgIB4NgIcDAELIAAgACgCBEEBazYCBCAAIAAoAgQgACgCBEEBdnI2AgQgACAAKAIEIAAoAgRBAnZyNgIEIAAgACgCBCAAKAIEQQR2cjYCBCAAIAAoAgQgACgCBEEIdnI2AgQgACAAKAIEIAAoAgRBEHZyNgIEIAAgACgCBEEBajYCBCAAIAAoAgQ2AhwLIAEgACgCHDYCCCABKAIIIAEoAhgoAgBNBEAgAUEBOgAfDAELIAEoAhggASgCCCABKAIMEFlBAXFFBEAgAUEAOgAfDAELIAFBAToAHwsgAS0AHxogAUEgaiQAIANCADcDEANAIAMpAxAgAygCXCkDMFQEQCADIAMoAlwoAkAgAykDEKdBBHRqKAIAKAIwQQBBACADKAJgEEY2AgwgAygCDEUEQCMAQRBrIgAgAygCaDYCDCAAKAIMIgAgACgCMEEBajYCMCADKAJcED0gA0EANgJsDAMLIAMoAlwoAlAgAygCDCADKQMQQQggAygCXEEIahB1QQFxRQRAAkAgAygCXCgCCEEKRgRAIAMoAmRBBHFFDQELIAMoAmAgAygCXEEIahBDIwBBEGsiACADKAJoNgIMIAAoAgwiACAAKAIwQQFqNgIwIAMoAlwQPSADQQA2AmwMBAsLIAMgAykDEEIBfDcDEAwBCwsgAygCXCADKAJcKAIUNgIYIAMgAygCXDYCbAsgAygCbCEAIANB8ABqJAAgBCAANgI4CyAEKAI4RQRAIAQoAlgQMRogBEEANgJcDAELIAQgBCgCODYCXAsgBCgCXCEAIARB4ABqJAAgAAuOAQEBfyMAQRBrIgIkACACIAA2AgwgAiABNgIIIAJBADYCBCACKAIIBEAjAEEQayIAIAIoAgg2AgwgAiAAKAIMKAIANgIEIAIoAggQlgFBAUYEQCMAQRBrIgAgAigCCDYCDEG0mwEgACgCDCgCBDYCAAsLIAIoAgwEQCACKAIMIAIoAgQ2AgALIAJBEGokAAuVAQEBfyMAQRBrIgEkACABIAA2AggCQAJ/IwBBEGsiACABKAIINgIMIAAoAgwpAxhCgIAQg1ALBEAgASgCCCgCAARAIAEgASgCCCgCABCeAUEBcToADwwCCyABQQE6AA8MAQsgASABKAIIQQBCAEESECE+AgQgASABKAIEQQBHOgAPCyABLQAPQQFxIQAgAUEQaiQAIAALfwEBfyMAQSBrIgMkACADIAA2AhggAyABNwMQIANBADYCDCADIAI2AggCQCADKQMQQv///////////wBWBEAgAygCCEEEQT0QFCADQX82AhwMAQsgAyADKAIYIAMpAxAgAygCDCADKAIIEGs2AhwLIAMoAhwhACADQSBqJAAgAAt9ACACQQFGBEAgASAAKAIIIAAoAgRrrH0hAQsCQCAAKAIUIAAoAhxLBEAgAEEAQQAgACgCJBEBABogACgCFEUNAQsgAEEANgIcIABCADcDECAAIAEgAiAAKAIoEQ8AQgBTDQAgAEIANwIEIAAgACgCAEFvcTYCAEEADwtBfwvhAgECfyMAQSBrIgMkAAJ/AkACQEGnEiABLAAAEKIBRQRAQbSbAUEcNgIADAELQZgJEBgiAg0BC0EADAELIAJBAEGQARAyIAFBKxCiAUUEQCACQQhBBCABLQAAQfIARhs2AgALAkAgAS0AAEHhAEcEQCACKAIAIQEMAQsgAEEDQQAQBCIBQYAIcUUEQCADIAFBgAhyNgIQIABBBCADQRBqEAQaCyACIAIoAgBBgAFyIgE2AgALIAJB/wE6AEsgAkGACDYCMCACIAA2AjwgAiACQZgBajYCLAJAIAFBCHENACADIANBGGo2AgAgAEGTqAEgAxAODQAgAkEKOgBLCyACQRo2AiggAkEbNgIkIAJBHDYCICACQR02AgxB6J8BKAIARQRAIAJBfzYCTAsgAkGsoAEoAgA2AjhBrKABKAIAIgAEQCAAIAI2AjQLQaygASACNgIAIAILIQAgA0EgaiQAIAAL8AEBAn8CfwJAIAFB/wFxIgMEQCAAQQNxBEADQCAALQAAIgJFDQMgAiABQf8BcUYNAyAAQQFqIgBBA3ENAAsLAkAgACgCACICQX9zIAJBgYKECGtxQYCBgoR4cQ0AIANBgYKECGwhAwNAIAIgA3MiAkF/cyACQYGChAhrcUGAgYKEeHENASAAKAIEIQIgAEEEaiEAIAJBgYKECGsgAkF/c3FBgIGChHhxRQ0ACwsDQCAAIgItAAAiAwRAIAJBAWohACADIAFB/wFxRw0BCwsgAgwCCyAAECsgAGoMAQsgAAsiAEEAIAAtAAAgAUH/AXFGGwsYACAAKAJMQX9MBEAgABCkAQ8LIAAQpAELYAIBfgJ/IAAoAighAkEBIQMgAEIAIAAtAABBgAFxBH9BAkEBIAAoAhQgACgCHEsbBUEBCyACEQ8AIgFCAFkEfiAAKAIUIAAoAhxrrCABIAAoAgggACgCBGusfXwFIAELC2sBAX8gAARAIAAoAkxBf0wEQCAAEG8PCyAAEG8PC0GwoAEoAgAEQEGwoAEoAgAQpQEhAQtBrKABKAIAIgAEQANAIAAoAkwaIAAoAhQgACgCHEsEQCAAEG8gAXIhAQsgACgCOCIADQALCyABCyIAIAAgARACIgBBgWBPBH9BtJsBQQAgAGs2AgBBfwUgAAsLUwEDfwJAIAAoAgAsAABBMGtBCk8NAANAIAAoAgAiAiwAACEDIAAgAkEBajYCACABIANqQTBrIQEgAiwAAUEwa0EKTw0BIAFBCmwhAQwACwALIAELuwIAAkAgAUEUSw0AAkACQAJAAkACQAJAAkACQAJAAkAgAUEJaw4KAAECAwQFBgcICQoLIAIgAigCACIBQQRqNgIAIAAgASgCADYCAA8LIAIgAigCACIBQQRqNgIAIAAgATQCADcDAA8LIAIgAigCACIBQQRqNgIAIAAgATUCADcDAA8LIAIgAigCAEEHakF4cSIBQQhqNgIAIAAgASkDADcDAA8LIAIgAigCACIBQQRqNgIAIAAgATIBADcDAA8LIAIgAigCACIBQQRqNgIAIAAgATMBADcDAA8LIAIgAigCACIBQQRqNgIAIAAgATAAADcDAA8LIAIgAigCACIBQQRqNgIAIAAgATEAADcDAA8LIAIgAigCAEEHakF4cSIBQQhqNgIAIAAgASsDADkDAA8LIAAgAkEYEQQACwt/AgF/AX4gAL0iA0I0iKdB/w9xIgJB/w9HBHwgAkUEQCABIABEAAAAAAAAAABhBH9BAAUgAEQAAAAAAADwQ6IgARCpASEAIAEoAgBBQGoLNgIAIAAPCyABIAJB/gdrNgIAIANC/////////4eAf4NCgICAgICAgPA/hL8FIAALC5sCACAARQRAQQAPCwJ/AkAgAAR/IAFB/wBNDQECQEGQmQEoAgAoAgBFBEAgAUGAf3FBgL8DRg0DDAELIAFB/w9NBEAgACABQT9xQYABcjoAASAAIAFBBnZBwAFyOgAAQQIMBAsgAUGAsANPQQAgAUGAQHFBgMADRxtFBEAgACABQT9xQYABcjoAAiAAIAFBDHZB4AFyOgAAIAAgAUEGdkE/cUGAAXI6AAFBAwwECyABQYCABGtB//8/TQRAIAAgAUE/cUGAAXI6AAMgACABQRJ2QfABcjoAACAAIAFBBnZBP3FBgAFyOgACIAAgAUEMdkE/cUGAAXI6AAFBBAwECwtBtJsBQRk2AgBBfwVBAQsMAQsgACABOgAAQQELC+MBAQJ/IAJBAEchAwJAAkACQCAAQQNxRQ0AIAJFDQAgAUH/AXEhBANAIAAtAAAgBEYNAiACQQFrIgJBAEchAyAAQQFqIgBBA3FFDQEgAg0ACwsgA0UNAQsCQCAALQAAIAFB/wFxRg0AIAJBBEkNACABQf8BcUGBgoQIbCEDA0AgACgCACADcyIEQX9zIARBgYKECGtxQYCBgoR4cQ0BIABBBGohACACQQRrIgJBA0sNAAsLIAJFDQAgAUH/AXEhAQNAIAEgAC0AAEYEQCAADwsgAEEBaiEAIAJBAWsiAg0ACwtBAAuLDAEGfyAAIAFqIQUCQAJAIAAoAgQiAkEBcQ0AIAJBA3FFDQEgACgCACICIAFqIQECQCAAIAJrIgBBzJsBKAIARwRAIAJB/wFNBEAgACgCCCIEIAJBA3YiAkEDdEHgmwFqRhogACgCDCIDIARHDQJBuJsBQbibASgCAEF+IAJ3cTYCAAwDCyAAKAIYIQYCQCAAIAAoAgwiA0cEQCAAKAIIIgJByJsBKAIASRogAiADNgIMIAMgAjYCCAwBCwJAIABBFGoiAigCACIEDQAgAEEQaiICKAIAIgQNAEEAIQMMAQsDQCACIQcgBCIDQRRqIgIoAgAiBA0AIANBEGohAiADKAIQIgQNAAsgB0EANgIACyAGRQ0CAkAgACAAKAIcIgRBAnRB6J0BaiICKAIARgRAIAIgAzYCACADDQFBvJsBQbybASgCAEF+IAR3cTYCAAwECyAGQRBBFCAGKAIQIABGG2ogAzYCACADRQ0DCyADIAY2AhggACgCECICBEAgAyACNgIQIAIgAzYCGAsgACgCFCICRQ0CIAMgAjYCFCACIAM2AhgMAgsgBSgCBCICQQNxQQNHDQFBwJsBIAE2AgAgBSACQX5xNgIEIAAgAUEBcjYCBCAFIAE2AgAPCyAEIAM2AgwgAyAENgIICwJAIAUoAgQiAkECcUUEQCAFQdCbASgCAEYEQEHQmwEgADYCAEHEmwFBxJsBKAIAIAFqIgE2AgAgACABQQFyNgIEIABBzJsBKAIARw0DQcCbAUEANgIAQcybAUEANgIADwsgBUHMmwEoAgBGBEBBzJsBIAA2AgBBwJsBQcCbASgCACABaiIBNgIAIAAgAUEBcjYCBCAAIAFqIAE2AgAPCyACQXhxIAFqIQECQCACQf8BTQRAIAUoAggiBCACQQN2IgJBA3RB4JsBakYaIAQgBSgCDCIDRgRAQbibAUG4mwEoAgBBfiACd3E2AgAMAgsgBCADNgIMIAMgBDYCCAwBCyAFKAIYIQYCQCAFIAUoAgwiA0cEQCAFKAIIIgJByJsBKAIASRogAiADNgIMIAMgAjYCCAwBCwJAIAVBFGoiBCgCACICDQAgBUEQaiIEKAIAIgINAEEAIQMMAQsDQCAEIQcgAiIDQRRqIgQoAgAiAg0AIANBEGohBCADKAIQIgINAAsgB0EANgIACyAGRQ0AAkAgBSAFKAIcIgRBAnRB6J0BaiICKAIARgRAIAIgAzYCACADDQFBvJsBQbybASgCAEF+IAR3cTYCAAwCCyAGQRBBFCAGKAIQIAVGG2ogAzYCACADRQ0BCyADIAY2AhggBSgCECICBEAgAyACNgIQIAIgAzYCGAsgBSgCFCICRQ0AIAMgAjYCFCACIAM2AhgLIAAgAUEBcjYCBCAAIAFqIAE2AgAgAEHMmwEoAgBHDQFBwJsBIAE2AgAPCyAFIAJBfnE2AgQgACABQQFyNgIEIAAgAWogATYCAAsgAUH/AU0EQCABQQN2IgJBA3RB4JsBaiEBAn9BuJsBKAIAIgNBASACdCICcUUEQEG4mwEgAiADcjYCACABDAELIAEoAggLIQIgASAANgIIIAIgADYCDCAAIAE2AgwgACACNgIIDwtBHyECIABCADcCECABQf///wdNBEAgAUEIdiICIAJBgP4/akEQdkEIcSIEdCICIAJBgOAfakEQdkEEcSIDdCICIAJBgIAPakEQdkECcSICdEEPdiADIARyIAJyayICQQF0IAEgAkEVanZBAXFyQRxqIQILIAAgAjYCHCACQQJ0QeidAWohBwJAAkBBvJsBKAIAIgRBASACdCIDcUUEQEG8mwEgAyAEcjYCACAHIAA2AgAgACAHNgIYDAELIAFBAEEZIAJBAXZrIAJBH0YbdCECIAcoAgAhAwNAIAMiBCgCBEF4cSABRg0CIAJBHXYhAyACQQF0IQIgBCADQQRxaiIHQRBqKAIAIgMNAAsgByAANgIQIAAgBDYCGAsgACAANgIMIAAgADYCCA8LIAQoAggiASAANgIMIAQgADYCCCAAQQA2AhggACAENgIMIAAgATYCCAsL+QIBAX8jAEEgayIEJAAgBCAANgIYIAQgATcDECAEIAI2AgwgBCADNgIIIAQgBCgCGCAEKAIYIAQpAxAgBCgCDCAEKAIIEK4BIgA2AgACQCAARQRAIARBADYCHAwBCyAEKAIAEElBAEgEQCAEKAIYQQhqIAQoAgAQFyAEKAIAEBsgBEEANgIcDAELIAQoAhghAiMAQRBrIgAkACAAIAI2AgggAEEYEBgiAjYCBAJAIAJFBEAgACgCCEEIakEOQQAQFCAAQQA2AgwMAQsgACgCBCAAKAIINgIAIwBBEGsiAiAAKAIEQQRqNgIMIAIoAgxBADYCACACKAIMQQA2AgQgAigCDEEANgIIIAAoAgRBADoAECAAKAIEQQA2AhQgACAAKAIENgIMCyAAKAIMIQIgAEEQaiQAIAQgAjYCBCACRQRAIAQoAgAQGyAEQQA2AhwMAQsgBCgCBCAEKAIANgIUIAQgBCgCBDYCHAsgBCgCHCEAIARBIGokACAAC7cOAgN/AX4jAEHAAWsiBSQAIAUgADYCuAEgBSABNgK0ASAFIAI3A6gBIAUgAzYCpAEgBUIANwOYASAFQgA3A5ABIAUgBDYCjAECQCAFKAK4AUUEQCAFQQA2ArwBDAELAkAgBSgCtAEEQCAFKQOoASAFKAK0ASkDMFQNAQsgBSgCuAFBCGpBEkEAEBQgBUEANgK8AQwBCwJAIAUoAqQBQQhxDQAgBSgCtAEoAkAgBSkDqAGnQQR0aigCCEUEQCAFKAK0ASgCQCAFKQOoAadBBHRqLQAMQQFxRQ0BCyAFKAK4AUEIakEPQQAQFCAFQQA2ArwBDAELIAUoArQBIAUpA6gBIAUoAqQBQQhyIAVByABqEH9BAEgEQCAFKAK4AUEIakEUQQAQFCAFQQA2ArwBDAELIAUoAqQBQSBxBEAgBSAFKAKkAUEEcjYCpAELAkAgBSkDmAFQBEAgBSkDkAFQDQELIAUoAqQBQQRxRQ0AIAUoArgBQQhqQRJBABAUIAVBADYCvAEMAQsCQCAFKQOYAVAEQCAFKQOQAVANAQsgBSkDmAEgBSkDmAEgBSkDkAF8WARAIAUpA2AgBSkDmAEgBSkDkAF8Wg0BCyAFKAK4AUEIakESQQAQFCAFQQA2ArwBDAELIAUpA5ABUARAIAUgBSkDYCAFKQOYAX03A5ABCyAFIAUpA5ABIAUpA2BUOgBHIAUgBSgCpAFBIHEEf0EABSAFLwF6QQBHC0EBcToARSAFIAUoAqQBQQRxBH9BAAUgBS8BeEEARwtBAXE6AEQgBQJ/IAUoAqQBQQRxBEBBACAFLwF4DQEaCyAFLQBHQX9zC0EBcToARiAFLQBFQQFxBEAgBSgCjAFFBEAgBSAFKAK4ASgCHDYCjAELIAUoAowBRQRAIAUoArgBQQhqQRpBABAUIAVBADYCvAEMAgsLIAUpA2hQBEAgBSAFKAK4AUEAQgBBABB+NgK8AQwBCwJAAkAgBS0AR0EBcUUNACAFLQBFQQFxDQAgBS0AREEBcQ0AIAUgBSkDkAE3AyAgBSAFKQOQATcDKCAFQQA7ATggBSAFKAJwNgIwIAVC3AA3AwggBSAFKAK0ASgCACAFKQOYASAFKQOQASAFQQhqQQAgBSgCtAEgBSkDqAEgBSgCuAFBCGoQZCIANgKIAQwBCyAFIAUoArQBIAUpA6gBIAUoAqQBIAUoArgBQQhqEEUiADYCBCAARQRAIAVBADYCvAEMAgsgBSAFKAK0ASgCAEIAIAUpA2ggBUHIAGogBSgCBC8BDEEBdkEDcSAFKAK0ASAFKQOoASAFKAK4AUEIahBkIgA2AogBCyAARQRAIAVBADYCvAEMAQsCfyAFKAKIASEAIAUoArQBIQMjAEEQayIBJAAgASAANgIMIAEgAzYCCCABKAIMIAEoAgg2AiwgASgCCCEDIAEoAgwhBCMAQSBrIgAkACAAIAM2AhggACAENgIUAkAgACgCGCgCSCAAKAIYKAJEQQFqTQRAIAAgACgCGCgCSEEKajYCDCAAIAAoAhgoAkwgACgCDEECdBBINgIQIAAoAhBFBEAgACgCGEEIakEOQQAQFCAAQX82AhwMAgsgACgCGCAAKAIMNgJIIAAoAhggACgCEDYCTAsgACgCFCEEIAAoAhgoAkwhBiAAKAIYIgcoAkQhAyAHIANBAWo2AkQgA0ECdCAGaiAENgIAIABBADYCHAsgACgCHCEDIABBIGokACABQRBqJAAgA0EASAsEQCAFKAKIARAbIAVBADYCvAEMAQsgBS0ARUEBcQRAIAUgBS8BekEAEHwiADYCACAARQRAIAUoArgBQQhqQRhBABAUIAVBADYCvAEMAgsgBSAFKAK4ASAFKAKIASAFLwF6QQAgBSgCjAEgBSgCABEFADYChAEgBSgCiAEQGyAFKAKEAUUEQCAFQQA2ArwBDAILIAUgBSgChAE2AogBCyAFLQBEQQFxBEAgBSAFKAK4ASAFKAKIASAFLwF4ELABNgKEASAFKAKIARAbIAUoAoQBRQRAIAVBADYCvAEMAgsgBSAFKAKEATYCiAELIAUtAEZBAXEEQCAFIAUoArgBIAUoAogBQQEQrwE2AoQBIAUoAogBEBsgBSgChAFFBEAgBUEANgK8AQwCCyAFIAUoAoQBNgKIAQsCQCAFLQBHQQFxRQ0AIAUtAEVBAXFFBEAgBS0AREEBcUUNAQsgBSgCuAEhASAFKAKIASEDIAUpA5gBIQIgBSkDkAEhCCMAQSBrIgAkACAAIAE2AhwgACADNgIYIAAgAjcDECAAIAg3AwggACgCGCAAKQMQIAApAwhBAEEAQQBCACAAKAIcQQhqEGQhASAAQSBqJAAgBSABNgKEASAFKAKIARAbIAUoAoQBRQRAIAVBADYCvAEMAgsgBSAFKAKEATYCiAELIAUgBSgCiAE2ArwBCyAFKAK8ASEAIAVBwAFqJAAgAAuEAgEBfyMAQSBrIgMkACADIAA2AhggAyABNgIUIAMgAjYCEAJAIAMoAhRFBEAgAygCGEEIakESQQAQFCADQQA2AhwMAQsgA0E4EBgiADYCDCAARQRAIAMoAhhBCGpBDkEAEBQgA0EANgIcDAELIwBBEGsiACADKAIMQQhqNgIMIAAoAgxBADYCACAAKAIMQQA2AgQgACgCDEEANgIIIAMoAgwgAygCEDYCACADKAIMQQA2AgQgAygCDEIANwMoQQBBAEEAEBohACADKAIMIAA2AjAgAygCDEIANwMYIAMgAygCGCADKAIUQRQgAygCDBBmNgIcCyADKAIcIQAgA0EgaiQAIAALQwEBfyMAQRBrIgMkACADIAA2AgwgAyABNgIIIAMgAjYCBCADKAIMIAMoAgggAygCBEEAQQAQsgEhACADQRBqJAAgAAtJAQF/IwBBEGsiASQAIAEgADYCDCABKAIMBEAgASgCDCgCrEAgASgCDCgCqEAoAgQRAgAgASgCDBA3IAEoAgwQFQsgAUEQaiQAC5QFAQF/IwBBMGsiBSQAIAUgADYCKCAFIAE2AiQgBSACNgIgIAUgAzoAHyAFIAQ2AhggBUEANgIMAkAgBSgCJEUEQCAFKAIoQQhqQRJBABAUIAVBADYCLAwBCyAFIAUoAiAgBS0AH0EBcRCzASIANgIMIABFBEAgBSgCKEEIakEQQQAQFCAFQQA2AiwMAQsgBSgCICEBIAUtAB9BAXEhAiAFKAIYIQMgBSgCDCEEIwBBIGsiACQAIAAgATYCGCAAIAI6ABcgACADNgIQIAAgBDYCDCAAQbDAABAYIgE2AggCQCABRQRAIABBADYCHAwBCyMAQRBrIgEgACgCCDYCDCABKAIMQQA2AgAgASgCDEEANgIEIAEoAgxBADYCCCAAKAIIAn8gAC0AF0EBcQRAIAAoAhhBf0cEfyAAKAIYQX5GBUEBC0EBcQwBC0EAC0EARzoADiAAKAIIIAAoAgw2AqhAIAAoAgggACgCGDYCFCAAKAIIIAAtABdBAXE6ABAgACgCCEEAOgAMIAAoAghBADoADSAAKAIIQQA6AA8gACgCCCgCqEAoAgAhAQJ/AkAgACgCGEF/RwRAIAAoAhhBfkcNAQtBCAwBCyAAKAIYC0H//wNxIAAoAhAgACgCCCABEQEAIQEgACgCCCABNgKsQCABRQRAIAAoAggQNyAAKAIIEBUgAEEANgIcDAELIAAgACgCCDYCHAsgACgCHCEBIABBIGokACAFIAE2AhQgAUUEQCAFKAIoQQhqQQ5BABAUIAVBADYCLAwBCyAFIAUoAiggBSgCJEETIAUoAhQQZiIANgIQIABFBEAgBSgCFBCxASAFQQA2AiwMAQsgBSAFKAIQNgIsCyAFKAIsIQAgBUEwaiQAIAALzAEBAX8jAEEgayICIAA2AhggAiABOgAXIAICfwJAIAIoAhhBf0cEQCACKAIYQX5HDQELQQgMAQsgAigCGAs7AQ4gAkEANgIQAkADQCACKAIQQdSXASgCAEkEQCACKAIQQQxsQdiXAWovAQAgAi8BDkYEQCACLQAXQQFxBEAgAiACKAIQQQxsQdiXAWooAgQ2AhwMBAsgAiACKAIQQQxsQdiXAWooAgg2AhwMAwUgAiACKAIQQQFqNgIQDAILAAsLIAJBADYCHAsgAigCHAvkAQEBfyMAQSBrIgMkACADIAA6ABsgAyABNgIUIAMgAjYCECADQcgAEBgiADYCDAJAIABFBEAgAygCEEEBQbSbASgCABAUIANBADYCHAwBCyADKAIMIAMoAhA2AgAgAygCDCADLQAbQQFxOgAEIAMoAgwgAygCFDYCCAJAIAMoAgwoAghBAU4EQCADKAIMKAIIQQlMDQELIAMoAgxBCTYCCAsgAygCDEEAOgAMIAMoAgxBADYCMCADKAIMQQA2AjQgAygCDEEANgI4IAMgAygCDDYCHAsgAygCHCEAIANBIGokACAAC+MIAQF/IwBBQGoiAiAANgI4IAIgATYCNCACIAIoAjgoAnw2AjAgAiACKAI4KAI4IAIoAjgoAmxqNgIsIAIgAigCOCgCeDYCICACIAIoAjgoApABNgIcIAICfyACKAI4KAJsIAIoAjgoAixBhgJrSwRAIAIoAjgoAmwgAigCOCgCLEGGAmtrDAELQQALNgIYIAIgAigCOCgCQDYCFCACIAIoAjgoAjQ2AhAgAiACKAI4KAI4IAIoAjgoAmxqQYICajYCDCACIAIoAiwgAigCIEEBa2otAAA6AAsgAiACKAIsIAIoAiBqLQAAOgAKIAIoAjgoAnggAigCOCgCjAFPBEAgAiACKAIwQQJ2NgIwCyACKAIcIAIoAjgoAnRLBEAgAiACKAI4KAJ0NgIcCwNAAkAgAiACKAI4KAI4IAIoAjRqNgIoAkAgAigCKCACKAIgai0AACACLQAKRw0AIAIoAiggAigCIEEBa2otAAAgAi0AC0cNACACKAIoLQAAIAIoAiwtAABHDQAgAiACKAIoIgBBAWo2AiggAC0AASACKAIsLQABRwRADAELIAIgAigCLEECajYCLCACIAIoAihBAWo2AigDQCACIAIoAiwiAEEBajYCLCAALQABIQEgAiACKAIoIgBBAWo2AigCf0EAIAAtAAEgAUcNABogAiACKAIsIgBBAWo2AiwgAC0AASEBIAIgAigCKCIAQQFqNgIoQQAgAC0AASABRw0AGiACIAIoAiwiAEEBajYCLCAALQABIQEgAiACKAIoIgBBAWo2AihBACAALQABIAFHDQAaIAIgAigCLCIAQQFqNgIsIAAtAAEhASACIAIoAigiAEEBajYCKEEAIAAtAAEgAUcNABogAiACKAIsIgBBAWo2AiwgAC0AASEBIAIgAigCKCIAQQFqNgIoQQAgAC0AASABRw0AGiACIAIoAiwiAEEBajYCLCAALQABIQEgAiACKAIoIgBBAWo2AihBACAALQABIAFHDQAaIAIgAigCLCIAQQFqNgIsIAAtAAEhASACIAIoAigiAEEBajYCKEEAIAAtAAEgAUcNABogAiACKAIsIgBBAWo2AiwgAC0AASEBIAIgAigCKCIAQQFqNgIoQQAgAC0AASABRw0AGiACKAIsIAIoAgxJC0EBcQ0ACyACQYICIAIoAgwgAigCLGtrNgIkIAIgAigCDEGCAms2AiwgAigCJCACKAIgSgRAIAIoAjggAigCNDYCcCACIAIoAiQ2AiAgAigCJCACKAIcTg0CIAIgAigCLCACKAIgQQFrai0AADoACyACIAIoAiwgAigCIGotAAA6AAoLCyACIAIoAhQgAigCNCACKAIQcUEBdGovAQAiATYCNEEAIQAgASACKAIYSwR/IAIgAigCMEEBayIANgIwIABBAEcFQQALQQFxDQELCwJAIAIoAiAgAigCOCgCdE0EQCACIAIoAiA2AjwMAQsgAiACKAI4KAJ0NgI8CyACKAI8C5IQAQF/IwBBMGsiAiQAIAIgADYCKCACIAE2AiQgAgJ/IAIoAigoAiwgAigCKCgCDEEFa0kEQCACKAIoKAIsDAELIAIoAigoAgxBBWsLNgIgIAJBADYCECACIAIoAigoAgAoAgQ2AgwDQAJAIAJB//8DNgIcIAIgAigCKCgCvC1BKmpBA3U2AhQgAigCKCgCACgCECACKAIUSQ0AIAIgAigCKCgCACgCECACKAIUazYCFCACIAIoAigoAmwgAigCKCgCXGs2AhggAigCHCACKAIYIAIoAigoAgAoAgRqSwRAIAIgAigCGCACKAIoKAIAKAIEajYCHAsgAigCHCACKAIUSwRAIAIgAigCFDYCHAsCQCACKAIcIAIoAiBPDQACQCACKAIcRQRAIAIoAiRBBEcNAQsgAigCJEUNACACKAIcIAIoAhggAigCKCgCACgCBGpGDQELDAELQQAhACACIAIoAiRBBEYEfyACKAIcIAIoAhggAigCKCgCACgCBGpGBUEAC0EBcTYCECACKAIoQQBBACACKAIQEFwgAigCKCgCCCACKAIoKAIUQQRraiACKAIcOgAAIAIoAigoAgggAigCKCgCFEEDa2ogAigCHEEIdjoAACACKAIoKAIIIAIoAigoAhRBAmtqIAIoAhxBf3M6AAAgAigCKCgCCCACKAIoKAIUQQFraiACKAIcQX9zQQh2OgAAIAIoAigoAgAQHCACKAIYBEAgAigCGCACKAIcSwRAIAIgAigCHDYCGAsgAigCKCgCACgCDCACKAIoKAI4IAIoAigoAlxqIAIoAhgQGRogAigCKCgCACIAIAIoAhggACgCDGo2AgwgAigCKCgCACIAIAAoAhAgAigCGGs2AhAgAigCKCgCACIAIAIoAhggACgCFGo2AhQgAigCKCIAIAIoAhggACgCXGo2AlwgAiACKAIcIAIoAhhrNgIcCyACKAIcBEAgAigCKCgCACACKAIoKAIAKAIMIAIoAhwQeBogAigCKCgCACIAIAIoAhwgACgCDGo2AgwgAigCKCgCACIAIAAoAhAgAigCHGs2AhAgAigCKCgCACIAIAIoAhwgACgCFGo2AhQLIAIoAhBFDQELCyACIAIoAgwgAigCKCgCACgCBGs2AgwgAigCDARAAkAgAigCDCACKAIoKAIsTwRAIAIoAihBAjYCsC0gAigCKCgCOCACKAIoKAIAKAIAIAIoAigoAixrIAIoAigoAiwQGRogAigCKCACKAIoKAIsNgJsDAELIAIoAgwgAigCKCgCPCACKAIoKAJsa08EQCACKAIoIgAgACgCbCACKAIoKAIsazYCbCACKAIoKAI4IAIoAigoAjggAigCKCgCLGogAigCKCgCbBAZGiACKAIoKAKwLUECSQRAIAIoAigiACAAKAKwLUEBajYCsC0LCyACKAIoKAI4IAIoAigoAmxqIAIoAigoAgAoAgAgAigCDGsgAigCDBAZGiACKAIoIgAgAigCDCAAKAJsajYCbAsgAigCKCACKAIoKAJsNgJcIAIoAigiAQJ/IAIoAgwgAigCKCgCLCACKAIoKAK0LWtLBEAgAigCKCgCLCACKAIoKAK0LWsMAQsgAigCDAsgASgCtC1qNgK0LQsgAigCKCgCwC0gAigCKCgCbEkEQCACKAIoIAIoAigoAmw2AsAtCwJAIAIoAhAEQCACQQM2AiwMAQsCQCACKAIkRQ0AIAIoAiRBBEYNACACKAIoKAIAKAIEDQAgAigCKCgCbCACKAIoKAJcRw0AIAJBATYCLAwBCyACIAIoAigoAjwgAigCKCgCbGtBAWs2AhQCQCACKAIoKAIAKAIEIAIoAhRNDQAgAigCKCgCXCACKAIoKAIsSA0AIAIoAigiACAAKAJcIAIoAigoAixrNgJcIAIoAigiACAAKAJsIAIoAigoAixrNgJsIAIoAigoAjggAigCKCgCOCACKAIoKAIsaiACKAIoKAJsEBkaIAIoAigoArAtQQJJBEAgAigCKCIAIAAoArAtQQFqNgKwLQsgAiACKAIoKAIsIAIoAhRqNgIUCyACKAIUIAIoAigoAgAoAgRLBEAgAiACKAIoKAIAKAIENgIUCyACKAIUBEAgAigCKCgCACACKAIoKAI4IAIoAigoAmxqIAIoAhQQeBogAigCKCIAIAIoAhQgACgCbGo2AmwLIAIoAigoAsAtIAIoAigoAmxJBEAgAigCKCACKAIoKAJsNgLALQsgAiACKAIoKAK8LUEqakEDdTYCFCACIAIoAigoAgwgAigCFGtB//8DSwR/Qf//AwUgAigCKCgCDCACKAIUaws2AhQgAgJ/IAIoAhQgAigCKCgCLEsEQCACKAIoKAIsDAELIAIoAhQLNgIgIAIgAigCKCgCbCACKAIoKAJcazYCGAJAIAIoAhggAigCIEkEQCACKAIYRQRAIAIoAiRBBEcNAgsgAigCJEUNASACKAIoKAIAKAIEDQEgAigCGCACKAIUSw0BCyACAn8gAigCGCACKAIUSwRAIAIoAhQMAQsgAigCGAs2AhwgAgJ/QQAgAigCJEEERw0AGkEAIAIoAigoAgAoAgQNABogAigCHCACKAIYRgtBAXE2AhAgAigCKCACKAIoKAI4IAIoAigoAlxqIAIoAhwgAigCEBBcIAIoAigiACACKAIcIAAoAlxqNgJcIAIoAigoAgAQHAsgAkECQQAgAigCEBs2AiwLIAIoAiwhACACQTBqJAAgAAuyAgEBfyMAQRBrIgEkACABIAA2AggCQCABKAIIEHkEQCABQX42AgwMAQsgASABKAIIKAIcKAIENgIEIAEoAggoAhwoAggEQCABKAIIKAIoIAEoAggoAhwoAgggASgCCCgCJBEEAAsgASgCCCgCHCgCRARAIAEoAggoAiggASgCCCgCHCgCRCABKAIIKAIkEQQACyABKAIIKAIcKAJABEAgASgCCCgCKCABKAIIKAIcKAJAIAEoAggoAiQRBAALIAEoAggoAhwoAjgEQCABKAIIKAIoIAEoAggoAhwoAjggASgCCCgCJBEEAAsgASgCCCgCKCABKAIIKAIcIAEoAggoAiQRBAAgASgCCEEANgIcIAFBfUEAIAEoAgRB8QBGGzYCDAsgASgCDCEAIAFBEGokACAAC+sXAQJ/IwBB8ABrIgMgADYCbCADIAE2AmggAyACNgJkIANBfzYCXCADIAMoAmgvAQI2AlQgA0EANgJQIANBBzYCTCADQQQ2AkggAygCVEUEQCADQYoBNgJMIANBAzYCSAsgA0EANgJgA0AgAygCYCADKAJkSkUEQCADIAMoAlQ2AlggAyADKAJoIAMoAmBBAWpBAnRqLwECNgJUIAMgAygCUEEBaiIANgJQAkACQCADKAJMIABMDQAgAygCWCADKAJURw0ADAELAkAgAygCUCADKAJISARAA0AgAyADKAJsQfwUaiADKAJYQQJ0ai8BAjYCRAJAIAMoAmwoArwtQRAgAygCRGtKBEAgAyADKAJsQfwUaiADKAJYQQJ0ai8BADYCQCADKAJsIgAgAC8BuC0gAygCQEH//wNxIAMoAmwoArwtdHI7AbgtIAMoAmwvAbgtQf8BcSEBIAMoAmwoAgghAiADKAJsIgQoAhQhACAEIABBAWo2AhQgACACaiABOgAAIAMoAmwvAbgtQQh2IQEgAygCbCgCCCECIAMoAmwiBCgCFCEAIAQgAEEBajYCFCAAIAJqIAE6AAAgAygCbCADKAJAQf//A3FBECADKAJsKAK8LWt1OwG4LSADKAJsIgAgACgCvC0gAygCREEQa2o2ArwtDAELIAMoAmwiACAALwG4LSADKAJsQfwUaiADKAJYQQJ0ai8BACADKAJsKAK8LXRyOwG4LSADKAJsIgAgAygCRCAAKAK8LWo2ArwtCyADIAMoAlBBAWsiADYCUCAADQALDAELAkAgAygCWARAIAMoAlggAygCXEcEQCADIAMoAmxB/BRqIAMoAlhBAnRqLwECNgI8AkAgAygCbCgCvC1BECADKAI8a0oEQCADIAMoAmxB/BRqIAMoAlhBAnRqLwEANgI4IAMoAmwiACAALwG4LSADKAI4Qf//A3EgAygCbCgCvC10cjsBuC0gAygCbC8BuC1B/wFxIQEgAygCbCgCCCECIAMoAmwiBCgCFCEAIAQgAEEBajYCFCAAIAJqIAE6AAAgAygCbC8BuC1BCHYhASADKAJsKAIIIQIgAygCbCIEKAIUIQAgBCAAQQFqNgIUIAAgAmogAToAACADKAJsIAMoAjhB//8DcUEQIAMoAmwoArwta3U7AbgtIAMoAmwiACAAKAK8LSADKAI8QRBrajYCvC0MAQsgAygCbCIAIAAvAbgtIAMoAmxB/BRqIAMoAlhBAnRqLwEAIAMoAmwoArwtdHI7AbgtIAMoAmwiACADKAI8IAAoArwtajYCvC0LIAMgAygCUEEBazYCUAsgAyADKAJsLwG+FTYCNAJAIAMoAmwoArwtQRAgAygCNGtKBEAgAyADKAJsLwG8FTYCMCADKAJsIgAgAC8BuC0gAygCMEH//wNxIAMoAmwoArwtdHI7AbgtIAMoAmwvAbgtQf8BcSEBIAMoAmwoAgghAiADKAJsIgQoAhQhACAEIABBAWo2AhQgACACaiABOgAAIAMoAmwvAbgtQQh2IQEgAygCbCgCCCECIAMoAmwiBCgCFCEAIAQgAEEBajYCFCAAIAJqIAE6AAAgAygCbCADKAIwQf//A3FBECADKAJsKAK8LWt1OwG4LSADKAJsIgAgACgCvC0gAygCNEEQa2o2ArwtDAELIAMoAmwiACAALwG4LSADKAJsLwG8FSADKAJsKAK8LXRyOwG4LSADKAJsIgAgAygCNCAAKAK8LWo2ArwtCyADQQI2AiwCQCADKAJsKAK8LUEQIAMoAixrSgRAIAMgAygCUEEDazYCKCADKAJsIgAgAC8BuC0gAygCKEH//wNxIAMoAmwoArwtdHI7AbgtIAMoAmwvAbgtQf8BcSEBIAMoAmwoAgghAiADKAJsIgQoAhQhACAEIABBAWo2AhQgACACaiABOgAAIAMoAmwvAbgtQQh2IQEgAygCbCgCCCECIAMoAmwiBCgCFCEAIAQgAEEBajYCFCAAIAJqIAE6AAAgAygCbCADKAIoQf//A3FBECADKAJsKAK8LWt1OwG4LSADKAJsIgAgACgCvC0gAygCLEEQa2o2ArwtDAELIAMoAmwiACAALwG4LSADKAJQQQNrQf//A3EgAygCbCgCvC10cjsBuC0gAygCbCIAIAMoAiwgACgCvC1qNgK8LQsMAQsCQCADKAJQQQpMBEAgAyADKAJsLwHCFTYCJAJAIAMoAmwoArwtQRAgAygCJGtKBEAgAyADKAJsLwHAFTYCICADKAJsIgAgAC8BuC0gAygCIEH//wNxIAMoAmwoArwtdHI7AbgtIAMoAmwvAbgtQf8BcSEBIAMoAmwoAgghAiADKAJsIgQoAhQhACAEIABBAWo2AhQgACACaiABOgAAIAMoAmwvAbgtQQh2IQEgAygCbCgCCCECIAMoAmwiBCgCFCEAIAQgAEEBajYCFCAAIAJqIAE6AAAgAygCbCADKAIgQf//A3FBECADKAJsKAK8LWt1OwG4LSADKAJsIgAgACgCvC0gAygCJEEQa2o2ArwtDAELIAMoAmwiACAALwG4LSADKAJsLwHAFSADKAJsKAK8LXRyOwG4LSADKAJsIgAgAygCJCAAKAK8LWo2ArwtCyADQQM2AhwCQCADKAJsKAK8LUEQIAMoAhxrSgRAIAMgAygCUEEDazYCGCADKAJsIgAgAC8BuC0gAygCGEH//wNxIAMoAmwoArwtdHI7AbgtIAMoAmwvAbgtQf8BcSEBIAMoAmwoAgghAiADKAJsIgQoAhQhACAEIABBAWo2AhQgACACaiABOgAAIAMoAmwvAbgtQQh2IQEgAygCbCgCCCECIAMoAmwiBCgCFCEAIAQgAEEBajYCFCAAIAJqIAE6AAAgAygCbCADKAIYQf//A3FBECADKAJsKAK8LWt1OwG4LSADKAJsIgAgACgCvC0gAygCHEEQa2o2ArwtDAELIAMoAmwiACAALwG4LSADKAJQQQNrQf//A3EgAygCbCgCvC10cjsBuC0gAygCbCIAIAMoAhwgACgCvC1qNgK8LQsMAQsgAyADKAJsLwHGFTYCFAJAIAMoAmwoArwtQRAgAygCFGtKBEAgAyADKAJsLwHEFTYCECADKAJsIgAgAC8BuC0gAygCEEH//wNxIAMoAmwoArwtdHI7AbgtIAMoAmwvAbgtQf8BcSEBIAMoAmwoAgghAiADKAJsIgQoAhQhACAEIABBAWo2AhQgACACaiABOgAAIAMoAmwvAbgtQQh2IQEgAygCbCgCCCECIAMoAmwiBCgCFCEAIAQgAEEBajYCFCAAIAJqIAE6AAAgAygCbCADKAIQQf//A3FBECADKAJsKAK8LWt1OwG4LSADKAJsIgAgACgCvC0gAygCFEEQa2o2ArwtDAELIAMoAmwiACAALwG4LSADKAJsLwHEFSADKAJsKAK8LXRyOwG4LSADKAJsIgAgAygCFCAAKAK8LWo2ArwtCyADQQc2AgwCQCADKAJsKAK8LUEQIAMoAgxrSgRAIAMgAygCUEELazYCCCADKAJsIgAgAC8BuC0gAygCCEH//wNxIAMoAmwoArwtdHI7AbgtIAMoAmwvAbgtQf8BcSEBIAMoAmwoAgghAiADKAJsIgQoAhQhACAEIABBAWo2AhQgACACaiABOgAAIAMoAmwvAbgtQQh2IQEgAygCbCgCCCECIAMoAmwiBCgCFCEAIAQgAEEBajYCFCAAIAJqIAE6AAAgAygCbCADKAIIQf//A3FBECADKAJsKAK8LWt1OwG4LSADKAJsIgAgACgCvC0gAygCDEEQa2o2ArwtDAELIAMoAmwiACAALwG4LSADKAJQQQtrQf//A3EgAygCbCgCvC10cjsBuC0gAygCbCIAIAMoAgwgACgCvC1qNgK8LQsLCwsgA0EANgJQIAMgAygCWDYCXAJAIAMoAlRFBEAgA0GKATYCTCADQQM2AkgMAQsCQCADKAJYIAMoAlRGBEAgA0EGNgJMIANBAzYCSAwBCyADQQc2AkwgA0EENgJICwsLIAMgAygCYEEBajYCYAwBCwsLkQQBAX8jAEEwayIDIAA2AiwgAyABNgIoIAMgAjYCJCADQX82AhwgAyADKAIoLwECNgIUIANBADYCECADQQc2AgwgA0EENgIIIAMoAhRFBEAgA0GKATYCDCADQQM2AggLIAMoAiggAygCJEEBakECdGpB//8DOwECIANBADYCIANAIAMoAiAgAygCJEpFBEAgAyADKAIUNgIYIAMgAygCKCADKAIgQQFqQQJ0ai8BAjYCFCADIAMoAhBBAWoiADYCEAJAAkAgAygCDCAATA0AIAMoAhggAygCFEcNAAwBCwJAIAMoAhAgAygCCEgEQCADKAIsQfwUaiADKAIYQQJ0aiIAIAMoAhAgAC8BAGo7AQAMAQsCQCADKAIYBEAgAygCGCADKAIcRwRAIAMoAiwgAygCGEECdGpB/BRqIgAgAC8BAEEBajsBAAsgAygCLCIAIABBvBVqLwEAQQFqOwG8FQwBCwJAIAMoAhBBCkwEQCADKAIsIgAgAEHAFWovAQBBAWo7AcAVDAELIAMoAiwiACAAQcQVai8BAEEBajsBxBULCwsgA0EANgIQIAMgAygCGDYCHAJAIAMoAhRFBEAgA0GKATYCDCADQQM2AggMAQsCQCADKAIYIAMoAhRGBEAgA0EGNgIMIANBAzYCCAwBCyADQQc2AgwgA0EENgIICwsLIAMgAygCIEEBajYCIAwBCwsLpxIBAn8jAEHQAGsiAyAANgJMIAMgATYCSCADIAI2AkQgA0EANgI4IAMoAkwoAqAtBEADQCADIAMoAkwoAqQtIAMoAjhBAXRqLwEANgJAIAMoAkwoApgtIQAgAyADKAI4IgFBAWo2AjggAyAAIAFqLQAANgI8AkAgAygCQEUEQCADIAMoAkggAygCPEECdGovAQI2AiwCQCADKAJMKAK8LUEQIAMoAixrSgRAIAMgAygCSCADKAI8QQJ0ai8BADYCKCADKAJMIgAgAC8BuC0gAygCKEH//wNxIAMoAkwoArwtdHI7AbgtIAMoAkwvAbgtQf8BcSEBIAMoAkwoAgghAiADKAJMIgQoAhQhACAEIABBAWo2AhQgACACaiABOgAAIAMoAkwvAbgtQQh2IQEgAygCTCgCCCECIAMoAkwiBCgCFCEAIAQgAEEBajYCFCAAIAJqIAE6AAAgAygCTCADKAIoQf//A3FBECADKAJMKAK8LWt1OwG4LSADKAJMIgAgACgCvC0gAygCLEEQa2o2ArwtDAELIAMoAkwiACAALwG4LSADKAJIIAMoAjxBAnRqLwEAIAMoAkwoArwtdHI7AbgtIAMoAkwiACADKAIsIAAoArwtajYCvC0LDAELIAMgAygCPC0A0F02AjQgAyADKAJIIAMoAjRBgQJqQQJ0ai8BAjYCJAJAIAMoAkwoArwtQRAgAygCJGtKBEAgAyADKAJIIAMoAjRBgQJqQQJ0ai8BADYCICADKAJMIgAgAC8BuC0gAygCIEH//wNxIAMoAkwoArwtdHI7AbgtIAMoAkwvAbgtQf8BcSEBIAMoAkwoAgghAiADKAJMIgQoAhQhACAEIABBAWo2AhQgACACaiABOgAAIAMoAkwvAbgtQQh2IQEgAygCTCgCCCECIAMoAkwiBCgCFCEAIAQgAEEBajYCFCAAIAJqIAE6AAAgAygCTCADKAIgQf//A3FBECADKAJMKAK8LWt1OwG4LSADKAJMIgAgACgCvC0gAygCJEEQa2o2ArwtDAELIAMoAkwiACAALwG4LSADKAJIIAMoAjRBgQJqQQJ0ai8BACADKAJMKAK8LXRyOwG4LSADKAJMIgAgAygCJCAAKAK8LWo2ArwtCyADIAMoAjRBAnRBkOoAaigCADYCMCADKAIwBEAgAyADKAI8IAMoAjRBAnRBgO0AaigCAGs2AjwgAyADKAIwNgIcAkAgAygCTCgCvC1BECADKAIca0oEQCADIAMoAjw2AhggAygCTCIAIAAvAbgtIAMoAhhB//8DcSADKAJMKAK8LXRyOwG4LSADKAJMLwG4LUH/AXEhASADKAJMKAIIIQIgAygCTCIEKAIUIQAgBCAAQQFqNgIUIAAgAmogAToAACADKAJMLwG4LUEIdiEBIAMoAkwoAgghAiADKAJMIgQoAhQhACAEIABBAWo2AhQgACACaiABOgAAIAMoAkwgAygCGEH//wNxQRAgAygCTCgCvC1rdTsBuC0gAygCTCIAIAAoArwtIAMoAhxBEGtqNgK8LQwBCyADKAJMIgAgAC8BuC0gAygCPEH//wNxIAMoAkwoArwtdHI7AbgtIAMoAkwiACADKAIcIAAoArwtajYCvC0LCyADIAMoAkBBAWs2AkAgAwJ/IAMoAkBBgAJJBEAgAygCQC0A0FkMAQsgAygCQEEHdkGAAmotANBZCzYCNCADIAMoAkQgAygCNEECdGovAQI2AhQCQCADKAJMKAK8LUEQIAMoAhRrSgRAIAMgAygCRCADKAI0QQJ0ai8BADYCECADKAJMIgAgAC8BuC0gAygCEEH//wNxIAMoAkwoArwtdHI7AbgtIAMoAkwvAbgtQf8BcSEBIAMoAkwoAgghAiADKAJMIgQoAhQhACAEIABBAWo2AhQgACACaiABOgAAIAMoAkwvAbgtQQh2IQEgAygCTCgCCCECIAMoAkwiBCgCFCEAIAQgAEEBajYCFCAAIAJqIAE6AAAgAygCTCADKAIQQf//A3FBECADKAJMKAK8LWt1OwG4LSADKAJMIgAgACgCvC0gAygCFEEQa2o2ArwtDAELIAMoAkwiACAALwG4LSADKAJEIAMoAjRBAnRqLwEAIAMoAkwoArwtdHI7AbgtIAMoAkwiACADKAIUIAAoArwtajYCvC0LIAMgAygCNEECdEGQ6wBqKAIANgIwIAMoAjAEQCADIAMoAkAgAygCNEECdEGA7gBqKAIAazYCQCADIAMoAjA2AgwCQCADKAJMKAK8LUEQIAMoAgxrSgRAIAMgAygCQDYCCCADKAJMIgAgAC8BuC0gAygCCEH//wNxIAMoAkwoArwtdHI7AbgtIAMoAkwvAbgtQf8BcSEBIAMoAkwoAgghAiADKAJMIgQoAhQhACAEIABBAWo2AhQgACACaiABOgAAIAMoAkwvAbgtQQh2IQEgAygCTCgCCCECIAMoAkwiBCgCFCEAIAQgAEEBajYCFCAAIAJqIAE6AAAgAygCTCADKAIIQf//A3FBECADKAJMKAK8LWt1OwG4LSADKAJMIgAgACgCvC0gAygCDEEQa2o2ArwtDAELIAMoAkwiACAALwG4LSADKAJAQf//A3EgAygCTCgCvC10cjsBuC0gAygCTCIAIAMoAgwgACgCvC1qNgK8LQsLCyADKAI4IAMoAkwoAqAtSQ0ACwsgAyADKAJILwGCCDYCBAJAIAMoAkwoArwtQRAgAygCBGtKBEAgAyADKAJILwGACDYCACADKAJMIgAgAC8BuC0gAygCAEH//wNxIAMoAkwoArwtdHI7AbgtIAMoAkwvAbgtQf8BcSEBIAMoAkwoAgghAiADKAJMIgQoAhQhACAEIABBAWo2AhQgACACaiABOgAAIAMoAkwvAbgtQQh2IQEgAygCTCgCCCECIAMoAkwiBCgCFCEAIAQgAEEBajYCFCAAIAJqIAE6AAAgAygCTCADKAIAQf//A3FBECADKAJMKAK8LWt1OwG4LSADKAJMIgAgACgCvC0gAygCBEEQa2o2ArwtDAELIAMoAkwiACAALwG4LSADKAJILwGACCADKAJMKAK8LXRyOwG4LSADKAJMIgAgAygCBCAAKAK8LWo2ArwtCwuXAgEEfyMAQRBrIgEgADYCDAJAIAEoAgwoArwtQRBGBEAgASgCDC8BuC1B/wFxIQIgASgCDCgCCCEDIAEoAgwiBCgCFCEAIAQgAEEBajYCFCAAIANqIAI6AAAgASgCDC8BuC1BCHYhAiABKAIMKAIIIQMgASgCDCIEKAIUIQAgBCAAQQFqNgIUIAAgA2ogAjoAACABKAIMQQA7AbgtIAEoAgxBADYCvC0MAQsgASgCDCgCvC1BCE4EQCABKAIMLwG4LSECIAEoAgwoAgghAyABKAIMIgQoAhQhACAEIABBAWo2AhQgACADaiACOgAAIAEoAgwiACAALwG4LUEIdjsBuC0gASgCDCIAIAAoArwtQQhrNgK8LQsLC+8BAQR/IwBBEGsiASAANgIMAkAgASgCDCgCvC1BCEoEQCABKAIMLwG4LUH/AXEhAiABKAIMKAIIIQMgASgCDCIEKAIUIQAgBCAAQQFqNgIUIAAgA2ogAjoAACABKAIMLwG4LUEIdiECIAEoAgwoAgghAyABKAIMIgQoAhQhACAEIABBAWo2AhQgACADaiACOgAADAELIAEoAgwoArwtQQBKBEAgASgCDC8BuC0hAiABKAIMKAIIIQMgASgCDCIEKAIUIQAgBCAAQQFqNgIUIAAgA2ogAjoAAAsLIAEoAgxBADsBuC0gASgCDEEANgK8LQv8AQEBfyMAQRBrIgEgADYCDCABQQA2AggDQCABKAIIQZ4CTkUEQCABKAIMQZQBaiABKAIIQQJ0akEAOwEAIAEgASgCCEEBajYCCAwBCwsgAUEANgIIA0AgASgCCEEeTkUEQCABKAIMQYgTaiABKAIIQQJ0akEAOwEAIAEgASgCCEEBajYCCAwBCwsgAUEANgIIA0AgASgCCEETTkUEQCABKAIMQfwUaiABKAIIQQJ0akEAOwEAIAEgASgCCEEBajYCCAwBCwsgASgCDEEBOwGUCSABKAIMQQA2AqwtIAEoAgxBADYCqC0gASgCDEEANgKwLSABKAIMQQA2AqAtCyIBAX8jAEEQayIBJAAgASAANgIMIAEoAgwQFSABQRBqJAAL6QEBAX8jAEEwayICIAA2AiQgAiABNwMYIAJCADcDECACIAIoAiQpAwhCAX03AwgCQANAIAIpAxAgAikDCFQEQCACIAIpAxAgAikDCCACKQMQfUIBiHw3AwACQCACKAIkKAIEIAIpAwCnQQN0aikDACACKQMYVgRAIAIgAikDAEIBfTcDCAwBCwJAIAIpAwAgAigCJCkDCFIEQCACKAIkKAIEIAIpAwBCAXynQQN0aikDACACKQMYWA0BCyACIAIpAwA3AygMBAsgAiACKQMAQgF8NwMQCwwBCwsgAiACKQMQNwMoCyACKQMoC6cBAQF/IwBBMGsiBCQAIAQgADYCKCAEIAE2AiQgBCACNwMYIAQgAzYCFCAEIAQoAigpAzggBCgCKCkDMCAEKAIkIAQpAxggBCgCFBCRATcDCAJAIAQpAwhCAFMEQCAEQX82AiwMAQsgBCgCKCAEKQMINwM4IAQoAiggBCgCKCkDOBC/ASECIAQoAiggAjcDQCAEQQA2AiwLIAQoAiwhACAEQTBqJAAgAAvrAQEBfyMAQSBrIgMkACADIAA2AhggAyABNwMQIAMgAjYCDAJAIAMpAxAgAygCGCkDEFQEQCADQQE6AB8MAQsgAyADKAIYKAIAIAMpAxBCBIanEEgiADYCCCAARQRAIAMoAgxBDkEAEBQgA0EAOgAfDAELIAMoAhggAygCCDYCACADIAMoAhgoAgQgAykDEEIBfEIDhqcQSCIANgIEIABFBEAgAygCDEEOQQAQFCADQQA6AB8MAQsgAygCGCADKAIENgIEIAMoAhggAykDEDcDECADQQE6AB8LIAMtAB9BAXEhACADQSBqJAAgAAvOAgEBfyMAQTBrIgQkACAEIAA2AiggBCABNwMgIAQgAjYCHCAEIAM2AhgCQAJAIAQoAigNACAEKQMgUA0AIAQoAhhBEkEAEBQgBEEANgIsDAELIAQgBCgCKCAEKQMgIAQoAhwgBCgCGBBNIgA2AgwgAEUEQCAEQQA2AiwMAQsgBEEYEBgiADYCFCAARQRAIAQoAhhBDkEAEBQgBCgCDBAzIARBADYCLAwBCyAEKAIUIAQoAgw2AhAgBCgCFEEANgIUQQAQASEAIAQoAhQgADYCDCMAQRBrIgAgBCgCFDYCDCAAKAIMQQA2AgAgACgCDEEANgIEIAAoAgxBADYCCCAEQQIgBCgCFCAEKAIYEJQBIgA2AhAgAEUEQCAEKAIUKAIQEDMgBCgCFBAVIARBADYCLAwBCyAEIAQoAhA2AiwLIAQoAiwhACAEQTBqJAAgAAupAQEBfyMAQTBrIgQkACAEIAA2AiggBCABNwMgIAQgAjYCHCAEIAM2AhgCQCAEKAIoRQRAIAQpAyBCAFIEQCAEKAIYQRJBABAUIARBADYCLAwCCyAEQQBCACAEKAIcIAQoAhgQwgE2AiwMAQsgBCAEKAIoNgIIIAQgBCkDIDcDECAEIARBCGpCASAEKAIcIAQoAhgQwgE2AiwLIAQoAiwhACAEQTBqJAAgAAtGAQF/IwBBIGsiAyQAIAMgADYCHCADIAE3AxAgAyACNgIMIAMoAhwgAykDECADKAIMIAMoAhxBCGoQTiEAIANBIGokACAAC40CAQF/IwBBMGsiAyQAIAMgADYCKCADIAE7ASYgAyACNgIgIAMgAygCKCgCNCADQR5qIAMvASZBgAZBABBfNgIQAkAgAygCEEUNACADLwEeQQVJDQACQCADKAIQLQAAQQFGDQAMAQsgAyADKAIQIAMvAR6tECkiADYCFCAARQRADAELIAMoAhQQjwEaIAMgAygCFBAqNgIYIAMoAiAQjAEgAygCGEYEQCADIAMoAhQQLz0BDiADIAMoAhQgAy8BDq0QHiADLwEOQYAQQQAQUjYCCCADKAIIBEAgAygCIBAlIAMgAygCCDYCIAsLIAMoAhQQFgsgAyADKAIgNgIsIAMoAiwhACADQTBqJAAgAAvaFwIBfwF+IwBBgAFrIgUkACAFIAA2AnQgBSABNgJwIAUgAjYCbCAFIAM6AGsgBSAENgJkIAUgBSgCbEEARzoAHSAFQR5BLiAFLQBrQQFxGzYCKAJAAkAgBSgCbARAIAUoAmwQLyAFKAIorVQEQCAFKAJkQRNBABAUIAVCfzcDeAwDCwwBCyAFIAUoAnAgBSgCKK0gBUEwaiAFKAJkEEEiADYCbCAARQRAIAVCfzcDeAwCCwsgBSgCbEIEEB4hAEHxEkH2EiAFLQBrQQFxGygAACAAKAAARwRAIAUoAmRBE0EAEBQgBS0AHUEBcUUEQCAFKAJsEBYLIAVCfzcDeAwBCyAFKAJ0EE8CQCAFLQBrQQFxRQRAIAUoAmwQHSEAIAUoAnQgADsBCAwBCyAFKAJ0QQA7AQgLIAUoAmwQHSEAIAUoAnQgADsBCiAFKAJsEB0hACAFKAJ0IAA7AQwgBSgCbBAdQf//A3EhACAFKAJ0IAA2AhAgBSAFKAJsEB07AS4gBSAFKAJsEB07ASwgBS8BLiEBIAUvASwhAiMAQTBrIgAkACAAIAE7AS4gACACOwEsIABCADcCACAAQQA2AiggAEIANwIgIABCADcCGCAAQgA3AhAgAEIANwIIIABBADYCICAAIAAvASxBCXZB0ABqNgIUIAAgAC8BLEEFdkEPcUEBazYCECAAIAAvASxBH3E2AgwgACAALwEuQQt2NgIIIAAgAC8BLkEFdkE/cTYCBCAAIAAvAS5BAXRBPnE2AgAgABAMIQEgAEEwaiQAIAEhACAFKAJ0IAA2AhQgBSgCbBAqIQAgBSgCdCAANgIYIAUoAmwQKq0hBiAFKAJ0IAY3AyAgBSgCbBAqrSEGIAUoAnQgBjcDKCAFIAUoAmwQHTsBIiAFIAUoAmwQHTsBHgJAIAUtAGtBAXEEQCAFQQA7ASAgBSgCdEEANgI8IAUoAnRBADsBQCAFKAJ0QQA2AkQgBSgCdEIANwNIDAELIAUgBSgCbBAdOwEgIAUoAmwQHUH//wNxIQAgBSgCdCAANgI8IAUoAmwQHSEAIAUoAnQgADsBQCAFKAJsECohACAFKAJ0IAA2AkQgBSgCbBAqrSEGIAUoAnQgBjcDSAsCfyMAQRBrIgAgBSgCbDYCDCAAKAIMLQAAQQFxRQsEQCAFKAJkQRRBABAUIAUtAB1BAXFFBEAgBSgCbBAWCyAFQn83A3gMAQsCQCAFKAJ0LwEMQQFxBEAgBSgCdC8BDEHAAHEEQCAFKAJ0Qf//AzsBUgwCCyAFKAJ0QQE7AVIMAQsgBSgCdEEAOwFSCyAFKAJ0QQA2AjAgBSgCdEEANgI0IAUoAnRBADYCOCAFIAUvASAgBS8BIiAFLwEeamo2AiQCQCAFLQAdQQFxBEAgBSgCbBAvIAUoAiStVARAIAUoAmRBFUEAEBQgBUJ/NwN4DAMLDAELIAUoAmwQFiAFIAUoAnAgBSgCJK1BACAFKAJkEEEiADYCbCAARQRAIAVCfzcDeAwCCwsgBS8BIgRAIAUoAmwgBSgCcCAFLwEiQQEgBSgCZBCNASEAIAUoAnQgADYCMCAFKAJ0KAIwRQRAAn8jAEEQayIAIAUoAmQ2AgwgACgCDCgCAEERRgsEQCAFKAJkQRVBABAUCyAFLQAdQQFxRQRAIAUoAmwQFgsgBUJ/NwN4DAILIAUoAnQvAQxBgBBxBEAgBSgCdCgCMEECEDpBBUYEQCAFKAJkQRVBABAUIAUtAB1BAXFFBEAgBSgCbBAWCyAFQn83A3gMAwsLCyAFLwEeBEAgBSAFKAJsIAUoAnAgBS8BHkEAIAUoAmQQYDYCGCAFKAIYRQRAIAUtAB1BAXFFBEAgBSgCbBAWCyAFQn83A3gMAgsgBSgCGCAFLwEeQYACQYAEIAUtAGtBAXEbIAUoAnRBNGogBSgCZBCIAUEBcUUEQCAFKAIYEBUgBS0AHUEBcUUEQCAFKAJsEBYLIAVCfzcDeAwCCyAFKAIYEBUgBS0Aa0EBcQRAIAUoAnRBAToABAsLIAUvASAEQCAFKAJsIAUoAnAgBS8BIEEAIAUoAmQQjQEhACAFKAJ0IAA2AjggBSgCdCgCOEUEQCAFLQAdQQFxRQRAIAUoAmwQFgsgBUJ/NwN4DAILIAUoAnQvAQxBgBBxBEAgBSgCdCgCOEECEDpBBUYEQCAFKAJkQRVBABAUIAUtAB1BAXFFBEAgBSgCbBAWCyAFQn83A3gMAwsLCyAFKAJ0QfXgASAFKAJ0KAIwEMUBIQAgBSgCdCAANgIwIAUoAnRB9cYBIAUoAnQoAjgQxQEhACAFKAJ0IAA2AjgCQAJAIAUoAnQpAyhC/////w9RDQAgBSgCdCkDIEL/////D1ENACAFKAJ0KQNIQv////8PUg0BCyAFIAUoAnQoAjQgBUEWakEBQYACQYAEIAUtAGtBAXEbIAUoAmQQXzYCDCAFKAIMRQRAIAUtAB1BAXFFBEAgBSgCbBAWCyAFQn83A3gMAgsgBSAFKAIMIAUvARatECkiADYCECAARQRAIAUoAmRBDkEAEBQgBS0AHUEBcUUEQCAFKAJsEBYLIAVCfzcDeAwCCwJAIAUoAnQpAyhC/////w9RBEAgBSgCEBAwIQYgBSgCdCAGNwMoDAELIAUtAGtBAXEEQCAFKAIQIQEjAEEgayIAJAAgACABNgIYIABCCDcDECAAIAAoAhgpAxAgACkDEHw3AwgCQCAAKQMIIAAoAhgpAxBUBEAgACgCGEEAOgAAIABBfzYCHAwBCyAAIAAoAhggACkDCBAsNgIcCyAAKAIcGiAAQSBqJAALCyAFKAJ0KQMgQv////8PUQRAIAUoAhAQMCEGIAUoAnQgBjcDIAsgBS0Aa0EBcUUEQCAFKAJ0KQNIQv////8PUQRAIAUoAhAQMCEGIAUoAnQgBjcDSAsgBSgCdCgCPEH//wNGBEAgBSgCEBAqIQAgBSgCdCAANgI8CwsgBSgCEBBHQQFxRQRAIAUoAmRBFUEAEBQgBSgCEBAWIAUtAB1BAXFFBEAgBSgCbBAWCyAFQn83A3gMAgsgBSgCEBAWCwJ/IwBBEGsiACAFKAJsNgIMIAAoAgwtAABBAXFFCwRAIAUoAmRBFEEAEBQgBS0AHUEBcUUEQCAFKAJsEBYLIAVCfzcDeAwBCyAFLQAdQQFxRQRAIAUoAmwQFgsgBSgCdCkDSEL///////////8AVgRAIAUoAmRBBEEWEBQgBUJ/NwN4DAELAn8gBSgCdCEBIAUoAmQhAiMAQSBrIgAkACAAIAE2AhggACACNgIUAkAgACgCGCgCEEHjAEcEQCAAQQE6AB8MAQsgACAAKAIYKAI0IABBEmpBgbICQYAGQQAQXzYCCAJAIAAoAggEQCAALwESQQdPDQELIAAoAhRBFUEAEBQgAEEAOgAfDAELIAAgACgCCCAALwESrRApIgE2AgwgAUUEQCAAKAIUQRRBABAUIABBADoAHwwBCyAAQQE6AAcCQAJAAkAgACgCDBAdQQFrDgICAAELIAAoAhgpAyhCFFQEQCAAQQA6AAcLDAELIAAoAhRBGEEAEBQgACgCDBAWIABBADoAHwwBCyAAKAIMQgIQHi8AAEHBigFHBEAgACgCFEEYQQAQFCAAKAIMEBYgAEEAOgAfDAELAkACQAJAAkACQCAAKAIMEI8BQQFrDgMAAQIDCyAAQYECOwEEDAMLIABBggI7AQQMAgsgAEGDAjsBBAwBCyAAKAIUQRhBABAUIAAoAgwQFiAAQQA6AB8MAQsgAC8BEkEHRwRAIAAoAhRBFUEAEBQgACgCDBAWIABBADoAHwwBCyAAKAIYIAAtAAdBAXE6AAYgACgCGCAALwEEOwFSIAAoAgwQHUH//wNxIQEgACgCGCABNgIQIAAoAgwQFiAAQQE6AB8LIAAtAB9BAXEhASAAQSBqJAAgAUEBcUULBEAgBUJ/NwN4DAELIAUoAnQoAjQQhwEhACAFKAJ0IAA2AjQgBSAFKAIoIAUoAiRqrTcDeAsgBSkDeCEGIAVBgAFqJAAgBgsYAEGomwFCADcCAEGwmwFBADYCAEGomwELCABBAUEMEHYLBwAgACgCLAsHACAAKAIoCwcAIAAoAhgLtQkBAX8jAEHgwABrIgUkACAFIAA2AtRAIAUgATYC0EAgBSACNgLMQCAFIAM3A8BAIAUgBDYCvEAgBSAFKALQQDYCuEACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgBSgCvEAOEQMEAAYBAgUJCgoKCgoKCAoHCgsgBUIANwPYQAwKCyAFIAUoArhAQeQAaiAFKALMQCAFKQPAQBBCNwPYQAwJCyAFKAK4QBAVIAVCADcD2EAMCAsgBSgCuEAoAhAEQCAFIAUoArhAKAIQIAUoArhAKQMYIAUoArhAQeQAahBlIgM3A5hAIANQBEAgBUJ/NwPYQAwJCyAFKAK4QCkDCCAFKAK4QCkDCCAFKQOYQHxWBEAgBSgCuEBB5ABqQRVBABAUIAVCfzcD2EAMCQsgBSgCuEAiACAFKQOYQCAAKQMAfDcDACAFKAK4QCIAIAUpA5hAIAApAwh8NwMIIAUoArhAQQA2AhALIAUoArhALQB4QQFxRQRAIAVCADcDqEADQCAFKQOoQCAFKAK4QCkDAFQEQCAFIAUoArhAKQMAIAUpA6hAfUKAwABWBH5CgMAABSAFKAK4QCkDACAFKQOoQH0LNwOgQCAFIAUoAtRAIAVBEGogBSkDoEAQLiIDNwOwQCADQgBTBEAgBSgCuEBB5ABqIAUoAtRAEBcgBUJ/NwPYQAwLCyAFKQOwQFAEQCAFKAK4QEHkAGpBEUEAEBQgBUJ/NwPYQAwLBSAFIAUpA7BAIAUpA6hAfDcDqEAMAgsACwsLIAUoArhAIAUoArhAKQMANwMgIAVCADcD2EAMBwsgBSkDwEAgBSgCuEApAwggBSgCuEApAyB9VgRAIAUgBSgCuEApAwggBSgCuEApAyB9NwPAQAsgBSkDwEBQBEAgBUIANwPYQAwHCyAFKAK4QC0AeEEBcQRAIAUoAtRAIAUoArhAKQMgQQAQJ0EASARAIAUoArhAQeQAaiAFKALUQBAXIAVCfzcD2EAMCAsLIAUgBSgC1EAgBSgCzEAgBSkDwEAQLiIDNwOwQCADQgBTBEAgBSgCuEBB5ABqQRFBABAUIAVCfzcD2EAMBwsgBSgCuEAiACAFKQOwQCAAKQMgfDcDICAFKQOwQFAEQCAFKAK4QCkDICAFKAK4QCkDCFQEQCAFKAK4QEHkAGpBEUEAEBQgBUJ/NwPYQAwICwsgBSAFKQOwQDcD2EAMBgsgBSAFKAK4QCkDICAFKAK4QCkDAH0gBSgCuEApAwggBSgCuEApAwB9IAUoAsxAIAUpA8BAIAUoArhAQeQAahCRATcDCCAFKQMIQgBTBEAgBUJ/NwPYQAwGCyAFKAK4QCAFKQMIIAUoArhAKQMAfDcDICAFQgA3A9hADAULIAUgBSgCzEA2AgQgBSgCBCAFKAK4QEEoaiAFKAK4QEHkAGoQlQFBAEgEQCAFQn83A9hADAULIAVCADcD2EAMBAsgBSAFKAK4QCwAYKw3A9hADAMLIAUgBSgCuEApA3A3A9hADAILIAUgBSgCuEApAyAgBSgCuEApAwB9NwPYQAwBCyAFKAK4QEHkAGpBHEEAEBQgBUJ/NwPYQAsgBSkD2EAhAyAFQeDAAGokACADCwcAIAAoAhALIgEBfyMAQRBrIgEgADYCDCABKAIMIgAgACgCMEEBajYCMAsHACAAKAIICxQAIAAgAa0gAq1CIIaEIAMgBBB/CxMBAX4gABBKIgFCIIinEAAgAacLEgAgACABrSACrUIghoQgAxAnCx8BAX4gACABIAKtIAOtQiCGhBAuIgRCIIinEAAgBKcLFQAgACABrSACrUIghoQgAyAEEMMBCxQAIAAgASACrSADrUIghoQgBBB+C60EAQF/IwBBIGsiBSQAIAUgADYCGCAFIAGtIAKtQiCGhDcDECAFIAM2AgwgBSAENgIIAkACQCAFKQMQIAUoAhgpAzBUBEAgBSgCCEEJTQ0BCyAFKAIYQQhqQRJBABAUIAVBfzYCHAwBCyAFKAIYKAIYQQJxBEAgBSgCGEEIakEZQQAQFCAFQX82AhwMAQsCfyAFKAIMIQEjAEEQayIAJAAgACABNgIIIABBAToABwJAIAAoAghFBEAgAEEBOgAPDAELIAAgACgCCCAALQAHQQFxELMBQQBHOgAPCyAALQAPQQFxIQEgAEEQaiQAIAFFCwRAIAUoAhhBCGpBEEEAEBQgBUF/NgIcDAELIAUgBSgCGCgCQCAFKQMQp0EEdGo2AgQgBSAFKAIEKAIABH8gBSgCBCgCACgCEAVBfws2AgACQCAFKAIMIAUoAgBGBEAgBSgCBCgCBARAIAUoAgQoAgQiACAAKAIAQX5xNgIAIAUoAgQoAgRBADsBUCAFKAIEKAIEKAIARQRAIAUoAgQoAgQQOSAFKAIEQQA2AgQLCwwBCyAFKAIEKAIERQRAIAUoAgQoAgAQPyEAIAUoAgQgADYCBCAARQRAIAUoAhhBCGpBDkEAEBQgBUF/NgIcDAMLCyAFKAIEKAIEIAUoAgw2AhAgBSgCBCgCBCAFKAIIOwFQIAUoAgQoAgQiACAAKAIAQQFyNgIACyAFQQA2AhwLIAUoAhwhACAFQSBqJAAgAAsXAQF+IAAgASACEHMiA0IgiKcQACADpwuuAQIBfwF+An8jAEEgayICIAA2AhQgAiABNgIQAkAgAigCFEUEQCACQn83AxgMAQsgAigCEEEIcQRAIAIgAigCFCkDMDcDCANAIAIpAwhCAFIEfyACKAIUKAJAIAIpAwhCAX2nQQR0aigCAAVBAQtFBEAgAiACKQMIQgF9NwMIDAELCyACIAIpAwg3AxgMAQsgAiACKAIUKQMwNwMYCyACKQMYIgNCIIinCxAAIAOnCxMAIAAgAa0gAq1CIIaEIAMQxAELiAICAX8BfgJ/IwBBIGsiBCQAIAQgADYCFCAEIAE2AhAgBCACrSADrUIghoQ3AwgCQCAEKAIURQRAIARCfzcDGAwBCyAEKAIUKAIEBEAgBEJ/NwMYDAELIAQpAwhC////////////AFYEQCAEKAIUQQRqQRJBABAUIARCfzcDGAwBCwJAIAQoAhQtABBBAXFFBEAgBCkDCFBFDQELIARCADcDGAwBCyAEIAQoAhQoAhQgBCgCECAEKQMIEC4iBTcDACAFQgBTBEAgBCgCFEEEaiAEKAIUKAIUEBcgBEJ/NwMYDAELIAQgBCkDADcDGAsgBCkDGCEFIARBIGokACAFQiCIpwsQACAFpwtPAQF/IwBBIGsiBCQAIAQgADYCHCAEIAGtIAKtQiCGhDcDECAEIAM2AgwgBCgCHCAEKQMQIAQoAgwgBCgCHCgCHBCtASEAIARBIGokACAAC9kDAQF/IwBBIGsiBSQAIAUgADYCGCAFIAGtIAKtQiCGhDcDECAFIAM2AgwgBSAENgIIAkAgBSgCGCAFKQMQQQBBABBFRQRAIAVBfzYCHAwBCyAFKAIYKAIYQQJxBEAgBSgCGEEIakEZQQAQFCAFQX82AhwMAQsgBSgCGCgCQCAFKQMQp0EEdGooAggEQCAFKAIYKAJAIAUpAxCnQQR0aigCCCAFKAIMEGhBAEgEQCAFKAIYQQhqQQ9BABAUIAVBfzYCHAwCCyAFQQA2AhwMAQsgBSAFKAIYKAJAIAUpAxCnQQR0ajYCBCAFIAUoAgQoAgAEfyAFKAIMIAUoAgQoAgAoAhRHBUEBC0EBcTYCAAJAIAUoAgAEQCAFKAIEKAIERQRAIAUoAgQoAgAQPyEAIAUoAgQgADYCBCAARQRAIAUoAhhBCGpBDkEAEBQgBUF/NgIcDAQLCyAFKAIEKAIEIAUoAgw2AhQgBSgCBCgCBCIAIAAoAgBBIHI2AgAMAQsgBSgCBCgCBARAIAUoAgQoAgQiACAAKAIAQV9xNgIAIAUoAgQoAgQoAgBFBEAgBSgCBCgCBBA5IAUoAgRBADYCBAsLCyAFQQA2AhwLIAUoAhwhACAFQSBqJAAgAAsXACAAIAGtIAKtQiCGhCADIAQgBRCZAQsXACAAIAGtIAKtQiCGhCADIAQgBRCXAQuPAQIBfwF+An8jAEEgayIEJAAgBCAANgIUIAQgATYCECAEIAI2AgwgBCADNgIIAkACQCAEKAIQBEAgBCgCDA0BCyAEKAIUQQhqQRJBABAUIARCfzcDGAwBCyAEIAQoAhQgBCgCECAEKAIMIAQoAggQmgE3AxgLIAQpAxghBSAEQSBqJAAgBUIgiKcLEAAgBacLiAEBAX8jAEEQayICJAAgAiAANgIMIAIgATYCCCMAQRBrIgAgAigCDDYCDCAAKAIMQQA2AgAgACgCDEEANgIEIAAoAgxBADYCCCACKAIMIAIoAgg2AgACQCACKAIMEJYBQQFGBEAgAigCDEG0mwEoAgA2AgQMAQsgAigCDEEANgIECyACQRBqJAALhQUCAX8BfgJ/IwBBMGsiAyQAIAMgADYCJCADIAE2AiAgAyACNgIcAkAgAygCJCgCGEECcQRAIAMoAiRBCGpBGUEAEBQgA0J/NwMoDAELIAMoAiBFBEAgAygCJEEIakESQQAQFCADQn83AygMAQsgA0EANgIMIAMgAygCIBArNgIYIAMoAiAgAygCGEEBa2osAABBL0cEQCADIAMoAhhBAmoQGCIANgIMIABFBEAgAygCJEEIakEOQQAQFCADQn83AygMAgsCQAJAIAMoAgwiASADKAIgIgBzQQNxDQAgAEEDcQRAA0AgASAALQAAIgI6AAAgAkUNAyABQQFqIQEgAEEBaiIAQQNxDQALCyAAKAIAIgJBf3MgAkGBgoQIa3FBgIGChHhxDQADQCABIAI2AgAgACgCBCECIAFBBGohASAAQQRqIQAgAkGBgoQIayACQX9zcUGAgYKEeHFFDQALCyABIAAtAAAiAjoAACACRQ0AA0AgASAALQABIgI6AAEgAUEBaiEBIABBAWohACACDQALCyADKAIMIAMoAhhqQS86AAAgAygCDCADKAIYQQFqakEAOgAACyADIAMoAiRBAEIAQQAQfiIANgIIIABFBEAgAygCDBAVIANCfzcDKAwBCyADIAMoAiQCfyADKAIMBEAgAygCDAwBCyADKAIgCyADKAIIIAMoAhwQmgE3AxAgAygCDBAVAkAgAykDEEIAUwRAIAMoAggQGwwBCyADKAIkIAMpAxBBAEEDQYCA/I8EEJkBQQBIBEAgAygCJCADKQMQEJgBGiADQn83AygMAgsLIAMgAykDEDcDKAsgAykDKCEEIANBMGokACAEQiCIpwsQACAEpwsRACAAIAGtIAKtQiCGhBCYAQt/AgF/AX4jAEEgayIDJAAgAyAANgIYIAMgATYCFCADIAI2AhAgAyADKAIYIAMoAhQgAygCEBBzIgQ3AwgCQCAEQgBTBEAgA0EANgIcDAELIAMgAygCGCADKQMIIAMoAhAgAygCGCgCHBCtATYCHAsgAygCHCEAIANBIGokACAAC8QBAQF/IwBBMGsiASQAIAEgADYCKCABQQA2AiQgAUIANwMYAkADQCABKQMYIAEoAigpAzBUBEAgASABKAIoIAEpAxhBACABQRdqIAFBEGoQlwE2AgwgASgCDEF/RgRAIAFBfzYCLAwDBQJAIAEtABdBA0cNACABKAIQQRB2QYDgA3FBgMACRw0AIAEgASgCJEEBajYCJAsgASABKQMYQgF8NwMYDAILAAsLIAEgASgCJDYCLAsgASgCLCEAIAFBMGokACAACxAAIwAgAGtBcHEiACQAIAALBgAgACQACwQAIwALggECAX8BfiMAQSBrIgQkACAEIAA2AhggBCABNgIUIAQgAjYCECAEIAM2AgwgBCAEKAIYIAQoAhQgBCgCEBBzIgU3AwACQCAFQgBTBEAgBEF/NgIcDAELIAQgBCgCGCAEKQMAIAQoAhAgBCgCDBB/NgIcCyAEKAIcIQAgBEEgaiQAIAAL0EUDBn8BfgJ8IwBB4ABrIgEkACABIAA2AlgCQCABKAJYRQRAIAFBfzYCXAwBCyMAQSBrIgAgASgCWDYCHCAAIAFBQGs2AhggAEEANgIUIABCADcDAAJAIAAoAhwtAChBAXFFBEAgACgCHCgCGCAAKAIcKAIURg0BCyAAQQE2AhQLIABCADcDCANAIAApAwggACgCHCkDMFQEQAJAAkAgACgCHCgCQCAAKQMIp0EEdGooAggNACAAKAIcKAJAIAApAwinQQR0ai0ADEEBcQ0AIAAoAhwoAkAgACkDCKdBBHRqKAIERQ0BIAAoAhwoAkAgACkDCKdBBHRqKAIEKAIARQ0BCyAAQQE2AhQLIAAoAhwoAkAgACkDCKdBBHRqLQAMQQFxRQRAIAAgACkDAEIBfDcDAAsgACAAKQMIQgF8NwMIDAELCyAAKAIYBEAgACgCGCAAKQMANwMACyABIAAoAhQ2AiQgASkDQFAEQAJAIAEoAlgoAgRBCHFFBEAgASgCJEUNAQsCfyABKAJYKAIAIQIjAEEQayIAJAAgACACNgIIAkAgACgCCCgCJEEDRgRAIABBADYCDAwBCyAAKAIIKAIgBEAgACgCCBAxQQBIBEAgAEF/NgIMDAILCyAAKAIIKAIkBEAgACgCCBBnCyAAKAIIQQBCAEEPECFCAFMEQCAAQX82AgwMAQsgACgCCEEDNgIkIABBADYCDAsgACgCDCECIABBEGokACACQQBICwRAAkACfyMAQRBrIgAgASgCWCgCADYCDCMAQRBrIgIgACgCDEEMajYCDCACKAIMKAIAQRZGCwRAIwBBEGsiACABKAJYKAIANgIMIwBBEGsiAiAAKAIMQQxqNgIMIAIoAgwoAgRBLEYNAQsgASgCWEEIaiABKAJYKAIAEBcgAUF/NgJcDAQLCwsgASgCWBA9IAFBADYCXAwBCyABKAIkRQRAIAEoAlgQPSABQQA2AlwMAQsgASkDQCABKAJYKQMwVgRAIAEoAlhBCGpBFEEAEBQgAUF/NgJcDAELIAEgASkDQKdBA3QQGCIANgIoIABFBEAgAUF/NgJcDAELIAFCfzcDOCABQgA3A0ggAUIANwNQA0AgASkDUCABKAJYKQMwVARAAkAgASgCWCgCQCABKQNQp0EEdGooAgBFDQACQCABKAJYKAJAIAEpA1CnQQR0aigCCA0AIAEoAlgoAkAgASkDUKdBBHRqLQAMQQFxDQAgASgCWCgCQCABKQNQp0EEdGooAgRFDQEgASgCWCgCQCABKQNQp0EEdGooAgQoAgBFDQELIAECfiABKQM4IAEoAlgoAkAgASkDUKdBBHRqKAIAKQNIVARAIAEpAzgMAQsgASgCWCgCQCABKQNQp0EEdGooAgApA0gLNwM4CyABKAJYKAJAIAEpA1CnQQR0ai0ADEEBcUUEQCABKQNIIAEpA0BaBEAgASgCKBAVIAEoAlhBCGpBFEEAEBQgAUF/NgJcDAQLIAEoAiggASkDSKdBA3RqIAEpA1A3AwAgASABKQNIQgF8NwNICyABIAEpA1BCAXw3A1AMAQsLIAEpA0ggASkDQFQEQCABKAIoEBUgASgCWEEIakEUQQAQFCABQX82AlwMAQsCQAJ/IwBBEGsiACABKAJYKAIANgIMIAAoAgwpAxhCgIAIg1ALBEAgAUIANwM4DAELIAEpAzhCf1EEQCABQn83AxggAUIANwM4IAFCADcDUANAIAEpA1AgASgCWCkDMFQEQCABKAJYKAJAIAEpA1CnQQR0aigCAARAIAEoAlgoAkAgASkDUKdBBHRqKAIAKQNIIAEpAzhaBEAgASABKAJYKAJAIAEpA1CnQQR0aigCACkDSDcDOCABIAEpA1A3AxgLCyABIAEpA1BCAXw3A1AMAQsLIAEpAxhCf1IEQCABKAJYIQIgASkDGCEHIAEoAlhBCGohAyMAQTBrIgAkACAAIAI2AiQgACAHNwMYIAAgAzYCFCAAIAAoAiQgACkDGCAAKAIUEGUiBzcDCAJAIAdQBEAgAEIANwMoDAELIAAgACgCJCgCQCAAKQMYp0EEdGooAgA2AgQCQCAAKQMIIAApAwggACgCBCkDIHxYBEAgACkDCCAAKAIEKQMgfEL///////////8AWA0BCyAAKAIUQQRBFhAUIABCADcDKAwBCyAAIAAoAgQpAyAgACkDCHw3AwggACgCBC8BDEEIcQRAIAAoAiQoAgAgACkDCEEAECdBAEgEQCAAKAIUIAAoAiQoAgAQFyAAQgA3AygMAgsgACgCJCgCACAAQgQQLkIEUgRAIAAoAhQgACgCJCgCABAXIABCADcDKAwCCyAAKAAAQdCWncAARgRAIAAgACkDCEIEfDcDCAsgACAAKQMIQgx8NwMIIAAoAgRBABBeQQFxBEAgACAAKQMIQgh8NwMICyAAKQMIQv///////////wBWBEAgACgCFEEEQRYQFCAAQgA3AygMAgsLIAAgACkDCDcDKAsgACkDKCEHIABBMGokACABIAc3AzggB1AEQCABKAIoEBUgAUF/NgJcDAQLCwsgASkDOEIAUgRAAn8gASgCWCgCACECIAEpAzghByMAQRBrIgAkACAAIAI2AgggACAHNwMAAkAgACgCCCgCJEEBRgRAIAAoAghBDGpBEkEAEBQgAEF/NgIMDAELIAAoAghBACAAKQMAQREQIUIAUwRAIABBfzYCDAwBCyAAKAIIQQE2AiQgAEEANgIMCyAAKAIMIQIgAEEQaiQAIAJBAEgLBEAgAUIANwM4CwsLIAEpAzhQBEACfyABKAJYKAIAIQIjAEEQayIAJAAgACACNgIIAkAgACgCCCgCJEEBRgRAIAAoAghBDGpBEkEAEBQgAEF/NgIMDAELIAAoAghBAEIAQQgQIUIAUwRAIABBfzYCDAwBCyAAKAIIQQE2AiQgAEEANgIMCyAAKAIMIQIgAEEQaiQAIAJBAEgLBEAgASgCWEEIaiABKAJYKAIAEBcgASgCKBAVIAFBfzYCXAwCCwsgASgCWCgCVCECIwBBEGsiACQAIAAgAjYCDCAAKAIMBEAgACgCDEQAAAAAAAAAADkDGCAAKAIMKAIARAAAAAAAAAAAIAAoAgwoAgwgACgCDCgCBBEWAAsgAEEQaiQAIAFBADYCLCABQgA3A0gDQAJAIAEpA0ggASkDQFoNACABKAJYKAJUIQIgASkDSCIHuiABKQNAuiIIoyEJIwBBIGsiACQAIAAgAjYCHCAAIAk5AxAgACAHQgF8uiAIozkDCCAAKAIcBEAgACgCHCAAKwMQOQMgIAAoAhwgACsDCDkDKCAAKAIcRAAAAAAAAAAAEFYLIABBIGokACABIAEoAiggASkDSKdBA3RqKQMANwNQIAEgASgCWCgCQCABKQNQp0EEdGo2AhACQAJAIAEoAhAoAgBFDQAgASgCECgCACkDSCABKQM4Wg0ADAELIAECf0EBIAEoAhAoAggNABogASgCECgCBARAQQEgASgCECgCBCgCAEEBcQ0BGgsgASgCECgCBAR/IAEoAhAoAgQoAgBBwABxQQBHBUEACwtBAXE2AhQgASgCECgCBEUEQCABKAIQKAIAED8hACABKAIQIAA2AgQgAEUEQCABKAJYQQhqQQ5BABAUIAFBATYCLAwDCwsgASABKAIQKAIENgIMAn8gASgCWCECIAEpA1AhByMAQTBrIgAkACAAIAI2AiggACAHNwMgAkAgACkDICAAKAIoKQMwWgRAIAAoAihBCGpBEkEAEBQgAEF/NgIsDAELIAAgACgCKCgCQCAAKQMgp0EEdGo2AhwCQCAAKAIcKAIABEAgACgCHCgCAC0ABEEBcUUNAQsgAEEANgIsDAELIAAoAhwoAgApA0hCGnxC////////////AFYEQCAAKAIoQQhqQQRBFhAUIABBfzYCLAwBCyAAKAIoKAIAIAAoAhwoAgApA0hCGnxBABAnQQBIBEAgACgCKEEIaiAAKAIoKAIAEBcgAEF/NgIsDAELIAAgACgCKCgCAEIEIABBGGogACgCKEEIahBBIgI2AhQgAkUEQCAAQX82AiwMAQsgACAAKAIUEB07ARIgACAAKAIUEB07ARAgACgCFBBHQQFxRQRAIAAoAhQQFiAAKAIoQQhqQRRBABAUIABBfzYCLAwBCyAAKAIUEBYgAC8BEARAIAAoAigoAgAgAC8BEq1BARAnQQBIBEAgACgCKEEIakEEQbSbASgCABAUIABBfzYCLAwCCyAAQQAgACgCKCgCACAALwEQQQAgACgCKEEIahBgNgIIIAAoAghFBEAgAEF/NgIsDAILIAAoAgggAC8BEEGAAiAAQQxqIAAoAihBCGoQiAFBAXFFBEAgACgCCBAVIABBfzYCLAwCCyAAKAIIEBUgACgCDARAIAAgACgCDBCHATYCDCAAKAIcKAIAKAI0IAAoAgwQiQEhAiAAKAIcKAIAIAI2AjQLCyAAKAIcKAIAQQE6AAQCQCAAKAIcKAIERQ0AIAAoAhwoAgQtAARBAXENACAAKAIcKAIEIAAoAhwoAgAoAjQ2AjQgACgCHCgCBEEBOgAECyAAQQA2AiwLIAAoAiwhAiAAQTBqJAAgAkEASAsEQCABQQE2AiwMAgsgASABKAJYKAIAEDQiBzcDMCAHQgBTBEAgAUEBNgIsDAILIAEoAgwgASkDMDcDSAJAIAEoAhQEQCABQQA2AgggASgCECgCCEUEQCABIAEoAlggASgCWCABKQNQQQhBABCuASIANgIIIABFBEAgAUEBNgIsDAULCwJ/IAEoAlghAgJ/IAEoAggEQCABKAIIDAELIAEoAhAoAggLIQMgASgCDCEEIwBBoAFrIgAkACAAIAI2ApgBIAAgAzYClAEgACAENgKQAQJAIAAoApQBIABBOGoQOEEASARAIAAoApgBQQhqIAAoApQBEBcgAEF/NgKcAQwBCyAAKQM4QsAAg1AEQCAAIAApAzhCwACENwM4IABBADsBaAsCQAJAIAAoApABKAIQQX9HBEAgACgCkAEoAhBBfkcNAQsgAC8BaEUNACAAKAKQASAALwFoNgIQDAELAkACQCAAKAKQASgCEA0AIAApAzhCBINQDQAgACAAKQM4QgiENwM4IAAgACkDUDcDWAwBCyAAIAApAzhC9////w+DNwM4CwsgACkDOEKAAYNQBEAgACAAKQM4QoABhDcDOCAAQQA7AWoLIABBgAI2AiQCQCAAKQM4QgSDUARAIAAgACgCJEGACHI2AiQgAEJ/NwNwDAELIAAoApABIAApA1A3AyggACAAKQNQNwNwAkAgACkDOEIIg1AEQAJAAkACQAJAAkACfwJAIAAoApABKAIQQX9HBEAgACgCkAEoAhBBfkcNAQtBCAwBCyAAKAKQASgCEAtB//8DcQ4NAgMDAwMDAwMBAwMDAAMLIABClMLk8w83AxAMAwsgAEKDg7D/DzcDEAwCCyAAQv////8PNwMQDAELIABCADcDEAsgACkDUCAAKQMQVgRAIAAgACgCJEGACHI2AiQLDAELIAAoApABIAApA1g3AyALCyAAIAAoApgBKAIAEDQiBzcDiAEgB0IAUwRAIAAoApgBQQhqIAAoApgBKAIAEBcgAEF/NgKcAQwBCyAAKAKQASICIAIvAQxB9/8DcTsBDCAAIAAoApgBIAAoApABIAAoAiQQUCICNgIoIAJBAEgEQCAAQX82ApwBDAELIAAgAC8BaAJ/AkAgACgCkAEoAhBBf0cEQCAAKAKQASgCEEF+Rw0BC0EIDAELIAAoApABKAIQC0H//wNxRzoAIiAAIAAtACJBAXEEfyAALwFoQQBHBUEAC0EBcToAISAAIAAvAWgEfyAALQAhBUEBC0EBcToAICAAIAAtACJBAXEEfyAAKAKQASgCEEEARwVBAAtBAXE6AB8gAAJ/QQEgAC0AIkEBcQ0AGkEBIAAoApABKAIAQYABcQ0AGiAAKAKQAS8BUiAALwFqRwtBAXE6AB4gACAALQAeQQFxBH8gAC8BakEARwVBAAtBAXE6AB0gACAALQAeQQFxBH8gACgCkAEvAVJBAEcFQQALQQFxOgAcIAAgACgClAE2AjQjAEEQayICIAAoAjQ2AgwgAigCDCICIAIoAjBBAWo2AjAgAC0AHUEBcQRAIAAgAC8BakEAEHwiAjYCDCACRQRAIAAoApgBQQhqQRhBABAUIAAoAjQQGyAAQX82ApwBDAILIAAgACgCmAEgACgCNCAALwFqQQAgACgCmAEoAhwgACgCDBEFACICNgIwIAJFBEAgACgCNBAbIABBfzYCnAEMAgsgACgCNBAbIAAgACgCMDYCNAsgAC0AIUEBcQRAIAAgACgCmAEgACgCNCAALwFoELABIgI2AjAgAkUEQCAAKAI0EBsgAEF/NgKcAQwCCyAAKAI0EBsgACAAKAIwNgI0CyAALQAgQQFxBEAgACAAKAKYASAAKAI0QQAQrwEiAjYCMCACRQRAIAAoAjQQGyAAQX82ApwBDAILIAAoAjQQGyAAIAAoAjA2AjQLIAAtAB9BAXEEQCAAKAKYASEDIAAoAjQhBCAAKAKQASgCECEFIAAoApABLwFQIQYjAEEQayICJAAgAiADNgIMIAIgBDYCCCACIAU2AgQgAiAGNgIAIAIoAgwgAigCCCACKAIEQQEgAigCABCyASEDIAJBEGokACAAIAMiAjYCMCACRQRAIAAoAjQQGyAAQX82ApwBDAILIAAoAjQQGyAAIAAoAjA2AjQLIAAtABxBAXEEQCAAQQA2AgQCQCAAKAKQASgCVARAIAAgACgCkAEoAlQ2AgQMAQsgACgCmAEoAhwEQCAAIAAoApgBKAIcNgIECwsgACAAKAKQAS8BUkEBEHwiAjYCCCACRQRAIAAoApgBQQhqQRhBABAUIAAoAjQQGyAAQX82ApwBDAILIAAgACgCmAEgACgCNCAAKAKQAS8BUkEBIAAoAgQgACgCCBEFACICNgIwIAJFBEAgACgCNBAbIABBfzYCnAEMAgsgACgCNBAbIAAgACgCMDYCNAsgACAAKAKYASgCABA0Igc3A4ABIAdCAFMEQCAAKAKYAUEIaiAAKAKYASgCABAXIABBfzYCnAEMAQsgACgCmAEhAyAAKAI0IQQgACkDcCEHIwBBwMAAayICJAAgAiADNgK4QCACIAQ2ArRAIAIgBzcDqEACQCACKAK0QBBJQQBIBEAgAigCuEBBCGogAigCtEAQFyACQX82ArxADAELIAJBADYCDCACQgA3AxADQAJAIAIgAigCtEAgAkEgakKAwAAQLiIHNwMYIAdCAFcNACACKAK4QCACQSBqIAIpAxgQNUEASARAIAJBfzYCDAUgAikDGEKAwABSDQIgAigCuEAoAlRFDQIgAikDqEBCAFcNAiACIAIpAxggAikDEHw3AxAgAigCuEAoAlQgAikDELkgAikDqEC5oxBWDAILCwsgAikDGEIAUwRAIAIoArhAQQhqIAIoArRAEBcgAkF/NgIMCyACKAK0QBAxGiACIAIoAgw2ArxACyACKAK8QCEDIAJBwMAAaiQAIAAgAzYCLCAAKAI0IABBOGoQOEEASARAIAAoApgBQQhqIAAoAjQQFyAAQX82AiwLIAAoAjQhAyMAQRBrIgIkACACIAM2AggCQANAIAIoAggEQCACKAIIKQMYQoCABINCAFIEQCACIAIoAghBAEIAQRAQITcDACACKQMAQgBTBEAgAkH/AToADwwECyACKQMAQgNVBEAgAigCCEEMakEUQQAQFCACQf8BOgAPDAQLIAIgAikDADwADwwDBSACIAIoAggoAgA2AggMAgsACwsgAkEAOgAPCyACLAAPIQMgAkEQaiQAIAAgAyICOgAjIAJBGHRBGHVBAEgEQCAAKAKYAUEIaiAAKAI0EBcgAEF/NgIsCyAAKAI0EBsgACgCLEEASARAIABBfzYCnAEMAQsgACAAKAKYASgCABA0Igc3A3ggB0IAUwRAIAAoApgBQQhqIAAoApgBKAIAEBcgAEF/NgKcAQwBCyAAKAKYASgCACAAKQOIARCbAUEASARAIAAoApgBQQhqIAAoApgBKAIAEBcgAEF/NgKcAQwBCyAAKQM4QuQAg0LkAFIEQCAAKAKYAUEIakEUQQAQFCAAQX82ApwBDAELIAAoApABKAIAQSBxRQRAAkAgACkDOEIQg0IAUgRAIAAoApABIAAoAmA2AhQMAQsgACgCkAFBFGoQARoLCyAAKAKQASAALwFoNgIQIAAoApABIAAoAmQ2AhggACgCkAEgACkDUDcDKCAAKAKQASAAKQN4IAApA4ABfTcDICAAKAKQASAAKAKQAS8BDEH5/wNxIAAtACNBAXRyOwEMIAAoApABIQMgACgCJEGACHFBAEchBCMAQRBrIgIkACACIAM2AgwgAiAEOgALAkAgAigCDCgCEEEORgRAIAIoAgxBPzsBCgwBCyACKAIMKAIQQQxGBEAgAigCDEEuOwEKDAELAkAgAi0AC0EBcUUEQCACKAIMQQAQXkEBcUUNAQsgAigCDEEtOwEKDAELAkAgAigCDCgCEEEIRwRAIAIoAgwvAVJBAUcNAQsgAigCDEEUOwEKDAELIAIgAigCDCgCMBBTIgM7AQggA0H//wNxBEAgAigCDCgCMCgCACACLwEIQQFrai0AAEEvRgRAIAIoAgxBFDsBCgwCCwsgAigCDEEKOwEKCyACQRBqJAAgACAAKAKYASAAKAKQASAAKAIkEFAiAjYCLCACQQBIBEAgAEF/NgKcAQwBCyAAKAIoIAAoAixHBEAgACgCmAFBCGpBFEEAEBQgAEF/NgKcAQwBCyAAKAKYASgCACAAKQN4EJsBQQBIBEAgACgCmAFBCGogACgCmAEoAgAQFyAAQX82ApwBDAELIABBADYCnAELIAAoApwBIQIgAEGgAWokACACQQBICwRAIAFBATYCLCABKAIIBEAgASgCCBAbCwwECyABKAIIBEAgASgCCBAbCwwBCyABKAIMIgAgAC8BDEH3/wNxOwEMIAEoAlggASgCDEGAAhBQQQBIBEAgAUEBNgIsDAMLIAEgASgCWCABKQNQIAEoAlhBCGoQZSIHNwMAIAdQBEAgAUEBNgIsDAMLIAEoAlgoAgAgASkDAEEAECdBAEgEQCABKAJYQQhqIAEoAlgoAgAQFyABQQE2AiwMAwsCfyABKAJYIQIgASgCDCkDICEHIwBBoMAAayIAJAAgACACNgKYQCAAIAc3A5BAIAAgACkDkEC6OQMAAkADQCAAKQOQQFBFBEAgACAAKQOQQEKAwABWBH5CgMAABSAAKQOQQAs+AgwgACgCmEAoAgAgAEEQaiAAKAIMrSAAKAKYQEEIahBhQQBIBEAgAEF/NgKcQAwDCyAAKAKYQCAAQRBqIAAoAgytEDVBAEgEQCAAQX82ApxADAMFIAAgACkDkEAgADUCDH03A5BAIAAoAphAKAJUIAArAwAgACkDkEC6oSAAKwMAoxBWDAILAAsLIABBADYCnEALIAAoApxAIQIgAEGgwABqJAAgAkEASAsEQCABQQE2AiwMAwsLCyABIAEpA0hCAXw3A0gMAQsLIAEoAixFBEACfyABKAJYIQAgASgCKCEDIAEpA0AhByMAQTBrIgIkACACIAA2AiggAiADNgIkIAIgBzcDGCACIAIoAigoAgAQNCIHNwMQAkAgB0IAUwRAIAJBfzYCLAwBCyACKAIoIQMgAigCJCEEIAIpAxghByMAQcABayIAJAAgACADNgK0ASAAIAQ2ArABIAAgBzcDqAEgACAAKAK0ASgCABA0Igc3AyACQCAHQgBTBEAgACgCtAFBCGogACgCtAEoAgAQFyAAQn83A7gBDAELIAAgACkDIDcDoAEgAEEAOgAXIABCADcDGANAIAApAxggACkDqAFUBEAgACAAKAK0ASgCQCAAKAKwASAAKQMYp0EDdGopAwCnQQR0ajYCDCAAIAAoArQBAn8gACgCDCgCBARAIAAoAgwoAgQMAQsgACgCDCgCAAtBgAQQUCIDNgIQIANBAEgEQCAAQn83A7gBDAMLIAAoAhAEQCAAQQE6ABcLIAAgACkDGEIBfDcDGAwBCwsgACAAKAK0ASgCABA0Igc3AyAgB0IAUwRAIAAoArQBQQhqIAAoArQBKAIAEBcgAEJ/NwO4AQwBCyAAIAApAyAgACkDoAF9NwOYAQJAIAApA6ABQv////8PWARAIAApA6gBQv//A1gNAQsgAEEBOgAXCyAAIABBMGpC4gAQKSIDNgIsIANFBEAgACgCtAFBCGpBDkEAEBQgAEJ/NwO4AQwBCyAALQAXQQFxBEAgACgCLEHnEkEEEEAgACgCLEIsEC0gACgCLEEtEB8gACgCLEEtEB8gACgCLEEAECAgACgCLEEAECAgACgCLCAAKQOoARAtIAAoAiwgACkDqAEQLSAAKAIsIAApA5gBEC0gACgCLCAAKQOgARAtIAAoAixB4hJBBBBAIAAoAixBABAgIAAoAiwgACkDoAEgACkDmAF8EC0gACgCLEEBECALIAAoAixB7BJBBBBAIAAoAixBABAgIAAoAiwgACkDqAFC//8DWgR+Qv//AwUgACkDqAELp0H//wNxEB8gACgCLCAAKQOoAUL//wNaBH5C//8DBSAAKQOoAQunQf//A3EQHyAAKAIsIAApA5gBQv////8PWgR/QX8FIAApA5gBpwsQICAAKAIsIAApA6ABQv////8PWgR/QX8FIAApA6ABpwsQICAAAn8gACgCtAEtAChBAXEEQCAAKAK0ASgCJAwBCyAAKAK0ASgCIAs2ApQBIAAoAiwCfyAAKAKUAQRAIAAoApQBLwEEDAELQQALQf//A3EQHwJ/IwBBEGsiAyAAKAIsNgIMIAMoAgwtAABBAXFFCwRAIAAoArQBQQhqQRRBABAUIAAoAiwQFiAAQn83A7gBDAELIAAoArQBAn8jAEEQayIDIAAoAiw2AgwgAygCDCgCBAsCfiMAQRBrIgMgACgCLDYCDAJ+IAMoAgwtAABBAXEEQCADKAIMKQMQDAELQgALCxA1QQBIBEAgACgCLBAWIABCfzcDuAEMAQsgACgCLBAWIAAoApQBBEAgACgCtAEgACgClAEoAgAgACgClAEvAQStEDVBAEgEQCAAQn83A7gBDAILCyAAIAApA5gBNwO4AQsgACkDuAEhByAAQcABaiQAIAIgBzcDACAHQgBTBEAgAkF/NgIsDAELIAIgAigCKCgCABA0Igc3AwggB0IAUwRAIAJBfzYCLAwBCyACQQA2AiwLIAIoAiwhACACQTBqJAAgAEEASAsEQCABQQE2AiwLCyABKAIoEBUgASgCLEUEQAJ/IAEoAlgoAgAhAiMAQRBrIgAkACAAIAI2AggCQCAAKAIIKAIkQQFHBEAgACgCCEEMakESQQAQFCAAQX82AgwMAQsgACgCCCgCIEEBSwRAIAAoAghBDGpBHUEAEBQgAEF/NgIMDAELIAAoAggoAiAEQCAAKAIIEDFBAEgEQCAAQX82AgwMAgsLIAAoAghBAEIAQQkQIUIAUwRAIAAoAghBAjYCJCAAQX82AgwMAQsgACgCCEEANgIkIABBADYCDAsgACgCDCECIABBEGokACACCwRAIAEoAlhBCGogASgCWCgCABAXIAFBATYCLAsLIAEoAlgoAlQhAiMAQRBrIgAkACAAIAI2AgwgACgCDEQAAAAAAADwPxBWIABBEGokACABKAIsBEAgASgCWCgCABBnIAFBfzYCXAwBCyABKAJYED0gAUEANgJcCyABKAJcIQAgAUHgAGokACAAC9IOAgd/An4jAEEwayIDJAAgAyAANgIoIAMgATYCJCADIAI2AiAjAEEQayIAIANBCGo2AgwgACgCDEEANgIAIAAoAgxBADYCBCAAKAIMQQA2AgggAygCKCEAIwBBIGsiBCQAIAQgADYCGCAEQgA3AxAgBEJ/NwMIIAQgA0EIajYCBAJAAkAgBCgCGARAIAQpAwhCf1kNAQsgBCgCBEESQQAQFCAEQQA2AhwMAQsgBCgCGCEAIAQpAxAhCiAEKQMIIQsgBCgCBCEBIwBBoAFrIgIkACACIAA2ApgBIAJBADYClAEgAiAKNwOIASACIAs3A4ABIAJBADYCfCACIAE2AngCQAJAIAIoApQBDQAgAigCmAENACACKAJ4QRJBABAUIAJBADYCnAEMAQsgAikDgAFCAFMEQCACQgA3A4ABCwJAIAIpA4gBQv///////////wBYBEAgAikDiAEgAikDiAEgAikDgAF8WA0BCyACKAJ4QRJBABAUIAJBADYCnAEMAQsgAkGIARAYIgA2AnQgAEUEQCACKAJ4QQ5BABAUIAJBADYCnAEMAQsgAigCdEEANgIYIAIoApgBBEAgAigCmAEiABArQQFqIgEQGCIFBH8gBSAAIAEQGQVBAAshACACKAJ0IAA2AhggAEUEQCACKAJ4QQ5BABAUIAIoAnQQFSACQQA2ApwBDAILCyACKAJ0IAIoApQBNgIcIAIoAnQgAikDiAE3A2ggAigCdCACKQOAATcDcAJAIAIoAnwEQCACKAJ0IgAgAigCfCIBKQMANwMgIAAgASkDMDcDUCAAIAEpAyg3A0ggACABKQMgNwNAIAAgASkDGDcDOCAAIAEpAxA3AzAgACABKQMINwMoIAIoAnRBADYCKCACKAJ0IgAgACkDIEL+////D4M3AyAMAQsgAigCdEEgahA7CyACKAJ0KQNwQgBSBEAgAigCdCACKAJ0KQNwNwM4IAIoAnQiACAAKQMgQgSENwMgCyMAQRBrIgAgAigCdEHYAGo2AgwgACgCDEEANgIAIAAoAgxBADYCBCAAKAIMQQA2AgggAigCdEEANgKAASACKAJ0QQA2AoQBIwBBEGsiACACKAJ0NgIMIAAoAgxBADYCACAAKAIMQQA2AgQgACgCDEEANgIIIAJBfzYCBCACQQc2AgBBDiACEDZCP4QhCiACKAJ0IAo3AxACQCACKAJ0KAIYBEAgAiACKAJ0KAIYIAJBGGoQpgFBAE46ABcgAi0AF0EBcUUEQAJAIAIoAnQpA2hQRQ0AIAIoAnQpA3BQRQ0AIAIoAnRC//8DNwMQCwsMAQsCQCACKAJ0KAIcIgAoAkxBAEgNAAsgACgCPCEAQQAhBSMAQSBrIgYkAAJ/AkAgACACQRhqIgkQCiIBQXhGBEAjAEEgayIHJAAgACAHQQhqEAkiCAR/QbSbASAINgIAQQAFQQELIQggB0EgaiQAIAgNAQsgAUGBYE8Ef0G0mwFBACABazYCAEF/BSABCwwBCwNAIAUgBmoiASAFQccSai0AADoAACAFQQ5HIQcgBUEBaiEFIAcNAAsCQCAABEBBDyEFIAAhAQNAIAFBCk8EQCAFQQFqIQUgAUEKbiEBDAELCyAFIAZqQQA6AAADQCAGIAVBAWsiBWogACAAQQpuIgFBCmxrQTByOgAAIABBCUshByABIQAgBw0ACwwBCyABQTA6AAAgBkEAOgAPCyAGIAkQAiIAQYFgTwR/QbSbAUEAIABrNgIAQX8FIAALCyEAIAZBIGokACACIABBAE46ABcLAkAgAi0AF0EBcUUEQCACKAJ0QdgAakEFQbSbASgCABAUDAELIAIoAnQpAyBCEINQBEAgAigCdCACKAJYNgJIIAIoAnQiACAAKQMgQhCENwMgCyACKAIkQYDgA3FBgIACRgRAIAIoAnRC/4EBNwMQIAIpA0AgAigCdCkDaCACKAJ0KQNwfFQEQCACKAJ4QRJBABAUIAIoAnQoAhgQFSACKAJ0EBUgAkEANgKcAQwDCyACKAJ0KQNwUARAIAIoAnQgAikDQCACKAJ0KQNofTcDOCACKAJ0IgAgACkDIEIEhDcDIAJAIAIoAnQoAhhFDQAgAikDiAFQRQ0AIAIoAnRC//8DNwMQCwsLCyACKAJ0IgAgACkDEEKAgBCENwMQIAJBHiACKAJ0IAIoAngQlAEiADYCcCAARQRAIAIoAnQoAhgQFSACKAJ0EBUgAkEANgKcAQwBCyACIAIoAnA2ApwBCyACKAKcASEAIAJBoAFqJAAgBCAANgIcCyAEKAIcIQAgBEEgaiQAIAMgADYCGAJAIABFBEAgAygCICADQQhqEJ0BIANBCGoQNyADQQA2AiwMAQsgAyADKAIYIAMoAiQgA0EIahCcASIANgIcIABFBEAgAygCGBAbIAMoAiAgA0EIahCdASADQQhqEDcgA0EANgIsDAELIANBCGoQNyADIAMoAhw2AiwLIAMoAiwhACADQTBqJAAgAAsYAQF/IwBBEGsiASAANgIMIAEoAgxBDGoLkh8BBn8jAEHgAGsiBCQAIAQgADYCVCAEIAE2AlAgBCACNwNIIAQgAzYCRCAEIAQoAlQ2AkAgBCAEKAJQNgI8AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgBCgCRA4TBgcCDAQFCg4BAwkQCw8NCBERABELIARCADcDWAwRCyAEKAJAKAIYRQRAIAQoAkBBHEEAEBQgBEJ/NwNYDBELIAQoAkAhACMAQYABayIBJAAgASAANgJ4IAEgASgCeCgCGBArQQhqEBgiADYCdAJAIABFBEAgASgCeEEOQQAQFCABQX82AnwMAQsCQCABKAJ4KAIYIAFBEGoQpgFFBEAgASABKAIcNgJsDAELIAFBfzYCbAsgASgCdCEAIAEgASgCeCgCGDYCACAAQasSIAEQcCABKAJ0IQMgASgCbCEHIwBBMGsiACQAIAAgAzYCKCAAIAc2AiQgAEEANgIQIAAgACgCKCAAKAIoECtqNgIYIAAgACgCGEEBazYCHANAIAAoAhwgACgCKE8EfyAAKAIcLAAAQdgARgVBAAtBAXEEQCAAIAAoAhBBAWo2AhAgACAAKAIcQQFrNgIcDAELCwJAIAAoAhBFBEBBtJsBQRw2AgAgAEF/NgIsDAELIAAgACgCHEEBajYCHANAIwBBEGsiByQAAkACfyMAQRBrIgMkACADIAdBCGo2AgggA0EEOwEGIANB6AtBAEEAEG0iBTYCAAJAIAVBAEgEQCADQQA6AA8MAQsCfyADKAIAIQYgAygCCCEIIAMvAQYhCSMAQRBrIgUkACAFIAk2AgwgBSAINgIIIAYgBUEIakEBIAVBBGoQBiIGBH9BtJsBIAY2AgBBfwVBAAshBiAFKAIEIQggBUEQaiQAIAMvAQZBfyAIIAYbRwsEQCADKAIAEGwgA0EAOgAPDAELIAMoAgAQbCADQQE6AA8LIAMtAA9BAXEhBSADQRBqJAAgBQsEQCAHIAcoAgg2AgwMAQtBwKABLQAAQQFxRQRAQQAQASEGAkBByJkBKAIAIgNFBEBBzJkBKAIAIAY2AgAMAQtB0JkBQQNBA0EBIANBB0YbIANBH0YbNgIAQbygAUEANgIAQcyZASgCACEFIANBAU4EQCAGrSECQQAhBgNAIAUgBkECdGogAkKt/tXk1IX9qNgAfkIBfCICQiCIPgIAIAZBAWoiBiADRw0ACwsgBSAFKAIAQQFyNgIACwtBzJkBKAIAIQMCQEHImQEoAgAiBUUEQCADIAMoAgBB7ZyZjgRsQbngAGpB/////wdxIgM2AgAMAQsgA0HQmQEoAgAiBkECdGoiCCAIKAIAIANBvKABKAIAIghBAnRqKAIAaiIDNgIAQbygAUEAIAhBAWoiCCAFIAhGGzYCAEHQmQFBACAGQQFqIgYgBSAGRhs2AgAgA0EBdiEDCyAHIAM2AgwLIAcoAgwhAyAHQRBqJAAgACADNgIMIAAgACgCHDYCFANAIAAoAhQgACgCGEkEQCAAIAAoAgxBJHA6AAsCfyAALAALQQpIBEAgACwAC0EwagwBCyAALAALQdcAagshAyAAIAAoAhQiB0EBajYCFCAHIAM6AAAgACAAKAIMQSRuNgIMDAELCyAAKAIoIQMgACAAKAIkQX9GBH9BtgMFIAAoAiQLNgIAIAAgA0HCgSAgABBtIgM2AiAgA0EATgRAIAAoAiRBf0cEQCAAKAIoIAAoAiQQDyIDQYFgTwR/QbSbAUEAIANrNgIAQQAFIAMLGgsgACAAKAIgNgIsDAILQbSbASgCAEEURg0ACyAAQX82AiwLIAAoAiwhAyAAQTBqJAAgASADIgA2AnAgAEF/RgRAIAEoAnhBDEG0mwEoAgAQFCABKAJ0EBUgAUF/NgJ8DAELIAEgASgCcEGjEhChASIANgJoIABFBEAgASgCeEEMQbSbASgCABAUIAEoAnAQbCABKAJ0EG4aIAEoAnQQFSABQX82AnwMAQsgASgCeCABKAJoNgKEASABKAJ4IAEoAnQ2AoABIAFBADYCfAsgASgCfCEAIAFBgAFqJAAgBCAArDcDWAwQCyAEKAJAKAIYBEAgBCgCQCgCHBBVGiAEKAJAQQA2AhwLIARCADcDWAwPCyAEKAJAKAKEARBVQQBIBEAgBCgCQEEANgKEASAEKAJAQQZBtJsBKAIAEBQLIAQoAkBBADYChAEgBCgCQCgCgAEgBCgCQCgCGBAIIgBBgWBPBH9BtJsBQQAgAGs2AgBBfwUgAAtBAEgEQCAEKAJAQQJBtJsBKAIAEBQgBEJ/NwNYDA8LIAQoAkAoAoABEBUgBCgCQEEANgKAASAEQgA3A1gMDgsgBCAEKAJAIAQoAlAgBCkDSBBCNwNYDA0LIAQoAkAoAhgQFSAEKAJAKAKAARAVIAQoAkAoAhwEQCAEKAJAKAIcEFUaCyAEKAJAEBUgBEIANwNYDAwLIAQoAkAoAhgEQCAEKAJAKAIYIQEjAEEgayIAJAAgACABNgIYIABBADoAFyAAQYCAIDYCDAJAIAAtABdBAXEEQCAAIAAoAgxBAnI2AgwMAQsgACAAKAIMNgIMCyAAKAIYIQEgACgCDCEDIABBtgM2AgAgACABIAMgABBtIgE2AhACQCABQQBIBEAgAEEANgIcDAELIAAgACgCEEGjEkGgEiAALQAXQQFxGxChASIBNgIIIAFFBEAgAEEANgIcDAELIAAgACgCCDYCHAsgACgCHCEBIABBIGokACAEKAJAIAE2AhwgAUUEQCAEKAJAQQtBtJsBKAIAEBQgBEJ/NwNYDA0LCyAEKAJAKQNoQgBSBEAgBCgCQCgCHCAEKAJAKQNoIAQoAkAQnwFBAEgEQCAEQn83A1gMDQsLIAQoAkBCADcDeCAEQgA3A1gMCwsCQCAEKAJAKQNwQgBSBEAgBCAEKAJAKQNwIAQoAkApA3h9NwMwIAQpAzAgBCkDSFYEQCAEIAQpA0g3AzALDAELIAQgBCkDSDcDMAsgBCkDMEL/////D1YEQCAEQv////8PNwMwCyAEAn8gBCgCPCEHIAQpAzCnIQAgBCgCQCgCHCIDKAJMGiADIAMtAEoiAUEBayABcjoASiADKAIIIAMoAgQiBWsiAUEBSAR/IAAFIAcgBSABIAAgACABSxsiARAZGiADIAMoAgQgAWo2AgQgASAHaiEHIAAgAWsLIgEEQANAAkACfyADIAMtAEoiBUEBayAFcjoASiADKAIUIAMoAhxLBEAgA0EAQQAgAygCJBEBABoLIANBADYCHCADQgA3AxAgAygCACIFQQRxBEAgAyAFQSByNgIAQX8MAQsgAyADKAIsIAMoAjBqIgY2AgggAyAGNgIEIAVBG3RBH3ULRQRAIAMgByABIAMoAiARAQAiBUEBakEBSw0BCyAAIAFrDAMLIAUgB2ohByABIAVrIgENAAsLIAALIgA2AiwgAEUEQAJ/IAQoAkAoAhwiACgCTEF/TARAIAAoAgAMAQsgACgCAAtBBXZBAXEEQCAEKAJAQQVBtJsBKAIAEBQgBEJ/NwNYDAwLCyAEKAJAIgAgACkDeCAEKAIsrXw3A3ggBCAEKAIsrTcDWAwKCyAEKAJAKAIYEG5BAEgEQCAEKAJAQRZBtJsBKAIAEBQgBEJ/NwNYDAoLIARCADcDWAwJCyAEKAJAKAKEAQRAIAQoAkAoAoQBEFUaIAQoAkBBADYChAELIAQoAkAoAoABEG4aIAQoAkAoAoABEBUgBCgCQEEANgKAASAEQgA3A1gMCAsgBAJ/IAQpA0hCEFQEQCAEKAJAQRJBABAUQQAMAQsgBCgCUAs2AhggBCgCGEUEQCAEQn83A1gMCAsgBEEBNgIcAkACQAJAAkACQCAEKAIYKAIIDgMAAgEDCyAEIAQoAhgpAwA3AyAMAwsCQCAEKAJAKQNwUARAIAQoAkAoAhwgBCgCGCkDAEECIAQoAkAQa0EASARAIARCfzcDWAwNCyAEIAQoAkAoAhwQowEiAjcDICACQgBTBEAgBCgCQEEEQbSbASgCABAUIARCfzcDWAwNCyAEIAQpAyAgBCgCQCkDaH03AyAgBEEANgIcDAELIAQgBCgCQCkDcCAEKAIYKQMAfDcDIAsMAgsgBCAEKAJAKQN4IAQoAhgpAwB8NwMgDAELIAQoAkBBEkEAEBQgBEJ/NwNYDAgLAkACQCAEKQMgQgBTDQAgBCgCQCkDcEIAUgRAIAQpAyAgBCgCQCkDcFYNAQsgBCgCQCkDaCAEKQMgIAQoAkApA2h8WA0BCyAEKAJAQRJBABAUIARCfzcDWAwICyAEKAJAIAQpAyA3A3ggBCgCHARAIAQoAkAoAhwgBCgCQCkDeCAEKAJAKQNofCAEKAJAEJ8BQQBIBEAgBEJ/NwNYDAkLCyAEQgA3A1gMBwsgBAJ/IAQpA0hCEFQEQCAEKAJAQRJBABAUQQAMAQsgBCgCUAs2AhQgBCgCFEUEQCAEQn83A1gMBwsgBCgCQCgChAEgBCgCFCkDACAEKAIUKAIIIAQoAkAQa0EASARAIARCfzcDWAwHCyAEQgA3A1gMBgsgBCkDSEI4VARAIARCfzcDWAwGCwJ/IwBBEGsiACAEKAJAQdgAajYCDCAAKAIMKAIACwRAIAQoAkACfyMAQRBrIgAgBCgCQEHYAGo2AgwgACgCDCgCAAsCfyMAQRBrIgAgBCgCQEHYAGo2AgwgACgCDCgCBAsQFCAEQn83A1gMBgsgBCgCUCIAIAQoAkAiASkAIDcAACAAIAEpAFA3ADAgACABKQBINwAoIAAgASkAQDcAICAAIAEpADg3ABggACABKQAwNwAQIAAgASkAKDcACCAEQjg3A1gMBQsgBCAEKAJAKQMQNwNYDAQLIAQgBCgCQCkDeDcDWAwDCyAEIAQoAkAoAoQBEKMBNwMIIAQpAwhCAFMEQCAEKAJAQR5BtJsBKAIAEBQgBEJ/NwNYDAMLIAQgBCkDCDcDWAwCCyAEKAJAKAKEASIAKAJMQQBOGiAAIAAoAgBBT3E2AgAgBAJ/IAQoAlAhASAEKQNIpyIAIAACfyAEKAJAKAKEASIDKAJMQX9MBEAgASAAIAMQcgwBCyABIAAgAxByCyIBRg0AGiABCzYCBAJAIAQpA0ggBCgCBK1RBEACfyAEKAJAKAKEASIAKAJMQX9MBEAgACgCAAwBCyAAKAIAC0EFdkEBcUUNAQsgBCgCQEEGQbSbASgCABAUIARCfzcDWAwCCyAEIAQoAgStNwNYDAELIAQoAkBBHEEAEBQgBEJ/NwNYCyAEKQNYIQIgBEHgAGokACACCwkAIAAoAjwQBQvkAQEEfyMAQSBrIgMkACADIAE2AhAgAyACIAAoAjAiBEEAR2s2AhQgACgCLCEFIAMgBDYCHCADIAU2AhhBfyEEAkACQCAAKAI8IANBEGpBAiADQQxqEAYiBQR/QbSbASAFNgIAQX8FQQALRQRAIAMoAgwiBEEASg0BCyAAIAAoAgAgBEEwcUEQc3I2AgAMAQsgBCADKAIUIgZNDQAgACAAKAIsIgU2AgQgACAFIAQgBmtqNgIIIAAoAjAEQCAAIAVBAWo2AgQgASACakEBayAFLQAAOgAACyACIQQLIANBIGokACAEC/QCAQd/IwBBIGsiAyQAIAMgACgCHCIFNgIQIAAoAhQhBCADIAI2AhwgAyABNgIYIAMgBCAFayIBNgIUIAEgAmohBUECIQcgA0EQaiEBAn8CQAJAIAAoAjwgA0EQakECIANBDGoQAyIEBH9BtJsBIAQ2AgBBfwVBAAtFBEADQCAFIAMoAgwiBEYNAiAEQX9MDQMgASAEIAEoAgQiCEsiBkEDdGoiCSAEIAhBACAGG2siCCAJKAIAajYCACABQQxBBCAGG2oiCSAJKAIAIAhrNgIAIAUgBGshBSAAKAI8IAFBCGogASAGGyIBIAcgBmsiByADQQxqEAMiBAR/QbSbASAENgIAQX8FQQALRQ0ACwsgBUF/Rw0BCyAAIAAoAiwiATYCHCAAIAE2AhQgACABIAAoAjBqNgIQIAIMAQsgAEEANgIcIABCADcDECAAIAAoAgBBIHI2AgBBACAHQQJGDQAaIAIgASgCBGsLIQAgA0EgaiQAIAALUgEBfyMAQRBrIgMkACAAKAI8IAGnIAFCIIinIAJB/wFxIANBCGoQDSIABH9BtJsBIAA2AgBBfwVBAAshACADKQMIIQEgA0EQaiQAQn8gASAAGwtFAEGgmwFCADcDAEGYmwFCADcDAEGQmwFCADcDAEGImwFCADcDAEGAmwFCADcDAEH4mgFCADcDAEHwmgFCADcDAEHwmgEL1QQBBX8jAEGwAWsiASQAIAEgADYCqAEgASgCqAEQNwJAAkAgASgCqAEoAgBBAE4EQCABKAKoASgCAEGAFCgCAEgNAQsgASABKAKoASgCADYCECABQSBqQY8SIAFBEGoQcCABQQA2AqQBIAEgAUEgajYCoAEMAQsgASABKAKoASgCAEECdEGAE2ooAgA2AqQBAkACQAJAAkAgASgCqAEoAgBBAnRBkBRqKAIAQQFrDgIAAQILIAEoAqgBKAIEIQJBkJkBKAIAIQRBACEAAkACQANAIAIgAEGgiAFqLQAARwRAQdcAIQMgAEEBaiIAQdcARw0BDAILCyAAIgMNAEGAiQEhAgwBC0GAiQEhAANAIAAtAAAhBSAAQQFqIgIhACAFDQAgAiEAIANBAWsiAw0ACwsgBCgCFBogASACNgKgAQwCCyMAQRBrIgAgASgCqAEoAgQ2AgwgAUEAIAAoAgxrQQJ0QajZAGooAgA2AqABDAELIAFBADYCoAELCwJAIAEoAqABRQRAIAEgASgCpAE2AqwBDAELIAEgASgCoAEQKwJ/IAEoAqQBBEAgASgCpAEQK0ECagwBC0EAC2pBAWoQGCIANgIcIABFBEAgAUG4EygCADYCrAEMAQsgASgCHCEAAn8gASgCpAEEQCABKAKkAQwBC0H6EgshA0HfEkH6EiABKAKkARshAiABIAEoAqABNgIIIAEgAjYCBCABIAM2AgAgAEG+CiABEHAgASgCqAEgASgCHDYCCCABIAEoAhw2AqwBCyABKAKsASEAIAFBsAFqJAAgAAszAQF/IAAoAhQiAyABIAIgACgCECADayIBIAEgAksbIgEQGRogACAAKAIUIAFqNgIUIAILjwUCBn4BfyABIAEoAgBBD2pBcHEiAUEQajYCACAAAnwgASkDACEDIAEpAwghBiMAQSBrIggkAAJAIAZC////////////AIMiBEKAgICAgIDAgDx9IARCgICAgICAwP/DAH1UBEAgBkIEhiADQjyIhCEEIANC//////////8PgyIDQoGAgICAgICACFoEQCAEQoGAgICAgICAwAB8IQIMAgsgBEKAgICAgICAgEB9IQIgA0KAgICAgICAgAiFQgBSDQEgAiAEQgGDfCECDAELIANQIARCgICAgICAwP//AFQgBEKAgICAgIDA//8AURtFBEAgBkIEhiADQjyIhEL/////////A4NCgICAgICAgPz/AIQhAgwBC0KAgICAgICA+P8AIQIgBEL///////+//8MAVg0AQgAhAiAEQjCIpyIAQZH3AEkNACADIQIgBkL///////8/g0KAgICAgIDAAIQiBSEHAkAgAEGB9wBrIgFBwABxBEAgAiABQUBqrYYhB0IAIQIMAQsgAUUNACAHIAGtIgSGIAJBwAAgAWutiIQhByACIASGIQILIAggAjcDECAIIAc3AxgCQEGB+AAgAGsiAEHAAHEEQCAFIABBQGqtiCEDQgAhBQwBCyAARQ0AIAVBwAAgAGuthiADIACtIgKIhCEDIAUgAoghBQsgCCADNwMAIAggBTcDCCAIKQMIQgSGIAgpAwAiA0I8iIQhAiAIKQMQIAgpAxiEQgBSrSADQv//////////D4OEIgNCgYCAgICAgIAIWgRAIAJCAXwhAgwBCyADQoCAgICAgICACIVCAFINACACQgGDIAJ8IQILIAhBIGokACACIAZCgICAgICAgICAf4OEvws5AwALrRcDEn8CfgF8IwBBsARrIgkkACAJQQA2AiwCQCABvSIYQn9XBEBBASESQa4IIRMgAZoiAb0hGAwBCyAEQYAQcQRAQQEhEkGxCCETDAELQbQIQa8IIARBAXEiEhshEyASRSEXCwJAIBhCgICAgICAgPj/AINCgICAgICAgPj/AFEEQCAAQSAgAiASQQNqIg0gBEH//3txECYgACATIBIQIiAAQeQLQbUSIAVBIHEiAxtBjw1BuRIgAxsgASABYhtBAxAiDAELIAlBEGohEAJAAn8CQCABIAlBLGoQqQEiASABoCIBRAAAAAAAAAAAYgRAIAkgCSgCLCIGQQFrNgIsIAVBIHIiFEHhAEcNAQwDCyAFQSByIhRB4QBGDQIgCSgCLCELQQYgAyADQQBIGwwBCyAJIAZBHWsiCzYCLCABRAAAAAAAALBBoiEBQQYgAyADQQBIGwshCiAJQTBqIAlB0AJqIAtBAEgbIg4hBwNAIAcCfyABRAAAAAAAAPBBYyABRAAAAAAAAAAAZnEEQCABqwwBC0EACyIDNgIAIAdBBGohByABIAO4oUQAAAAAZc3NQaIiAUQAAAAAAAAAAGINAAsCQCALQQFIBEAgCyEDIAchBiAOIQgMAQsgDiEIIAshAwNAIANBHSADQR1IGyEMAkAgB0EEayIGIAhJDQAgDK0hGUIAIRgDQCAGIAY1AgAgGYYgGHwiGCAYQoCU69wDgCIYQoCU69wDfn0+AgAgCCAGQQRrIgZNBEAgGEL/////D4MhGAwBCwsgGKciA0UNACAIQQRrIgggAzYCAAsDQCAIIAciBkkEQCAGQQRrIgcoAgBFDQELCyAJIAkoAiwgDGsiAzYCLCAGIQcgA0EASg0ACwsgCkEZakEJbSEHIANBf0wEQCAHQQFqIQ0gFEHmAEYhFQNAQQlBACADayADQXdIGyEWAkAgBiAISwRAQYCU69wDIBZ2IQ9BfyAWdEF/cyERQQAhAyAIIQcDQCAHIAMgBygCACIMIBZ2ajYCACAMIBFxIA9sIQMgB0EEaiIHIAZJDQALIAggCEEEaiAIKAIAGyEIIANFDQEgBiADNgIAIAZBBGohBgwBCyAIIAhBBGogCCgCABshCAsgCSAJKAIsIBZqIgM2AiwgDiAIIBUbIgcgDUECdGogBiAGIAdrQQJ1IA1KGyEGIANBAEgNAAsLQQAhBwJAIAYgCE0NACAOIAhrQQJ1QQlsIQcgCCgCACIMQQpJDQBB5AAhAwNAIAdBAWohByADIAxLDQEgA0EKbCEDDAALAAsgCkEAIAcgFEHmAEYbayAUQecARiAKQQBHcWsiAyAGIA5rQQJ1QQlsQQlrSARAIANBgMgAaiIRQQltIgxBAnQgCUEwakEEciAJQdQCaiALQQBIG2pBgCBrIQ1BCiEDAkAgESAMQQlsayIMQQdKDQBB5AAhAwNAIAxBAWoiDEEIRg0BIANBCmwhAwwACwALAkAgDSgCACIRIBEgA24iDCADbGsiD0EBIA1BBGoiCyAGRhtFDQBEAAAAAAAA4D9EAAAAAAAA8D9EAAAAAAAA+D8gBiALRhtEAAAAAAAA+D8gDyADQQF2IgtGGyALIA9LGyEaRAEAAAAAAEBDRAAAAAAAAEBDIAxBAXEbIQECQCAXDQAgEy0AAEEtRw0AIBqaIRogAZohAQsgDSARIA9rIgs2AgAgASAaoCABYQ0AIA0gAyALaiIDNgIAIANBgJTr3ANPBEADQCANQQA2AgAgCCANQQRrIg1LBEAgCEEEayIIQQA2AgALIA0gDSgCAEEBaiIDNgIAIANB/5Pr3ANLDQALCyAOIAhrQQJ1QQlsIQcgCCgCACILQQpJDQBB5AAhAwNAIAdBAWohByADIAtLDQEgA0EKbCEDDAALAAsgDUEEaiIDIAYgAyAGSRshBgsDQCAGIgsgCE0iDEUEQCALQQRrIgYoAgBFDQELCwJAIBRB5wBHBEAgBEEIcSEPDAELIAdBf3NBfyAKQQEgChsiBiAHSiAHQXtKcSIDGyAGaiEKQX9BfiADGyAFaiEFIARBCHEiDw0AQXchBgJAIAwNACALQQRrKAIAIgNFDQBBACEGIANBCnANAEEAIQxB5AAhBgNAIAMgBnBFBEAgDEEBaiEMIAZBCmwhBgwBCwsgDEF/cyEGCyALIA5rQQJ1QQlsIQMgBUFfcUHGAEYEQEEAIQ8gCiADIAZqQQlrIgNBACADQQBKGyIDIAMgCkobIQoMAQtBACEPIAogAyAHaiAGakEJayIDQQAgA0EAShsiAyADIApKGyEKCyAKIA9yQQBHIREgAEEgIAIgBUFfcSIMQcYARgR/IAdBACAHQQBKGwUgECAHIAdBH3UiA2ogA3OtIBAQRCIGa0EBTARAA0AgBkEBayIGQTA6AAAgECAGa0ECSA0ACwsgBkECayIVIAU6AAAgBkEBa0EtQSsgB0EASBs6AAAgECAVawsgCiASaiARampBAWoiDSAEECYgACATIBIQIiAAQTAgAiANIARBgIAEcxAmAkACQAJAIAxBxgBGBEAgCUEQakEIciEDIAlBEGpBCXIhByAOIAggCCAOSxsiBSEIA0AgCDUCACAHEEQhBgJAIAUgCEcEQCAGIAlBEGpNDQEDQCAGQQFrIgZBMDoAACAGIAlBEGpLDQALDAELIAYgB0cNACAJQTA6ABggAyEGCyAAIAYgByAGaxAiIAhBBGoiCCAOTQ0AC0EAIQYgEUUNAiAAQdYSQQEQIiAIIAtPDQEgCkEBSA0BA0AgCDUCACAHEEQiBiAJQRBqSwRAA0AgBkEBayIGQTA6AAAgBiAJQRBqSw0ACwsgACAGIApBCSAKQQlIGxAiIApBCWshBiAIQQRqIgggC08NAyAKQQlKIQMgBiEKIAMNAAsMAgsCQCAKQQBIDQAgCyAIQQRqIAggC0kbIQUgCUEQakEJciELIAlBEGpBCHIhAyAIIQcDQCALIAc1AgAgCxBEIgZGBEAgCUEwOgAYIAMhBgsCQCAHIAhHBEAgBiAJQRBqTQ0BA0AgBkEBayIGQTA6AAAgBiAJQRBqSw0ACwwBCyAAIAZBARAiIAZBAWohBkEAIApBAEwgDxsNACAAQdYSQQEQIgsgACAGIAsgBmsiBiAKIAYgCkgbECIgCiAGayEKIAdBBGoiByAFTw0BIApBf0oNAAsLIABBMCAKQRJqQRJBABAmIAAgFSAQIBVrECIMAgsgCiEGCyAAQTAgBkEJakEJQQAQJgsMAQsgE0EJaiATIAVBIHEiCxshCgJAIANBC0sNAEEMIANrIgZFDQBEAAAAAAAAIEAhGgNAIBpEAAAAAAAAMECiIRogBkEBayIGDQALIAotAABBLUYEQCAaIAGaIBqhoJohAQwBCyABIBqgIBqhIQELIBAgCSgCLCIGIAZBH3UiBmogBnOtIBAQRCIGRgRAIAlBMDoADyAJQQ9qIQYLIBJBAnIhDiAJKAIsIQcgBkECayIMIAVBD2o6AAAgBkEBa0EtQSsgB0EASBs6AAAgBEEIcSEHIAlBEGohCANAIAgiBQJ/IAGZRAAAAAAAAOBBYwRAIAGqDAELQYCAgIB4CyIGQYCHAWotAAAgC3I6AAAgASAGt6FEAAAAAAAAMECiIQECQCAFQQFqIgggCUEQamtBAUcNAAJAIAFEAAAAAAAAAABiDQAgA0EASg0AIAdFDQELIAVBLjoAASAFQQJqIQgLIAFEAAAAAAAAAABiDQALIABBICACIA4CfwJAIANFDQAgCCAJa0ESayADTg0AIAMgEGogDGtBAmoMAQsgECAJQRBqIAxqayAIagsiA2oiDSAEECYgACAKIA4QIiAAQTAgAiANIARBgIAEcxAmIAAgCUEQaiAIIAlBEGprIgUQIiAAQTAgAyAFIBAgDGsiA2prQQBBABAmIAAgDCADECILIABBICACIA0gBEGAwABzECYgCUGwBGokACACIA0gAiANShsLBgBB4J8BCwYAQdyfAQsGAEHUnwELGAEBfyMAQRBrIgEgADYCDCABKAIMQQRqCxgBAX8jAEEQayIBIAA2AgwgASgCDEEIagtpAQF/IwBBEGsiASQAIAEgADYCDCABKAIMKAIUBEAgASgCDCgCFBAbCyABQQA2AgggASgCDCgCBARAIAEgASgCDCgCBDYCCAsgASgCDEEEahA3IAEoAgwQFSABKAIIIQAgAUEQaiQAIAALqQEBA38CQCAALQAAIgJFDQADQCABLQAAIgRFBEAgAiEDDAILAkAgAiAERg0AIAJBIHIgAiACQcEAa0EaSRsgAS0AACICQSByIAIgAkHBAGtBGkkbRg0AIAAtAAAhAwwCCyABQQFqIQEgAC0AASECIABBAWohACACDQALCyADQf8BcSIAQSByIAAgAEHBAGtBGkkbIAEtAAAiAEEgciAAIABBwQBrQRpJG2sL2AkBAX8jAEGwAWsiBSQAIAUgADYCpAEgBSABNgKgASAFIAI2ApwBIAUgAzcDkAEgBSAENgKMASAFIAUoAqABNgKIAQJAAkACQAJAAkACQAJAAkACQAJAAkAgBSgCjAEODwABAgMEBQcICQkJCQkJBgkLIAUoAogBQgA3AyAgBUIANwOoAQwJCyAFIAUoAqQBIAUoApwBIAUpA5ABEC4iAzcDgAEgA0IAUwRAIAUoAogBQQhqIAUoAqQBEBcgBUJ/NwOoAQwJCwJAIAUpA4ABUARAIAUoAogBKQMoIAUoAogBKQMgUQRAIAUoAogBQQE2AgQgBSgCiAEgBSgCiAEpAyA3AxggBSgCiAEoAgAEQCAFKAKkASAFQcgAahA4QQBIBEAgBSgCiAFBCGogBSgCpAEQFyAFQn83A6gBDA0LAkAgBSkDSEIgg1ANACAFKAJ0IAUoAogBKAIwRg0AIAUoAogBQQhqQQdBABAUIAVCfzcDqAEMDQsCQCAFKQNIQgSDUA0AIAUpA2AgBSgCiAEpAxhRDQAgBSgCiAFBCGpBFUEAEBQgBUJ/NwOoAQwNCwsLDAELAkAgBSgCiAEoAgQNACAFKAKIASkDICAFKAKIASkDKFYNACAFIAUoAogBKQMoIAUoAogBKQMgfTcDQANAIAUpA0AgBSkDgAFUBEAgBSAFKQOAASAFKQNAfUL/////D1YEfkL/////DwUgBSkDgAEgBSkDQH0LNwM4IAUoAogBKAIwIAUoApwBIAUpA0CnaiAFKQM4pxAaIQAgBSgCiAEgADYCMCAFKAKIASIAIAUpAzggACkDKHw3AyggBSAFKQM4IAUpA0B8NwNADAELCwsLIAUoAogBIgAgBSkDgAEgACkDIHw3AyAgBSAFKQOAATcDqAEMCAsgBUIANwOoAQwHCyAFIAUoApwBNgI0IAUoAogBKAIEBEAgBSgCNCAFKAKIASkDGDcDGCAFKAI0IAUoAogBKAIwNgIsIAUoAjQgBSgCiAEpAxg3AyAgBSgCNEEAOwEwIAUoAjRBADsBMiAFKAI0IgAgACkDAELsAYQ3AwALIAVCADcDqAEMBgsgBSAFKAKIAUEIaiAFKAKcASAFKQOQARBCNwOoAQwFCyAFKAKIARAVIAVCADcDqAEMBAsjAEEQayIAIAUoAqQBNgIMIAUgACgCDCkDGDcDKCAFKQMoQgBTBEAgBSgCiAFBCGogBSgCpAEQFyAFQn83A6gBDAQLIAUpAyghAyAFQX82AhggBUEQNgIUIAVBDzYCECAFQQ02AgwgBUEMNgIIIAVBCjYCBCAFQQk2AgAgBUEIIAUQNkJ/hSADgzcDqAEMAwsgBQJ/IAUpA5ABQhBUBEAgBSgCiAFBCGpBEkEAEBRBAAwBCyAFKAKcAQs2AhwgBSgCHEUEQCAFQn83A6gBDAMLAkAgBSgCpAEgBSgCHCkDACAFKAIcKAIIECdBAE4EQCAFIAUoAqQBEEoiAzcDICADQgBZDQELIAUoAogBQQhqIAUoAqQBEBcgBUJ/NwOoAQwDCyAFKAKIASAFKQMgNwMgIAVCADcDqAEMAgsgBSAFKAKIASkDIDcDqAEMAQsgBSgCiAFBCGpBHEEAEBQgBUJ/NwOoAQsgBSkDqAEhAyAFQbABaiQAIAMLnAwBAX8jAEEwayIFJAAgBSAANgIkIAUgATYCICAFIAI2AhwgBSADNwMQIAUgBDYCDCAFIAUoAiA2AggCQAJAAkACQAJAAkACQAJAAkACQCAFKAIMDhEAAQIDBQYICAgICAgICAcIBAgLIAUoAghCADcDGCAFKAIIQQA6AAwgBSgCCEEAOgANIAUoAghBADoADyAFKAIIQn83AyAgBSgCCCgCrEAgBSgCCCgCqEAoAgwRAABBAXFFBEAgBUJ/NwMoDAkLIAVCADcDKAwICyAFKAIkIQEgBSgCCCECIAUoAhwhBCAFKQMQIQMjAEFAaiIAJAAgACABNgI0IAAgAjYCMCAAIAQ2AiwgACADNwMgAkACfyMAQRBrIgEgACgCMDYCDCABKAIMKAIACwRAIABCfzcDOAwBCwJAIAApAyBQRQRAIAAoAjAtAA1BAXFFDQELIABCADcDOAwBCyAAQgA3AwggAEEAOgAbA0AgAC0AG0EBcQR/QQAFIAApAwggACkDIFQLQQFxBEAgACAAKQMgIAApAwh9NwMAIAAgACgCMCgCrEAgACgCLCAAKQMIp2ogACAAKAIwKAKoQCgCHBEBADYCHCAAKAIcQQJHBEAgACAAKQMAIAApAwh8NwMICwJAAkACQAJAIAAoAhxBAWsOAwACAQMLIAAoAjBBAToADQJAIAAoAjAtAAxBAXENAAsgACgCMCkDIEIAUwRAIAAoAjBBFEEAEBQgAEEBOgAbDAMLAkAgACgCMC0ADkEBcUUNACAAKAIwKQMgIAApAwhWDQAgACgCMEEBOgAPIAAoAjAgACgCMCkDIDcDGCAAKAIsIAAoAjBBKGogACgCMCkDGKcQGRogACAAKAIwKQMYNwM4DAYLIABBAToAGwwCCyAAKAIwLQAMQQFxBEAgAEEBOgAbDAILIAAgACgCNCAAKAIwQShqQoDAABAuIgM3AxAgA0IAUwRAIAAoAjAgACgCNBAXIABBAToAGwwCCwJAIAApAxBQBEAgACgCMEEBOgAMIAAoAjAoAqxAIAAoAjAoAqhAKAIYEQIAIAAoAjApAyBCAFMEQCAAKAIwQgA3AyALDAELAkAgACgCMCkDIEIAWQRAIAAoAjBBADoADgwBCyAAKAIwIAApAxA3AyALIAAoAjAoAqxAIAAoAjBBKGogACkDECAAKAIwKAKoQCgCFBEQABoLDAELAn8jAEEQayIBIAAoAjA2AgwgASgCDCgCAEULBEAgACgCMEEUQQAQFAsgAEEBOgAbCwwBCwsgACkDCEIAUgRAIAAoAjBBADoADiAAKAIwIgEgACkDCCABKQMYfDcDGCAAIAApAwg3AzgMAQsgAEF/QQACfyMAQRBrIgEgACgCMDYCDCABKAIMKAIACxusNwM4CyAAKQM4IQMgAEFAayQAIAUgAzcDKAwHCyAFKAIIKAKsQCAFKAIIKAKoQCgCEBEAAEEBcUUEQCAFQn83AygMBwsgBUIANwMoDAYLIAUgBSgCHDYCBAJAIAUoAggtABBBAXEEQCAFKAIILQANQQFxBEAgBSgCBCAFKAIILQAPQQFxBH9BAAUCfwJAIAUoAggoAhRBf0cEQCAFKAIIKAIUQX5HDQELQQgMAQsgBSgCCCgCFAtB//8DcQs7ATAgBSgCBCAFKAIIKQMYNwMgIAUoAgQiACAAKQMAQsgAhDcDAAwCCyAFKAIEIgAgACkDAEK3////D4M3AwAMAQsgBSgCBEEAOwEwIAUoAgQiACAAKQMAQsAAhDcDAAJAIAUoAggtAA1BAXEEQCAFKAIEIAUoAggpAxg3AxggBSgCBCIAIAApAwBCBIQ3AwAMAQsgBSgCBCIAIAApAwBC+////w+DNwMACwsgBUIANwMoDAULIAUgBSgCCC0AD0EBcQR/QQAFIAUoAggoAqxAIAUoAggoAqhAKAIIEQAAC6w3AygMBAsgBSAFKAIIIAUoAhwgBSkDEBBCNwMoDAMLIAUoAggQsQEgBUIANwMoDAILIAVBfzYCACAFQRAgBRA2Qj+ENwMoDAELIAUoAghBFEEAEBQgBUJ/NwMoCyAFKQMoIQMgBUEwaiQAIAMLPAEBfyMAQRBrIgMkACADIAA7AQ4gAyABNgIIIAMgAjYCBEEAIAMoAgggAygCBBC0ASEAIANBEGokACAAC46nAQEEfyMAQSBrIgUkACAFIAA2AhggBSABNgIUIAUgAjYCECAFIAUoAhg2AgwgBSgCDCAFKAIQKQMAQv////8PVgR+Qv////8PBSAFKAIQKQMACz4CICAFKAIMIAUoAhQ2AhwCQCAFKAIMLQAEQQFxBEAgBSgCDEEQaiEBQQRBACAFKAIMLQAMQQFxGyECIwBBQGoiACQAIAAgATYCOCAAIAI2AjQCQAJAAkAgACgCOBB5DQAgACgCNEEFSg0AIAAoAjRBAE4NAQsgAEF+NgI8DAELIAAgACgCOCgCHDYCLAJAAkAgACgCOCgCDEUNACAAKAI4KAIEBEAgACgCOCgCAEUNAQsgACgCLCgCBEGaBUcNASAAKAI0QQRGDQELIAAoAjhBsNkAKAIANgIYIABBfjYCPAwBCyAAKAI4KAIQRQRAIAAoAjhBvNkAKAIANgIYIABBezYCPAwBCyAAIAAoAiwoAig2AjAgACgCLCAAKAI0NgIoAkAgACgCLCgCFARAIAAoAjgQHCAAKAI4KAIQRQRAIAAoAixBfzYCKCAAQQA2AjwMAwsMAQsCQCAAKAI4KAIEDQAgACgCNEEBdEEJQQAgACgCNEEEShtrIAAoAjBBAXRBCUEAIAAoAjBBBEoba0oNACAAKAI0QQRGDQAgACgCOEG82QAoAgA2AhggAEF7NgI8DAILCwJAIAAoAiwoAgRBmgVHDQAgACgCOCgCBEUNACAAKAI4QbzZACgCADYCGCAAQXs2AjwMAQsgACgCLCgCBEEqRgRAIAAgACgCLCgCMEEEdEH4AGtBCHQ2AigCQAJAIAAoAiwoAogBQQJIBEAgACgCLCgChAFBAk4NAQsgAEEANgIkDAELAkAgACgCLCgChAFBBkgEQCAAQQE2AiQMAQsCQCAAKAIsKAKEAUEGRgRAIABBAjYCJAwBCyAAQQM2AiQLCwsgACAAKAIoIAAoAiRBBnRyNgIoIAAoAiwoAmwEQCAAIAAoAihBIHI2AigLIAAgACgCKEEfIAAoAihBH3BrajYCKCAAKAIsIAAoAigQTCAAKAIsKAJsBEAgACgCLCAAKAI4KAIwQRB2EEwgACgCLCAAKAI4KAIwQf//A3EQTAtBAEEAQQAQPiEBIAAoAjggATYCMCAAKAIsQfEANgIEIAAoAjgQHCAAKAIsKAIUBEAgACgCLEF/NgIoIABBADYCPAwCCwsgACgCLCgCBEE5RgRAQQBBAEEAEBohASAAKAI4IAE2AjAgACgCLCgCCCECIAAoAiwiAygCFCEBIAMgAUEBajYCFCABIAJqQR86AAAgACgCLCgCCCECIAAoAiwiAygCFCEBIAMgAUEBajYCFCABIAJqQYsBOgAAIAAoAiwoAgghAiAAKAIsIgMoAhQhASADIAFBAWo2AhQgASACakEIOgAAAkAgACgCLCgCHEUEQCAAKAIsKAIIIQIgACgCLCIDKAIUIQEgAyABQQFqNgIUIAEgAmpBADoAACAAKAIsKAIIIQIgACgCLCIDKAIUIQEgAyABQQFqNgIUIAEgAmpBADoAACAAKAIsKAIIIQIgACgCLCIDKAIUIQEgAyABQQFqNgIUIAEgAmpBADoAACAAKAIsKAIIIQIgACgCLCIDKAIUIQEgAyABQQFqNgIUIAEgAmpBADoAACAAKAIsKAIIIQIgACgCLCIDKAIUIQEgAyABQQFqNgIUIAEgAmpBADoAACAAKAIsKAKEAUEJRgR/QQIFQQRBACAAKAIsKAKIAUECSAR/IAAoAiwoAoQBQQJIBUEBC0EBcRsLIQIgACgCLCgCCCEDIAAoAiwiBCgCFCEBIAQgAUEBajYCFCABIANqIAI6AAAgACgCLCgCCCECIAAoAiwiAygCFCEBIAMgAUEBajYCFCABIAJqQQM6AAAgACgCLEHxADYCBCAAKAI4EBwgACgCLCgCFARAIAAoAixBfzYCKCAAQQA2AjwMBAsMAQsgACgCLCgCHCgCAEVFQQJBACAAKAIsKAIcKAIsG2pBBEEAIAAoAiwoAhwoAhAbakEIQQAgACgCLCgCHCgCHBtqQRBBACAAKAIsKAIcKAIkG2ohAiAAKAIsKAIIIQMgACgCLCIEKAIUIQEgBCABQQFqNgIUIAEgA2ogAjoAACAAKAIsKAIcKAIEQf8BcSECIAAoAiwoAgghAyAAKAIsIgQoAhQhASAEIAFBAWo2AhQgASADaiACOgAAIAAoAiwoAhwoAgRBCHZB/wFxIQIgACgCLCgCCCEDIAAoAiwiBCgCFCEBIAQgAUEBajYCFCABIANqIAI6AAAgACgCLCgCHCgCBEEQdkH/AXEhAiAAKAIsKAIIIQMgACgCLCIEKAIUIQEgBCABQQFqNgIUIAEgA2ogAjoAACAAKAIsKAIcKAIEQRh2IQIgACgCLCgCCCEDIAAoAiwiBCgCFCEBIAQgAUEBajYCFCABIANqIAI6AAAgACgCLCgChAFBCUYEf0ECBUEEQQAgACgCLCgCiAFBAkgEfyAAKAIsKAKEAUECSAVBAQtBAXEbCyECIAAoAiwoAgghAyAAKAIsIgQoAhQhASAEIAFBAWo2AhQgASADaiACOgAAIAAoAiwoAhwoAgxB/wFxIQIgACgCLCgCCCEDIAAoAiwiBCgCFCEBIAQgAUEBajYCFCABIANqIAI6AAAgACgCLCgCHCgCEARAIAAoAiwoAhwoAhRB/wFxIQIgACgCLCgCCCEDIAAoAiwiBCgCFCEBIAQgAUEBajYCFCABIANqIAI6AAAgACgCLCgCHCgCFEEIdkH/AXEhAiAAKAIsKAIIIQMgACgCLCIEKAIUIQEgBCABQQFqNgIUIAEgA2ogAjoAAAsgACgCLCgCHCgCLARAIAAoAjgoAjAgACgCLCgCCCAAKAIsKAIUEBohASAAKAI4IAE2AjALIAAoAixBADYCICAAKAIsQcUANgIECwsgACgCLCgCBEHFAEYEQCAAKAIsKAIcKAIQBEAgACAAKAIsKAIUNgIgIAAgACgCLCgCHCgCFEH//wNxIAAoAiwoAiBrNgIcA0AgACgCLCgCDCAAKAIsKAIUIAAoAhxqSQRAIAAgACgCLCgCDCAAKAIsKAIUazYCGCAAKAIsKAIIIAAoAiwoAhRqIAAoAiwoAhwoAhAgACgCLCgCIGogACgCGBAZGiAAKAIsIAAoAiwoAgw2AhQCQCAAKAIsKAIcKAIsRQ0AIAAoAiwoAhQgACgCIE0NACAAKAI4KAIwIAAoAiwoAgggACgCIGogACgCLCgCFCAAKAIgaxAaIQEgACgCOCABNgIwCyAAKAIsIgEgACgCGCABKAIgajYCICAAKAI4EBwgACgCLCgCFARAIAAoAixBfzYCKCAAQQA2AjwMBQUgAEEANgIgIAAgACgCHCAAKAIYazYCHAwCCwALCyAAKAIsKAIIIAAoAiwoAhRqIAAoAiwoAhwoAhAgACgCLCgCIGogACgCHBAZGiAAKAIsIgEgACgCHCABKAIUajYCFAJAIAAoAiwoAhwoAixFDQAgACgCLCgCFCAAKAIgTQ0AIAAoAjgoAjAgACgCLCgCCCAAKAIgaiAAKAIsKAIUIAAoAiBrEBohASAAKAI4IAE2AjALIAAoAixBADYCIAsgACgCLEHJADYCBAsgACgCLCgCBEHJAEYEQCAAKAIsKAIcKAIcBEAgACAAKAIsKAIUNgIUA0AgACgCLCgCFCAAKAIsKAIMRgRAAkAgACgCLCgCHCgCLEUNACAAKAIsKAIUIAAoAhRNDQAgACgCOCgCMCAAKAIsKAIIIAAoAhRqIAAoAiwoAhQgACgCFGsQGiEBIAAoAjggATYCMAsgACgCOBAcIAAoAiwoAhQEQCAAKAIsQX82AiggAEEANgI8DAULIABBADYCFAsgACgCLCgCHCgCHCECIAAoAiwiAygCICEBIAMgAUEBajYCICAAIAEgAmotAAA2AhAgACgCECECIAAoAiwoAgghAyAAKAIsIgQoAhQhASAEIAFBAWo2AhQgASADaiACOgAAIAAoAhANAAsCQCAAKAIsKAIcKAIsRQ0AIAAoAiwoAhQgACgCFE0NACAAKAI4KAIwIAAoAiwoAgggACgCFGogACgCLCgCFCAAKAIUaxAaIQEgACgCOCABNgIwCyAAKAIsQQA2AiALIAAoAixB2wA2AgQLIAAoAiwoAgRB2wBGBEAgACgCLCgCHCgCJARAIAAgACgCLCgCFDYCDANAIAAoAiwoAhQgACgCLCgCDEYEQAJAIAAoAiwoAhwoAixFDQAgACgCLCgCFCAAKAIMTQ0AIAAoAjgoAjAgACgCLCgCCCAAKAIMaiAAKAIsKAIUIAAoAgxrEBohASAAKAI4IAE2AjALIAAoAjgQHCAAKAIsKAIUBEAgACgCLEF/NgIoIABBADYCPAwFCyAAQQA2AgwLIAAoAiwoAhwoAiQhAiAAKAIsIgMoAiAhASADIAFBAWo2AiAgACABIAJqLQAANgIIIAAoAgghAiAAKAIsKAIIIQMgACgCLCIEKAIUIQEgBCABQQFqNgIUIAEgA2ogAjoAACAAKAIIDQALAkAgACgCLCgCHCgCLEUNACAAKAIsKAIUIAAoAgxNDQAgACgCOCgCMCAAKAIsKAIIIAAoAgxqIAAoAiwoAhQgACgCDGsQGiEBIAAoAjggATYCMAsLIAAoAixB5wA2AgQLIAAoAiwoAgRB5wBGBEAgACgCLCgCHCgCLARAIAAoAiwoAgwgACgCLCgCFEECakkEQCAAKAI4EBwgACgCLCgCFARAIAAoAixBfzYCKCAAQQA2AjwMBAsLIAAoAjgoAjBB/wFxIQIgACgCLCgCCCEDIAAoAiwiBCgCFCEBIAQgAUEBajYCFCABIANqIAI6AAAgACgCOCgCMEEIdkH/AXEhAiAAKAIsKAIIIQMgACgCLCIEKAIUIQEgBCABQQFqNgIUIAEgA2ogAjoAAEEAQQBBABAaIQEgACgCOCABNgIwCyAAKAIsQfEANgIEIAAoAjgQHCAAKAIsKAIUBEAgACgCLEF/NgIoIABBADYCPAwCCwsCQAJAIAAoAjgoAgQNACAAKAIsKAJ0DQAgACgCNEUNASAAKAIsKAIEQZoFRg0BCyAAAn8gACgCLCgChAFFBEAgACgCLCAAKAI0ELYBDAELAn8gACgCLCgCiAFBAkYEQCAAKAIsIQIgACgCNCEDIwBBIGsiASQAIAEgAjYCGCABIAM2AhQCQANAAkAgASgCGCgCdEUEQCABKAIYEFsgASgCGCgCdEUEQCABKAIURQRAIAFBADYCHAwFCwwCCwsgASgCGEEANgJgIAEgASgCGCICKAI4IAIoAmxqLQAAOgAPIAEoAhgiAigCpC0gAigCoC1BAXRqQQA7AQAgAS0ADyEDIAEoAhgiAigCmC0hBCACIAIoAqAtIgJBAWo2AqAtIAIgBGogAzoAACABKAIYIAEtAA9BAnRqIgIgAi8BlAFBAWo7AZQBIAEgASgCGCgCoC0gASgCGCgCnC1BAWtGNgIQIAEoAhgiAiACKAJ0QQFrNgJ0IAEoAhgiAiACKAJsQQFqNgJsIAEoAhAEQCABKAIYAn8gASgCGCgCXEEATgRAIAEoAhgoAjggASgCGCgCXGoMAQtBAAsgASgCGCgCbCABKAIYKAJca0EAECggASgCGCABKAIYKAJsNgJcIAEoAhgoAgAQHCABKAIYKAIAKAIQRQRAIAFBADYCHAwECwsMAQsLIAEoAhhBADYCtC0gASgCFEEERgRAIAEoAhgCfyABKAIYKAJcQQBOBEAgASgCGCgCOCABKAIYKAJcagwBC0EACyABKAIYKAJsIAEoAhgoAlxrQQEQKCABKAIYIAEoAhgoAmw2AlwgASgCGCgCABAcIAEoAhgoAgAoAhBFBEAgAUECNgIcDAILIAFBAzYCHAwBCyABKAIYKAKgLQRAIAEoAhgCfyABKAIYKAJcQQBOBEAgASgCGCgCOCABKAIYKAJcagwBC0EACyABKAIYKAJsIAEoAhgoAlxrQQAQKCABKAIYIAEoAhgoAmw2AlwgASgCGCgCABAcIAEoAhgoAgAoAhBFBEAgAUEANgIcDAILCyABQQE2AhwLIAEoAhwhAiABQSBqJAAgAgwBCwJ/IAAoAiwoAogBQQNGBEAgACgCLCECIAAoAjQhAyMAQTBrIgEkACABIAI2AiggASADNgIkAkADQAJAIAEoAigoAnRBggJNBEAgASgCKBBbAkAgASgCKCgCdEGCAksNACABKAIkDQAgAUEANgIsDAQLIAEoAigoAnRFDQELIAEoAihBADYCYAJAIAEoAigoAnRBA0kNACABKAIoKAJsRQ0AIAEgASgCKCgCOCABKAIoKAJsakEBazYCGCABIAEoAhgtAAA2AhwgASgCHCECIAEgASgCGCIDQQFqNgIYAkAgAy0AASACRw0AIAEoAhwhAiABIAEoAhgiA0EBajYCGCADLQABIAJHDQAgASgCHCECIAEgASgCGCIDQQFqNgIYIAMtAAEgAkcNACABIAEoAigoAjggASgCKCgCbGpBggJqNgIUA0AgASgCHCECIAEgASgCGCIDQQFqNgIYAn9BACADLQABIAJHDQAaIAEoAhwhAiABIAEoAhgiA0EBajYCGEEAIAMtAAEgAkcNABogASgCHCECIAEgASgCGCIDQQFqNgIYQQAgAy0AASACRw0AGiABKAIcIQIgASABKAIYIgNBAWo2AhhBACADLQABIAJHDQAaIAEoAhwhAiABIAEoAhgiA0EBajYCGEEAIAMtAAEgAkcNABogASgCHCECIAEgASgCGCIDQQFqNgIYQQAgAy0AASACRw0AGiABKAIcIQIgASABKAIYIgNBAWo2AhhBACADLQABIAJHDQAaIAEoAhwhAiABIAEoAhgiA0EBajYCGEEAIAMtAAEgAkcNABogASgCGCABKAIUSQtBAXENAAsgASgCKEGCAiABKAIUIAEoAhhrazYCYCABKAIoKAJgIAEoAigoAnRLBEAgASgCKCABKAIoKAJ0NgJgCwsLAkAgASgCKCgCYEEDTwRAIAEgASgCKCgCYEEDazoAEyABQQE7ARAgASgCKCICKAKkLSACKAKgLUEBdGogAS8BEDsBACABLQATIQMgASgCKCICKAKYLSEEIAIgAigCoC0iAkEBajYCoC0gAiAEaiADOgAAIAEgAS8BEEEBazsBECABKAIoIAEtABNB0N0Aai0AAEECdGpBmAlqIgIgAi8BAEEBajsBACABKAIoQYgTagJ/IAEvARBBgAJJBEAgAS8BEC0A0FkMAQsgAS8BEEEHdkGAAmotANBZC0ECdGoiAiACLwEAQQFqOwEAIAEgASgCKCgCoC0gASgCKCgCnC1BAWtGNgIgIAEoAigiAiACKAJ0IAEoAigoAmBrNgJ0IAEoAigiAiABKAIoKAJgIAIoAmxqNgJsIAEoAihBADYCYAwBCyABIAEoAigiAigCOCACKAJsai0AADoADyABKAIoIgIoAqQtIAIoAqAtQQF0akEAOwEAIAEtAA8hAyABKAIoIgIoApgtIQQgAiACKAKgLSICQQFqNgKgLSACIARqIAM6AAAgASgCKCABLQAPQQJ0aiICIAIvAZQBQQFqOwGUASABIAEoAigoAqAtIAEoAigoApwtQQFrRjYCICABKAIoIgIgAigCdEEBazYCdCABKAIoIgIgAigCbEEBajYCbAsgASgCIARAIAEoAigCfyABKAIoKAJcQQBOBEAgASgCKCgCOCABKAIoKAJcagwBC0EACyABKAIoKAJsIAEoAigoAlxrQQAQKCABKAIoIAEoAigoAmw2AlwgASgCKCgCABAcIAEoAigoAgAoAhBFBEAgAUEANgIsDAQLCwwBCwsgASgCKEEANgK0LSABKAIkQQRGBEAgASgCKAJ/IAEoAigoAlxBAE4EQCABKAIoKAI4IAEoAigoAlxqDAELQQALIAEoAigoAmwgASgCKCgCXGtBARAoIAEoAiggASgCKCgCbDYCXCABKAIoKAIAEBwgASgCKCgCACgCEEUEQCABQQI2AiwMAgsgAUEDNgIsDAELIAEoAigoAqAtBEAgASgCKAJ/IAEoAigoAlxBAE4EQCABKAIoKAI4IAEoAigoAlxqDAELQQALIAEoAigoAmwgASgCKCgCXGtBABAoIAEoAiggASgCKCgCbDYCXCABKAIoKAIAEBwgASgCKCgCACgCEEUEQCABQQA2AiwMAgsLIAFBATYCLAsgASgCLCECIAFBMGokACACDAELIAAoAiwgACgCNCAAKAIsKAKEAUEMbEGA7wBqKAIIEQMACwsLNgIEAkAgACgCBEECRwRAIAAoAgRBA0cNAQsgACgCLEGaBTYCBAsCQCAAKAIEBEAgACgCBEECRw0BCyAAKAI4KAIQRQRAIAAoAixBfzYCKAsgAEEANgI8DAILIAAoAgRBAUYEQAJAIAAoAjRBAUYEQCAAKAIsIQIjAEEgayIBJAAgASACNgIcIAFBAzYCGAJAIAEoAhwoArwtQRAgASgCGGtKBEAgAUECNgIUIAEoAhwiAiACLwG4LSABKAIUQf//A3EgASgCHCgCvC10cjsBuC0gASgCHC8BuC1B/wFxIQMgASgCHCgCCCEEIAEoAhwiBigCFCECIAYgAkEBajYCFCACIARqIAM6AAAgASgCHC8BuC1BCHYhAyABKAIcKAIIIQQgASgCHCIGKAIUIQIgBiACQQFqNgIUIAIgBGogAzoAACABKAIcIAEoAhRB//8DcUEQIAEoAhwoArwta3U7AbgtIAEoAhwiAiACKAK8LSABKAIYQRBrajYCvC0MAQsgASgCHCICIAIvAbgtQQIgASgCHCgCvC10cjsBuC0gASgCHCICIAEoAhggAigCvC1qNgK8LQsgAUGS6AAvAQA2AhACQCABKAIcKAK8LUEQIAEoAhBrSgRAIAFBkOgALwEANgIMIAEoAhwiAiACLwG4LSABKAIMQf//A3EgASgCHCgCvC10cjsBuC0gASgCHC8BuC1B/wFxIQMgASgCHCgCCCEEIAEoAhwiBigCFCECIAYgAkEBajYCFCACIARqIAM6AAAgASgCHC8BuC1BCHYhAyABKAIcKAIIIQQgASgCHCIGKAIUIQIgBiACQQFqNgIUIAIgBGogAzoAACABKAIcIAEoAgxB//8DcUEQIAEoAhwoArwta3U7AbgtIAEoAhwiAiACKAK8LSABKAIQQRBrajYCvC0MAQsgASgCHCICIAIvAbgtQZDoAC8BACABKAIcKAK8LXRyOwG4LSABKAIcIgIgASgCECACKAK8LWo2ArwtCyABKAIcELsBIAFBIGokAAwBCyAAKAI0QQVHBEAgACgCLEEAQQBBABBcIAAoAjRBA0YEQCAAKAIsKAJEIAAoAiwoAkxBAWtBAXRqQQA7AQAgACgCLCgCREEAIAAoAiwoAkxBAWtBAXQQMiAAKAIsKAJ0RQRAIAAoAixBADYCbCAAKAIsQQA2AlwgACgCLEEANgK0LQsLCwsgACgCOBAcIAAoAjgoAhBFBEAgACgCLEF/NgIoIABBADYCPAwDCwsLIAAoAjRBBEcEQCAAQQA2AjwMAQsgACgCLCgCGEEATARAIABBATYCPAwBCwJAIAAoAiwoAhhBAkYEQCAAKAI4KAIwQf8BcSECIAAoAiwoAgghAyAAKAIsIgQoAhQhASAEIAFBAWo2AhQgASADaiACOgAAIAAoAjgoAjBBCHZB/wFxIQIgACgCLCgCCCEDIAAoAiwiBCgCFCEBIAQgAUEBajYCFCABIANqIAI6AAAgACgCOCgCMEEQdkH/AXEhAiAAKAIsKAIIIQMgACgCLCIEKAIUIQEgBCABQQFqNgIUIAEgA2ogAjoAACAAKAI4KAIwQRh2IQIgACgCLCgCCCEDIAAoAiwiBCgCFCEBIAQgAUEBajYCFCABIANqIAI6AAAgACgCOCgCCEH/AXEhAiAAKAIsKAIIIQMgACgCLCIEKAIUIQEgBCABQQFqNgIUIAEgA2ogAjoAACAAKAI4KAIIQQh2Qf8BcSECIAAoAiwoAgghAyAAKAIsIgQoAhQhASAEIAFBAWo2AhQgASADaiACOgAAIAAoAjgoAghBEHZB/wFxIQIgACgCLCgCCCEDIAAoAiwiBCgCFCEBIAQgAUEBajYCFCABIANqIAI6AAAgACgCOCgCCEEYdiECIAAoAiwoAgghAyAAKAIsIgQoAhQhASAEIAFBAWo2AhQgASADaiACOgAADAELIAAoAiwgACgCOCgCMEEQdhBMIAAoAiwgACgCOCgCMEH//wNxEEwLIAAoAjgQHCAAKAIsKAIYQQBKBEAgACgCLEEAIAAoAiwoAhhrNgIYCyAAIAAoAiwoAhRFNgI8CyAAKAI8IQEgAEFAayQAIAUgATYCCAwBCyAFKAIMQRBqIQEjAEHgAGsiACQAIAAgATYCWCAAQQI2AlQCQAJAAkAgACgCWBBLDQAgACgCWCgCDEUNACAAKAJYKAIADQEgACgCWCgCBEUNAQsgAEF+NgJcDAELIAAgACgCWCgCHDYCUCAAKAJQKAIEQb/+AEYEQCAAKAJQQcD+ADYCBAsgACAAKAJYKAIMNgJIIAAgACgCWCgCEDYCQCAAIAAoAlgoAgA2AkwgACAAKAJYKAIENgJEIAAgACgCUCgCPDYCPCAAIAAoAlAoAkA2AjggACAAKAJENgI0IAAgACgCQDYCMCAAQQA2AhADQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAAKAJQKAIEQbT+AGsOHwABAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fCyAAKAJQKAIMRQRAIAAoAlBBwP4ANgIEDCELA0AgACgCOEEQSQRAIAAoAkRFDSEgACAAKAJEQQFrNgJEIAAgACgCTCIBQQFqNgJMIAAgACgCPCABLQAAIAAoAjh0ajYCPCAAIAAoAjhBCGo2AjgMAQsLAkAgACgCUCgCDEECcUUNACAAKAI8QZ+WAkcNACAAKAJQKAIoRQRAIAAoAlBBDzYCKAtBAEEAQQAQGiEBIAAoAlAgATYCHCAAIAAoAjw6AAwgACAAKAI8QQh2OgANIAAoAlAoAhwgAEEMakECEBohASAAKAJQIAE2AhwgAEEANgI8IABBADYCOCAAKAJQQbX+ADYCBAwhCyAAKAJQQQA2AhQgACgCUCgCJARAIAAoAlAoAiRBfzYCMAsCQCAAKAJQKAIMQQFxBEAgACgCPEH/AXFBCHQgACgCPEEIdmpBH3BFDQELIAAoAlhBmgw2AhggACgCUEHR/gA2AgQMIQsgACgCPEEPcUEIRwRAIAAoAlhBmw82AhggACgCUEHR/gA2AgQMIQsgACAAKAI8QQR2NgI8IAAgACgCOEEEazYCOCAAIAAoAjxBD3FBCGo2AhQgACgCUCgCKEUEQCAAKAJQIAAoAhQ2AigLAkAgACgCFEEPTQRAIAAoAhQgACgCUCgCKE0NAQsgACgCWEGTDTYCGCAAKAJQQdH+ADYCBAwhCyAAKAJQQQEgACgCFHQ2AhhBAEEAQQAQPiEBIAAoAlAgATYCHCAAKAJYIAE2AjAgACgCUEG9/gBBv/4AIAAoAjxBgARxGzYCBCAAQQA2AjwgAEEANgI4DCALA0AgACgCOEEQSQRAIAAoAkRFDSAgACAAKAJEQQFrNgJEIAAgACgCTCIBQQFqNgJMIAAgACgCPCABLQAAIAAoAjh0ajYCPCAAIAAoAjhBCGo2AjgMAQsLIAAoAlAgACgCPDYCFCAAKAJQKAIUQf8BcUEIRwRAIAAoAlhBmw82AhggACgCUEHR/gA2AgQMIAsgACgCUCgCFEGAwANxBEAgACgCWEGgCTYCGCAAKAJQQdH+ADYCBAwgCyAAKAJQKAIkBEAgACgCUCgCJCAAKAI8QQh2QQFxNgIACwJAIAAoAlAoAhRBgARxRQ0AIAAoAlAoAgxBBHFFDQAgACAAKAI8OgAMIAAgACgCPEEIdjoADSAAKAJQKAIcIABBDGpBAhAaIQEgACgCUCABNgIcCyAAQQA2AjwgAEEANgI4IAAoAlBBtv4ANgIECwNAIAAoAjhBIEkEQCAAKAJERQ0fIAAgACgCREEBazYCRCAAIAAoAkwiAUEBajYCTCAAIAAoAjwgAS0AACAAKAI4dGo2AjwgACAAKAI4QQhqNgI4DAELCyAAKAJQKAIkBEAgACgCUCgCJCAAKAI8NgIECwJAIAAoAlAoAhRBgARxRQ0AIAAoAlAoAgxBBHFFDQAgACAAKAI8OgAMIAAgACgCPEEIdjoADSAAIAAoAjxBEHY6AA4gACAAKAI8QRh2OgAPIAAoAlAoAhwgAEEMakEEEBohASAAKAJQIAE2AhwLIABBADYCPCAAQQA2AjggACgCUEG3/gA2AgQLA0AgACgCOEEQSQRAIAAoAkRFDR4gACAAKAJEQQFrNgJEIAAgACgCTCIBQQFqNgJMIAAgACgCPCABLQAAIAAoAjh0ajYCPCAAIAAoAjhBCGo2AjgMAQsLIAAoAlAoAiQEQCAAKAJQKAIkIAAoAjxB/wFxNgIIIAAoAlAoAiQgACgCPEEIdjYCDAsCQCAAKAJQKAIUQYAEcUUNACAAKAJQKAIMQQRxRQ0AIAAgACgCPDoADCAAIAAoAjxBCHY6AA0gACgCUCgCHCAAQQxqQQIQGiEBIAAoAlAgATYCHAsgAEEANgI8IABBADYCOCAAKAJQQbj+ADYCBAsCQCAAKAJQKAIUQYAIcQRAA0AgACgCOEEQSQRAIAAoAkRFDR8gACAAKAJEQQFrNgJEIAAgACgCTCIBQQFqNgJMIAAgACgCPCABLQAAIAAoAjh0ajYCPCAAIAAoAjhBCGo2AjgMAQsLIAAoAlAgACgCPDYCRCAAKAJQKAIkBEAgACgCUCgCJCAAKAI8NgIUCwJAIAAoAlAoAhRBgARxRQ0AIAAoAlAoAgxBBHFFDQAgACAAKAI8OgAMIAAgACgCPEEIdjoADSAAKAJQKAIcIABBDGpBAhAaIQEgACgCUCABNgIcCyAAQQA2AjwgAEEANgI4DAELIAAoAlAoAiQEQCAAKAJQKAIkQQA2AhALCyAAKAJQQbn+ADYCBAsgACgCUCgCFEGACHEEQCAAIAAoAlAoAkQ2AiwgACgCLCAAKAJESwRAIAAgACgCRDYCLAsgACgCLARAAkAgACgCUCgCJEUNACAAKAJQKAIkKAIQRQ0AIAAgACgCUCgCJCgCFCAAKAJQKAJEazYCFCAAKAJQKAIkKAIQIAAoAhRqIAAoAkwCfyAAKAJQKAIkKAIYIAAoAhQgACgCLGpJBEAgACgCUCgCJCgCGCAAKAIUawwBCyAAKAIsCxAZGgsCQCAAKAJQKAIUQYAEcUUNACAAKAJQKAIMQQRxRQ0AIAAoAlAoAhwgACgCTCAAKAIsEBohASAAKAJQIAE2AhwLIAAgACgCRCAAKAIsazYCRCAAIAAoAiwgACgCTGo2AkwgACgCUCIBIAEoAkQgACgCLGs2AkQLIAAoAlAoAkQNGwsgACgCUEEANgJEIAAoAlBBuv4ANgIECwJAIAAoAlAoAhRBgBBxBEAgACgCREUNGyAAQQA2AiwDQCAAKAJMIQEgACAAKAIsIgJBAWo2AiwgACABIAJqLQAANgIUAkAgACgCUCgCJEUNACAAKAJQKAIkKAIcRQ0AIAAoAlAoAkQgACgCUCgCJCgCIE8NACAAKAIUIQIgACgCUCgCJCgCHCEDIAAoAlAiBCgCRCEBIAQgAUEBajYCRCABIANqIAI6AAALIAAoAhQEfyAAKAIsIAAoAkRJBUEAC0EBcQ0ACwJAIAAoAlAoAhRBgARxRQ0AIAAoAlAoAgxBBHFFDQAgACgCUCgCHCAAKAJMIAAoAiwQGiEBIAAoAlAgATYCHAsgACAAKAJEIAAoAixrNgJEIAAgACgCLCAAKAJMajYCTCAAKAIUDRsMAQsgACgCUCgCJARAIAAoAlAoAiRBADYCHAsLIAAoAlBBADYCRCAAKAJQQbv+ADYCBAsCQCAAKAJQKAIUQYAgcQRAIAAoAkRFDRogAEEANgIsA0AgACgCTCEBIAAgACgCLCICQQFqNgIsIAAgASACai0AADYCFAJAIAAoAlAoAiRFDQAgACgCUCgCJCgCJEUNACAAKAJQKAJEIAAoAlAoAiQoAihPDQAgACgCFCECIAAoAlAoAiQoAiQhAyAAKAJQIgQoAkQhASAEIAFBAWo2AkQgASADaiACOgAACyAAKAIUBH8gACgCLCAAKAJESQVBAAtBAXENAAsCQCAAKAJQKAIUQYAEcUUNACAAKAJQKAIMQQRxRQ0AIAAoAlAoAhwgACgCTCAAKAIsEBohASAAKAJQIAE2AhwLIAAgACgCRCAAKAIsazYCRCAAIAAoAiwgACgCTGo2AkwgACgCFA0aDAELIAAoAlAoAiQEQCAAKAJQKAIkQQA2AiQLCyAAKAJQQbz+ADYCBAsgACgCUCgCFEGABHEEQANAIAAoAjhBEEkEQCAAKAJERQ0aIAAgACgCREEBazYCRCAAIAAoAkwiAUEBajYCTCAAIAAoAjwgAS0AACAAKAI4dGo2AjwgACAAKAI4QQhqNgI4DAELCwJAIAAoAlAoAgxBBHFFDQAgACgCPCAAKAJQKAIcQf//A3FGDQAgACgCWEH7DDYCGCAAKAJQQdH+ADYCBAwaCyAAQQA2AjwgAEEANgI4CyAAKAJQKAIkBEAgACgCUCgCJCAAKAJQKAIUQQl1QQFxNgIsIAAoAlAoAiRBATYCMAtBAEEAQQAQGiEBIAAoAlAgATYCHCAAKAJYIAE2AjAgACgCUEG//gA2AgQMGAsDQCAAKAI4QSBJBEAgACgCREUNGCAAIAAoAkRBAWs2AkQgACAAKAJMIgFBAWo2AkwgACAAKAI8IAEtAAAgACgCOHRqNgI8IAAgACgCOEEIajYCOAwBCwsgACgCUCAAKAI8QQh2QYD+A3EgACgCPEEYdmogACgCPEGA/gNxQQh0aiAAKAI8Qf8BcUEYdGoiATYCHCAAKAJYIAE2AjAgAEEANgI8IABBADYCOCAAKAJQQb7+ADYCBAsgACgCUCgCEEUEQCAAKAJYIAAoAkg2AgwgACgCWCAAKAJANgIQIAAoAlggACgCTDYCACAAKAJYIAAoAkQ2AgQgACgCUCAAKAI8NgI8IAAoAlAgACgCODYCQCAAQQI2AlwMGAtBAEEAQQAQPiEBIAAoAlAgATYCHCAAKAJYIAE2AjAgACgCUEG//gA2AgQLIAAoAlRBBUYNFCAAKAJUQQZGDRQLIAAoAlAoAggEQCAAIAAoAjwgACgCOEEHcXY2AjwgACAAKAI4IAAoAjhBB3FrNgI4IAAoAlBBzv4ANgIEDBULA0AgACgCOEEDSQRAIAAoAkRFDRUgACAAKAJEQQFrNgJEIAAgACgCTCIBQQFqNgJMIAAgACgCPCABLQAAIAAoAjh0ajYCPCAAIAAoAjhBCGo2AjgMAQsLIAAoAlAgACgCPEEBcTYCCCAAIAAoAjxBAXY2AjwgACAAKAI4QQFrNgI4AkACQAJAAkACQCAAKAI8QQNxDgQAAQIDBAsgACgCUEHB/gA2AgQMAwsjAEEQayIBIAAoAlA2AgwgASgCDEGw8gA2AlAgASgCDEEJNgJYIAEoAgxBsIIBNgJUIAEoAgxBBTYCXCAAKAJQQcf+ADYCBCAAKAJUQQZGBEAgACAAKAI8QQJ2NgI8IAAgACgCOEECazYCOAwXCwwCCyAAKAJQQcT+ADYCBAwBCyAAKAJYQfANNgIYIAAoAlBB0f4ANgIECyAAIAAoAjxBAnY2AjwgACAAKAI4QQJrNgI4DBQLIAAgACgCPCAAKAI4QQdxdjYCPCAAIAAoAjggACgCOEEHcWs2AjgDQCAAKAI4QSBJBEAgACgCREUNFCAAIAAoAkRBAWs2AkQgACAAKAJMIgFBAWo2AkwgACAAKAI8IAEtAAAgACgCOHRqNgI8IAAgACgCOEEIajYCOAwBCwsgACgCPEH//wNxIAAoAjxBEHZB//8Dc0cEQCAAKAJYQaEKNgIYIAAoAlBB0f4ANgIEDBQLIAAoAlAgACgCPEH//wNxNgJEIABBADYCPCAAQQA2AjggACgCUEHC/gA2AgQgACgCVEEGRg0SCyAAKAJQQcP+ADYCBAsgACAAKAJQKAJENgIsIAAoAiwEQCAAKAIsIAAoAkRLBEAgACAAKAJENgIsCyAAKAIsIAAoAkBLBEAgACAAKAJANgIsCyAAKAIsRQ0RIAAoAkggACgCTCAAKAIsEBkaIAAgACgCRCAAKAIsazYCRCAAIAAoAiwgACgCTGo2AkwgACAAKAJAIAAoAixrNgJAIAAgACgCLCAAKAJIajYCSCAAKAJQIgEgASgCRCAAKAIsazYCRAwSCyAAKAJQQb/+ADYCBAwRCwNAIAAoAjhBDkkEQCAAKAJERQ0RIAAgACgCREEBazYCRCAAIAAoAkwiAUEBajYCTCAAIAAoAjwgAS0AACAAKAI4dGo2AjwgACAAKAI4QQhqNgI4DAELCyAAKAJQIAAoAjxBH3FBgQJqNgJkIAAgACgCPEEFdjYCPCAAIAAoAjhBBWs2AjggACgCUCAAKAI8QR9xQQFqNgJoIAAgACgCPEEFdjYCPCAAIAAoAjhBBWs2AjggACgCUCAAKAI8QQ9xQQRqNgJgIAAgACgCPEEEdjYCPCAAIAAoAjhBBGs2AjgCQCAAKAJQKAJkQZ4CTQRAIAAoAlAoAmhBHk0NAQsgACgCWEH9CTYCGCAAKAJQQdH+ADYCBAwRCyAAKAJQQQA2AmwgACgCUEHF/gA2AgQLA0AgACgCUCgCbCAAKAJQKAJgSQRAA0AgACgCOEEDSQRAIAAoAkRFDRIgACAAKAJEQQFrNgJEIAAgACgCTCIBQQFqNgJMIAAgACgCPCABLQAAIAAoAjh0ajYCPCAAIAAoAjhBCGo2AjgMAQsLIAAoAjxBB3EhAiAAKAJQQfQAaiEDIAAoAlAiBCgCbCEBIAQgAUEBajYCbCABQQF0QYDyAGovAQBBAXQgA2ogAjsBACAAIAAoAjxBA3Y2AjwgACAAKAI4QQNrNgI4DAELCwNAIAAoAlAoAmxBE0kEQCAAKAJQQfQAaiECIAAoAlAiAygCbCEBIAMgAUEBajYCbCABQQF0QYDyAGovAQBBAXQgAmpBADsBAAwBCwsgACgCUCAAKAJQQbQKajYCcCAAKAJQIAAoAlAoAnA2AlAgACgCUEEHNgJYIABBACAAKAJQQfQAakETIAAoAlBB8ABqIAAoAlBB2ABqIAAoAlBB9AVqEHc2AhAgACgCEARAIAAoAlhBhwk2AhggACgCUEHR/gA2AgQMEAsgACgCUEEANgJsIAAoAlBBxv4ANgIECwNAAkAgACgCUCgCbCAAKAJQKAJkIAAoAlAoAmhqTw0AA0ACQCAAIAAoAlAoAlAgACgCPEEBIAAoAlAoAlh0QQFrcUECdGooAQA2ASAgAC0AISAAKAI4TQ0AIAAoAkRFDREgACAAKAJEQQFrNgJEIAAgACgCTCIBQQFqNgJMIAAgACgCPCABLQAAIAAoAjh0ajYCPCAAIAAoAjhBCGo2AjgMAQsLAkAgAC8BIkEQSQRAIAAgACgCPCAALQAhdjYCPCAAIAAoAjggAC0AIWs2AjggAC8BIiECIAAoAlBB9ABqIQMgACgCUCIEKAJsIQEgBCABQQFqNgJsIAFBAXQgA2ogAjsBAAwBCwJAIAAvASJBEEYEQANAIAAoAjggAC0AIUECakkEQCAAKAJERQ0UIAAgACgCREEBazYCRCAAIAAoAkwiAUEBajYCTCAAIAAoAjwgAS0AACAAKAI4dGo2AjwgACAAKAI4QQhqNgI4DAELCyAAIAAoAjwgAC0AIXY2AjwgACAAKAI4IAAtACFrNgI4IAAoAlAoAmxFBEAgACgCWEHPCTYCGCAAKAJQQdH+ADYCBAwECyAAIAAoAlAgACgCUCgCbEEBdGovAXI2AhQgACAAKAI8QQNxQQNqNgIsIAAgACgCPEECdjYCPCAAIAAoAjhBAms2AjgMAQsCQCAALwEiQRFGBEADQCAAKAI4IAAtACFBA2pJBEAgACgCREUNFSAAIAAoAkRBAWs2AkQgACAAKAJMIgFBAWo2AkwgACAAKAI8IAEtAAAgACgCOHRqNgI8IAAgACgCOEEIajYCOAwBCwsgACAAKAI8IAAtACF2NgI8IAAgACgCOCAALQAhazYCOCAAQQA2AhQgACAAKAI8QQdxQQNqNgIsIAAgACgCPEEDdjYCPCAAIAAoAjhBA2s2AjgMAQsDQCAAKAI4IAAtACFBB2pJBEAgACgCREUNFCAAIAAoAkRBAWs2AkQgACAAKAJMIgFBAWo2AkwgACAAKAI8IAEtAAAgACgCOHRqNgI8IAAgACgCOEEIajYCOAwBCwsgACAAKAI8IAAtACF2NgI8IAAgACgCOCAALQAhazYCOCAAQQA2AhQgACAAKAI8Qf8AcUELajYCLCAAIAAoAjxBB3Y2AjwgACAAKAI4QQdrNgI4CwsgACgCUCgCbCAAKAIsaiAAKAJQKAJkIAAoAlAoAmhqSwRAIAAoAlhBzwk2AhggACgCUEHR/gA2AgQMAgsDQCAAIAAoAiwiAUEBazYCLCABBEAgACgCFCECIAAoAlBB9ABqIQMgACgCUCIEKAJsIQEgBCABQQFqNgJsIAFBAXQgA2ogAjsBAAwBCwsLDAELCyAAKAJQKAIEQdH+AEYNDiAAKAJQLwH0BEUEQCAAKAJYQfULNgIYIAAoAlBB0f4ANgIEDA8LIAAoAlAgACgCUEG0Cmo2AnAgACgCUCAAKAJQKAJwNgJQIAAoAlBBCTYCWCAAQQEgACgCUEH0AGogACgCUCgCZCAAKAJQQfAAaiAAKAJQQdgAaiAAKAJQQfQFahB3NgIQIAAoAhAEQCAAKAJYQesINgIYIAAoAlBB0f4ANgIEDA8LIAAoAlAgACgCUCgCcDYCVCAAKAJQQQY2AlwgAEECIAAoAlBB9ABqIAAoAlAoAmRBAXRqIAAoAlAoAmggACgCUEHwAGogACgCUEHcAGogACgCUEH0BWoQdzYCECAAKAIQBEAgACgCWEG5CTYCGCAAKAJQQdH+ADYCBAwPCyAAKAJQQcf+ADYCBCAAKAJUQQZGDQ0LIAAoAlBByP4ANgIECwJAIAAoAkRBBkkNACAAKAJAQYICSQ0AIAAoAlggACgCSDYCDCAAKAJYIAAoAkA2AhAgACgCWCAAKAJMNgIAIAAoAlggACgCRDYCBCAAKAJQIAAoAjw2AjwgACgCUCAAKAI4NgJAIAAoAjAhAiMAQeAAayIBIAAoAlg2AlwgASACNgJYIAEgASgCXCgCHDYCVCABIAEoAlwoAgA2AlAgASABKAJQIAEoAlwoAgRBBWtqNgJMIAEgASgCXCgCDDYCSCABIAEoAkggASgCWCABKAJcKAIQa2s2AkQgASABKAJIIAEoAlwoAhBBgQJrajYCQCABIAEoAlQoAiw2AjwgASABKAJUKAIwNgI4IAEgASgCVCgCNDYCNCABIAEoAlQoAjg2AjAgASABKAJUKAI8NgIsIAEgASgCVCgCQDYCKCABIAEoAlQoAlA2AiQgASABKAJUKAJUNgIgIAFBASABKAJUKAJYdEEBazYCHCABQQEgASgCVCgCXHRBAWs2AhgDQCABKAIoQQ9JBEAgASABKAJQIgJBAWo2AlAgASABKAIsIAItAAAgASgCKHRqNgIsIAEgASgCKEEIajYCKCABIAEoAlAiAkEBajYCUCABIAEoAiwgAi0AACABKAIodGo2AiwgASABKAIoQQhqNgIoCyABIAEoAiQgASgCLCABKAIccUECdGooAQA2ARACQAJAA0AgASABLQARNgIMIAEgASgCLCABKAIMdjYCLCABIAEoAiggASgCDGs2AiggASABLQAQNgIMIAEoAgxFBEAgAS8BEiECIAEgASgCSCIDQQFqNgJIIAMgAjoAAAwCCyABKAIMQRBxBEAgASABLwESNgIIIAEgASgCDEEPcTYCDCABKAIMBEAgASgCKCABKAIMSQRAIAEgASgCUCICQQFqNgJQIAEgASgCLCACLQAAIAEoAih0ajYCLCABIAEoAihBCGo2AigLIAEgASgCCCABKAIsQQEgASgCDHRBAWtxajYCCCABIAEoAiwgASgCDHY2AiwgASABKAIoIAEoAgxrNgIoCyABKAIoQQ9JBEAgASABKAJQIgJBAWo2AlAgASABKAIsIAItAAAgASgCKHRqNgIsIAEgASgCKEEIajYCKCABIAEoAlAiAkEBajYCUCABIAEoAiwgAi0AACABKAIodGo2AiwgASABKAIoQQhqNgIoCyABIAEoAiAgASgCLCABKAIYcUECdGooAQA2ARACQANAIAEgAS0AETYCDCABIAEoAiwgASgCDHY2AiwgASABKAIoIAEoAgxrNgIoIAEgAS0AEDYCDCABKAIMQRBxBEAgASABLwESNgIEIAEgASgCDEEPcTYCDCABKAIoIAEoAgxJBEAgASABKAJQIgJBAWo2AlAgASABKAIsIAItAAAgASgCKHRqNgIsIAEgASgCKEEIajYCKCABKAIoIAEoAgxJBEAgASABKAJQIgJBAWo2AlAgASABKAIsIAItAAAgASgCKHRqNgIsIAEgASgCKEEIajYCKAsLIAEgASgCBCABKAIsQQEgASgCDHRBAWtxajYCBCABIAEoAiwgASgCDHY2AiwgASABKAIoIAEoAgxrNgIoIAEgASgCSCABKAJEazYCDAJAIAEoAgQgASgCDEsEQCABIAEoAgQgASgCDGs2AgwgASgCDCABKAI4SwRAIAEoAlQoAsQ3BEAgASgCXEHdDDYCGCABKAJUQdH+ADYCBAwKCwsgASABKAIwNgIAAkAgASgCNEUEQCABIAEoAgAgASgCPCABKAIMa2o2AgAgASgCDCABKAIISQRAIAEgASgCCCABKAIMazYCCANAIAEgASgCACICQQFqNgIAIAItAAAhAiABIAEoAkgiA0EBajYCSCADIAI6AAAgASABKAIMQQFrIgI2AgwgAg0ACyABIAEoAkggASgCBGs2AgALDAELAkAgASgCNCABKAIMSQRAIAEgASgCACABKAI8IAEoAjRqIAEoAgxrajYCACABIAEoAgwgASgCNGs2AgwgASgCDCABKAIISQRAIAEgASgCCCABKAIMazYCCANAIAEgASgCACICQQFqNgIAIAItAAAhAiABIAEoAkgiA0EBajYCSCADIAI6AAAgASABKAIMQQFrIgI2AgwgAg0ACyABIAEoAjA2AgAgASgCNCABKAIISQRAIAEgASgCNDYCDCABIAEoAgggASgCDGs2AggDQCABIAEoAgAiAkEBajYCACACLQAAIQIgASABKAJIIgNBAWo2AkggAyACOgAAIAEgASgCDEEBayICNgIMIAINAAsgASABKAJIIAEoAgRrNgIACwsMAQsgASABKAIAIAEoAjQgASgCDGtqNgIAIAEoAgwgASgCCEkEQCABIAEoAgggASgCDGs2AggDQCABIAEoAgAiAkEBajYCACACLQAAIQIgASABKAJIIgNBAWo2AkggAyACOgAAIAEgASgCDEEBayICNgIMIAINAAsgASABKAJIIAEoAgRrNgIACwsLA0AgASgCCEECSwRAIAEgASgCACICQQFqNgIAIAItAAAhAiABIAEoAkgiA0EBajYCSCADIAI6AAAgASABKAIAIgJBAWo2AgAgAi0AACECIAEgASgCSCIDQQFqNgJIIAMgAjoAACABIAEoAgAiAkEBajYCACACLQAAIQIgASABKAJIIgNBAWo2AkggAyACOgAAIAEgASgCCEEDazYCCAwBCwsMAQsgASABKAJIIAEoAgRrNgIAA0AgASABKAIAIgJBAWo2AgAgAi0AACECIAEgASgCSCIDQQFqNgJIIAMgAjoAACABIAEoAgAiAkEBajYCACACLQAAIQIgASABKAJIIgNBAWo2AkggAyACOgAAIAEgASgCACICQQFqNgIAIAItAAAhAiABIAEoAkgiA0EBajYCSCADIAI6AAAgASABKAIIQQNrNgIIIAEoAghBAksNAAsLIAEoAggEQCABIAEoAgAiAkEBajYCACACLQAAIQIgASABKAJIIgNBAWo2AkggAyACOgAAIAEoAghBAUsEQCABIAEoAgAiAkEBajYCACACLQAAIQIgASABKAJIIgNBAWo2AkggAyACOgAACwsMAgsgASgCDEHAAHFFBEAgASABKAIgIAEvARIgASgCLEEBIAEoAgx0QQFrcWpBAnRqKAEANgEQDAELCyABKAJcQYUPNgIYIAEoAlRB0f4ANgIEDAQLDAILIAEoAgxBwABxRQRAIAEgASgCJCABLwESIAEoAixBASABKAIMdEEBa3FqQQJ0aigBADYBEAwBCwsgASgCDEEgcQRAIAEoAlRBv/4ANgIEDAILIAEoAlxB6Q42AhggASgCVEHR/gA2AgQMAQsgASgCUCABKAJMSQR/IAEoAkggASgCQEkFQQALQQFxDQELCyABIAEoAihBA3Y2AgggASABKAJQIAEoAghrNgJQIAEgASgCKCABKAIIQQN0azYCKCABIAEoAixBASABKAIodEEBa3E2AiwgASgCXCABKAJQNgIAIAEoAlwgASgCSDYCDCABKAJcAn8gASgCUCABKAJMSQRAIAEoAkwgASgCUGtBBWoMAQtBBSABKAJQIAEoAkxraws2AgQgASgCXAJ/IAEoAkggASgCQEkEQCABKAJAIAEoAkhrQYECagwBC0GBAiABKAJIIAEoAkBraws2AhAgASgCVCABKAIsNgI8IAEoAlQgASgCKDYCQCAAIAAoAlgoAgw2AkggACAAKAJYKAIQNgJAIAAgACgCWCgCADYCTCAAIAAoAlgoAgQ2AkQgACAAKAJQKAI8NgI8IAAgACgCUCgCQDYCOCAAKAJQKAIEQb/+AEYEQCAAKAJQQX82Asg3CwwNCyAAKAJQQQA2Asg3A0ACQCAAIAAoAlAoAlAgACgCPEEBIAAoAlAoAlh0QQFrcUECdGooAQA2ASAgAC0AISAAKAI4TQ0AIAAoAkRFDQ0gACAAKAJEQQFrNgJEIAAgACgCTCIBQQFqNgJMIAAgACgCPCABLQAAIAAoAjh0ajYCPCAAIAAoAjhBCGo2AjgMAQsLAkAgAC0AIEUNACAALQAgQfABcQ0AIAAgACgBIDYBGANAAkAgACAAKAJQKAJQIAAvARogACgCPEEBIAAtABkgAC0AGGp0QQFrcSAALQAZdmpBAnRqKAEANgEgIAAoAjggAC0AGSAALQAhak8NACAAKAJERQ0OIAAgACgCREEBazYCRCAAIAAoAkwiAUEBajYCTCAAIAAoAjwgAS0AACAAKAI4dGo2AjwgACAAKAI4QQhqNgI4DAELCyAAIAAoAjwgAC0AGXY2AjwgACAAKAI4IAAtABlrNgI4IAAoAlAiASAALQAZIAEoAsg3ajYCyDcLIAAgACgCPCAALQAhdjYCPCAAIAAoAjggAC0AIWs2AjggACgCUCIBIAAtACEgASgCyDdqNgLINyAAKAJQIAAvASI2AkQgAC0AIEUEQCAAKAJQQc3+ADYCBAwNCyAALQAgQSBxBEAgACgCUEF/NgLINyAAKAJQQb/+ADYCBAwNCyAALQAgQcAAcQRAIAAoAlhB6Q42AhggACgCUEHR/gA2AgQMDQsgACgCUCAALQAgQQ9xNgJMIAAoAlBByf4ANgIECyAAKAJQKAJMBEADQCAAKAI4IAAoAlAoAkxJBEAgACgCREUNDSAAIAAoAkRBAWs2AkQgACAAKAJMIgFBAWo2AkwgACAAKAI8IAEtAAAgACgCOHRqNgI8IAAgACgCOEEIajYCOAwBCwsgACgCUCIBIAEoAkQgACgCPEEBIAAoAlAoAkx0QQFrcWo2AkQgACAAKAI8IAAoAlAoAkx2NgI8IAAgACgCOCAAKAJQKAJMazYCOCAAKAJQIgEgACgCUCgCTCABKALIN2o2Asg3CyAAKAJQIAAoAlAoAkQ2Asw3IAAoAlBByv4ANgIECwNAAkAgACAAKAJQKAJUIAAoAjxBASAAKAJQKAJcdEEBa3FBAnRqKAEANgEgIAAtACEgACgCOE0NACAAKAJERQ0LIAAgACgCREEBazYCRCAAIAAoAkwiAUEBajYCTCAAIAAoAjwgAS0AACAAKAI4dGo2AjwgACAAKAI4QQhqNgI4DAELCyAALQAgQfABcUUEQCAAIAAoASA2ARgDQAJAIAAgACgCUCgCVCAALwEaIAAoAjxBASAALQAZIAAtABhqdEEBa3EgAC0AGXZqQQJ0aigBADYBICAAKAI4IAAtABkgAC0AIWpPDQAgACgCREUNDCAAIAAoAkRBAWs2AkQgACAAKAJMIgFBAWo2AkwgACAAKAI8IAEtAAAgACgCOHRqNgI8IAAgACgCOEEIajYCOAwBCwsgACAAKAI8IAAtABl2NgI8IAAgACgCOCAALQAZazYCOCAAKAJQIgEgAC0AGSABKALIN2o2Asg3CyAAIAAoAjwgAC0AIXY2AjwgACAAKAI4IAAtACFrNgI4IAAoAlAiASAALQAhIAEoAsg3ajYCyDcgAC0AIEHAAHEEQCAAKAJYQYUPNgIYIAAoAlBB0f4ANgIEDAsLIAAoAlAgAC8BIjYCSCAAKAJQIAAtACBBD3E2AkwgACgCUEHL/gA2AgQLIAAoAlAoAkwEQANAIAAoAjggACgCUCgCTEkEQCAAKAJERQ0LIAAgACgCREEBazYCRCAAIAAoAkwiAUEBajYCTCAAIAAoAjwgAS0AACAAKAI4dGo2AjwgACAAKAI4QQhqNgI4DAELCyAAKAJQIgEgASgCSCAAKAI8QQEgACgCUCgCTHRBAWtxajYCSCAAIAAoAjwgACgCUCgCTHY2AjwgACAAKAI4IAAoAlAoAkxrNgI4IAAoAlAiASAAKAJQKAJMIAEoAsg3ajYCyDcLIAAoAlBBzP4ANgIECyAAKAJARQ0HIAAgACgCMCAAKAJAazYCLAJAIAAoAlAoAkggACgCLEsEQCAAIAAoAlAoAkggACgCLGs2AiwgACgCLCAAKAJQKAIwSwRAIAAoAlAoAsQ3BEAgACgCWEHdDDYCGCAAKAJQQdH+ADYCBAwMCwsCQCAAKAIsIAAoAlAoAjRLBEAgACAAKAIsIAAoAlAoAjRrNgIsIAAgACgCUCgCOCAAKAJQKAIsIAAoAixrajYCKAwBCyAAIAAoAlAoAjggACgCUCgCNCAAKAIsa2o2AigLIAAoAiwgACgCUCgCREsEQCAAIAAoAlAoAkQ2AiwLDAELIAAgACgCSCAAKAJQKAJIazYCKCAAIAAoAlAoAkQ2AiwLIAAoAiwgACgCQEsEQCAAIAAoAkA2AiwLIAAgACgCQCAAKAIsazYCQCAAKAJQIgEgASgCRCAAKAIsazYCRANAIAAgACgCKCIBQQFqNgIoIAEtAAAhASAAIAAoAkgiAkEBajYCSCACIAE6AAAgACAAKAIsQQFrIgE2AiwgAQ0ACyAAKAJQKAJERQRAIAAoAlBByP4ANgIECwwICyAAKAJARQ0GIAAoAlAoAkQhASAAIAAoAkgiAkEBajYCSCACIAE6AAAgACAAKAJAQQFrNgJAIAAoAlBByP4ANgIEDAcLIAAoAlAoAgwEQANAIAAoAjhBIEkEQCAAKAJERQ0IIAAgACgCREEBazYCRCAAIAAoAkwiAUEBajYCTCAAIAAoAjwgAS0AACAAKAI4dGo2AjwgACAAKAI4QQhqNgI4DAELCyAAIAAoAjAgACgCQGs2AjAgACgCWCIBIAAoAjAgASgCFGo2AhQgACgCUCIBIAAoAjAgASgCIGo2AiACQCAAKAJQKAIMQQRxRQ0AIAAoAjBFDQACfyAAKAJQKAIUBEAgACgCUCgCHCAAKAJIIAAoAjBrIAAoAjAQGgwBCyAAKAJQKAIcIAAoAkggACgCMGsgACgCMBA+CyEBIAAoAlAgATYCHCAAKAJYIAE2AjALIAAgACgCQDYCMAJAIAAoAlAoAgxBBHFFDQACfyAAKAJQKAIUBEAgACgCPAwBCyAAKAI8QQh2QYD+A3EgACgCPEEYdmogACgCPEGA/gNxQQh0aiAAKAI8Qf8BcUEYdGoLIAAoAlAoAhxGDQAgACgCWEHIDDYCGCAAKAJQQdH+ADYCBAwICyAAQQA2AjwgAEEANgI4CyAAKAJQQc/+ADYCBAsCQCAAKAJQKAIMRQ0AIAAoAlAoAhRFDQADQCAAKAI4QSBJBEAgACgCREUNByAAIAAoAkRBAWs2AkQgACAAKAJMIgFBAWo2AkwgACAAKAI8IAEtAAAgACgCOHRqNgI8IAAgACgCOEEIajYCOAwBCwsgACgCPCAAKAJQKAIgRwRAIAAoAlhBsQw2AhggACgCUEHR/gA2AgQMBwsgAEEANgI8IABBADYCOAsgACgCUEHQ/gA2AgQLIABBATYCEAwDCyAAQX02AhAMAgsgAEF8NgJcDAMLIABBfjYCXAwCCwsgACgCWCAAKAJINgIMIAAoAlggACgCQDYCECAAKAJYIAAoAkw2AgAgACgCWCAAKAJENgIEIAAoAlAgACgCPDYCPCAAKAJQIAAoAjg2AkACQAJAIAAoAlAoAiwNACAAKAIwIAAoAlgoAhBGDQEgACgCUCgCBEHR/gBPDQEgACgCUCgCBEHO/gBJDQAgACgCVEEERg0BCwJ/IAAoAlghAiAAKAJYKAIMIQMgACgCMCAAKAJYKAIQayEEIwBBIGsiASQAIAEgAjYCGCABIAM2AhQgASAENgIQIAEgASgCGCgCHDYCDAJAIAEoAgwoAjhFBEAgASgCGCgCKEEBIAEoAgwoAih0QQEgASgCGCgCIBEBACECIAEoAgwgAjYCOCABKAIMKAI4RQRAIAFBATYCHAwCCwsgASgCDCgCLEUEQCABKAIMQQEgASgCDCgCKHQ2AiwgASgCDEEANgI0IAEoAgxBADYCMAsCQCABKAIQIAEoAgwoAixPBEAgASgCDCgCOCABKAIUIAEoAgwoAixrIAEoAgwoAiwQGRogASgCDEEANgI0IAEoAgwgASgCDCgCLDYCMAwBCyABIAEoAgwoAiwgASgCDCgCNGs2AgggASgCCCABKAIQSwRAIAEgASgCEDYCCAsgASgCDCgCOCABKAIMKAI0aiABKAIUIAEoAhBrIAEoAggQGRogASABKAIQIAEoAghrNgIQAkAgASgCEARAIAEoAgwoAjggASgCFCABKAIQayABKAIQEBkaIAEoAgwgASgCEDYCNCABKAIMIAEoAgwoAiw2AjAMAQsgASgCDCICIAEoAgggAigCNGo2AjQgASgCDCgCNCABKAIMKAIsRgRAIAEoAgxBADYCNAsgASgCDCgCMCABKAIMKAIsSQRAIAEoAgwiAiABKAIIIAIoAjBqNgIwCwsLIAFBADYCHAsgASgCHCECIAFBIGokACACCwRAIAAoAlBB0v4ANgIEIABBfDYCXAwCCwsgACAAKAI0IAAoAlgoAgRrNgI0IAAgACgCMCAAKAJYKAIQazYCMCAAKAJYIgEgACgCNCABKAIIajYCCCAAKAJYIgEgACgCMCABKAIUajYCFCAAKAJQIgEgACgCMCABKAIgajYCIAJAIAAoAlAoAgxBBHFFDQAgACgCMEUNAAJ/IAAoAlAoAhQEQCAAKAJQKAIcIAAoAlgoAgwgACgCMGsgACgCMBAaDAELIAAoAlAoAhwgACgCWCgCDCAAKAIwayAAKAIwED4LIQEgACgCUCABNgIcIAAoAlggATYCMAsgACgCWCAAKAJQKAJAQcAAQQAgACgCUCgCCBtqQYABQQAgACgCUCgCBEG//gBGG2pBgAJBACAAKAJQKAIEQcf+AEcEfyAAKAJQKAIEQcL+AEYFQQELQQFxG2o2AiwCQAJAIAAoAjRFBEAgACgCMEUNAQsgACgCVEEERw0BCyAAKAIQDQAgAEF7NgIQCyAAIAAoAhA2AlwLIAAoAlwhASAAQeAAaiQAIAUgATYCCAsgBSgCECIAIAApAwAgBSgCDDUCIH03AwACQAJAAkACQAJAIAUoAghBBWoOBwIDAwMDAAEDCyAFQQA2AhwMAwsgBUEBNgIcDAILIAUoAgwoAhRFBEAgBUEDNgIcDAILCyAFKAIMKAIAQQ0gBSgCCBAUIAVBAjYCHAsgBSgCHCEAIAVBIGokACAACyQBAX8jAEEQayIBIAA2AgwgASABKAIMNgIIIAEoAghBAToADAuXAQEBfyMAQSBrIgMkACADIAA2AhggAyABNgIUIAMgAjcDCCADIAMoAhg2AgQCQAJAIAMpAwhC/////w9YBEAgAygCBCgCFEUNAQsgAygCBCgCAEESQQAQFCADQQA6AB8MAQsgAygCBCADKQMIPgIUIAMoAgQgAygCFDYCECADQQE6AB8LIAMtAB9BAXEhACADQSBqJAAgAAukAgECfyMAQRBrIgEkACABIAA2AgggASABKAIINgIEAkAgASgCBC0ABEEBcQRAIAEgASgCBEEQahC3ATYCAAwBCyABKAIEQRBqIQIjAEEQayIAJAAgACACNgIIAkAgACgCCBBLBEAgAEF+NgIMDAELIAAgACgCCCgCHDYCBCAAKAIEKAI4BEAgACgCCCgCKCAAKAIEKAI4IAAoAggoAiQRBAALIAAoAggoAiggACgCCCgCHCAAKAIIKAIkEQQAIAAoAghBADYCHCAAQQA2AgwLIAAoAgwhAiAAQRBqJAAgASACNgIACwJAIAEoAgAEQCABKAIEKAIAQQ0gASgCABAUIAFBADoADwwBCyABQQE6AA8LIAEtAA9BAXEhACABQRBqJAAgAAuyGAEFfyMAQRBrIgQkACAEIAA2AgggBCAEKAIINgIEIAQoAgRBADYCFCAEKAIEQQA2AhAgBCgCBEEANgIgIAQoAgRBADYCHAJAIAQoAgQtAARBAXEEQCAEKAIEQRBqIQEgBCgCBCgCCCECIwBBMGsiACQAIAAgATYCKCAAIAI2AiQgAEEINgIgIABBcTYCHCAAQQk2AhggAEEANgIUIABBwBI2AhAgAEE4NgIMIABBATYCBAJAAkACQCAAKAIQRQ0AIAAoAhAsAABB+O4ALAAARw0AIAAoAgxBOEYNAQsgAEF6NgIsDAELIAAoAihFBEAgAEF+NgIsDAELIAAoAihBADYCGCAAKAIoKAIgRQRAIAAoAihBBTYCICAAKAIoQQA2AigLIAAoAigoAiRFBEAgACgCKEEGNgIkCyAAKAIkQX9GBEAgAEEGNgIkCwJAIAAoAhxBAEgEQCAAQQA2AgQgAEEAIAAoAhxrNgIcDAELIAAoAhxBD0oEQCAAQQI2AgQgACAAKAIcQRBrNgIcCwsCQAJAIAAoAhhBAUgNACAAKAIYQQlKDQAgACgCIEEIRw0AIAAoAhxBCEgNACAAKAIcQQ9KDQAgACgCJEEASA0AIAAoAiRBCUoNACAAKAIUQQBIDQAgACgCFEEESg0AIAAoAhxBCEcNASAAKAIEQQFGDQELIABBfjYCLAwBCyAAKAIcQQhGBEAgAEEJNgIcCyAAIAAoAigoAihBAUHELSAAKAIoKAIgEQEANgIIIAAoAghFBEAgAEF8NgIsDAELIAAoAiggACgCCDYCHCAAKAIIIAAoAig2AgAgACgCCEEqNgIEIAAoAgggACgCBDYCGCAAKAIIQQA2AhwgACgCCCAAKAIcNgIwIAAoAghBASAAKAIIKAIwdDYCLCAAKAIIIAAoAggoAixBAWs2AjQgACgCCCAAKAIYQQdqNgJQIAAoAghBASAAKAIIKAJQdDYCTCAAKAIIIAAoAggoAkxBAWs2AlQgACgCCCAAKAIIKAJQQQJqQQNuNgJYIAAoAigoAiggACgCCCgCLEECIAAoAigoAiARAQAhASAAKAIIIAE2AjggACgCKCgCKCAAKAIIKAIsQQIgACgCKCgCIBEBACEBIAAoAgggATYCQCAAKAIoKAIoIAAoAggoAkxBAiAAKAIoKAIgEQEAIQEgACgCCCABNgJEIAAoAghBADYCwC0gACgCCEEBIAAoAhhBBmp0NgKcLSAAIAAoAigoAiggACgCCCgCnC1BBCAAKAIoKAIgEQEANgIAIAAoAgggACgCADYCCCAAKAIIIAAoAggoApwtQQJ0NgIMAkACQCAAKAIIKAI4RQ0AIAAoAggoAkBFDQAgACgCCCgCREUNACAAKAIIKAIIDQELIAAoAghBmgU2AgQgACgCKEG42QAoAgA2AhggACgCKBC3ARogAEF8NgIsDAELIAAoAgggACgCACAAKAIIKAKcLUEBdkEBdGo2AqQtIAAoAgggACgCCCgCCCAAKAIIKAKcLUEDbGo2ApgtIAAoAgggACgCJDYChAEgACgCCCAAKAIUNgKIASAAKAIIIAAoAiA6ACQgACgCKCEBIwBBEGsiAyQAIAMgATYCDCADKAIMIQIjAEEQayIBJAAgASACNgIIAkAgASgCCBB5BEAgAUF+NgIMDAELIAEoAghBADYCFCABKAIIQQA2AgggASgCCEEANgIYIAEoAghBAjYCLCABIAEoAggoAhw2AgQgASgCBEEANgIUIAEoAgQgASgCBCgCCDYCECABKAIEKAIYQQBIBEAgASgCBEEAIAEoAgQoAhhrNgIYCyABKAIEIAEoAgQoAhhBAkYEf0E5BUEqQfEAIAEoAgQoAhgbCzYCBAJ/IAEoAgQoAhhBAkYEQEEAQQBBABAaDAELQQBBAEEAED4LIQIgASgCCCACNgIwIAEoAgRBADYCKCABKAIEIQUjAEEQayICJAAgAiAFNgIMIAIoAgwgAigCDEGUAWo2ApgWIAIoAgxB0N8ANgKgFiACKAIMIAIoAgxBiBNqNgKkFiACKAIMQeTfADYCrBYgAigCDCACKAIMQfwUajYCsBYgAigCDEH43wA2ArgWIAIoAgxBADsBuC0gAigCDEEANgK8LSACKAIMEL0BIAJBEGokACABQQA2AgwLIAEoAgwhAiABQRBqJAAgAyACNgIIIAMoAghFBEAgAygCDCgCHCECIwBBEGsiASQAIAEgAjYCDCABKAIMIAEoAgwoAixBAXQ2AjwgASgCDCgCRCABKAIMKAJMQQFrQQF0akEAOwEAIAEoAgwoAkRBACABKAIMKAJMQQFrQQF0EDIgASgCDCABKAIMKAKEAUEMbEGA7wBqLwECNgKAASABKAIMIAEoAgwoAoQBQQxsQYDvAGovAQA2AowBIAEoAgwgASgCDCgChAFBDGxBgO8Aai8BBDYCkAEgASgCDCABKAIMKAKEAUEMbEGA7wBqLwEGNgJ8IAEoAgxBADYCbCABKAIMQQA2AlwgASgCDEEANgJ0IAEoAgxBADYCtC0gASgCDEECNgJ4IAEoAgxBAjYCYCABKAIMQQA2AmggASgCDEEANgJIIAFBEGokAAsgAygCCCEBIANBEGokACAAIAE2AiwLIAAoAiwhASAAQTBqJAAgBCABNgIADAELIAQoAgRBEGohASMAQSBrIgAkACAAIAE2AhggAEFxNgIUIABBwBI2AhAgAEE4NgIMAkACQAJAIAAoAhBFDQAgACgCECwAAEHAEiwAAEcNACAAKAIMQThGDQELIABBejYCHAwBCyAAKAIYRQRAIABBfjYCHAwBCyAAKAIYQQA2AhggACgCGCgCIEUEQCAAKAIYQQU2AiAgACgCGEEANgIoCyAAKAIYKAIkRQRAIAAoAhhBBjYCJAsgACAAKAIYKAIoQQFB0DcgACgCGCgCIBEBADYCBCAAKAIERQRAIABBfDYCHAwBCyAAKAIYIAAoAgQ2AhwgACgCBCAAKAIYNgIAIAAoAgRBADYCOCAAKAIEQbT+ADYCBCAAKAIYIQIgACgCFCEDIwBBIGsiASQAIAEgAjYCGCABIAM2AhQCQCABKAIYEEsEQCABQX42AhwMAQsgASABKAIYKAIcNgIMAkAgASgCFEEASARAIAFBADYCECABQQAgASgCFGs2AhQMAQsgASABKAIUQQR1QQVqNgIQIAEoAhRBMEgEQCABIAEoAhRBD3E2AhQLCwJAIAEoAhRFDQAgASgCFEEITgRAIAEoAhRBD0wNAQsgAUF+NgIcDAELAkAgASgCDCgCOEUNACABKAIMKAIoIAEoAhRGDQAgASgCGCgCKCABKAIMKAI4IAEoAhgoAiQRBAAgASgCDEEANgI4CyABKAIMIAEoAhA2AgwgASgCDCABKAIUNgIoIAEoAhghAiMAQRBrIgMkACADIAI2AggCQCADKAIIEEsEQCADQX42AgwMAQsgAyADKAIIKAIcNgIEIAMoAgRBADYCLCADKAIEQQA2AjAgAygCBEEANgI0IAMoAgghBSMAQRBrIgIkACACIAU2AggCQCACKAIIEEsEQCACQX42AgwMAQsgAiACKAIIKAIcNgIEIAIoAgRBADYCICACKAIIQQA2AhQgAigCCEEANgIIIAIoAghBADYCGCACKAIEKAIMBEAgAigCCCACKAIEKAIMQQFxNgIwCyACKAIEQbT+ADYCBCACKAIEQQA2AgggAigCBEEANgIQIAIoAgRBgIACNgIYIAIoAgRBADYCJCACKAIEQQA2AjwgAigCBEEANgJAIAIoAgQgAigCBEG0CmoiBTYCcCACKAIEIAU2AlQgAigCBCAFNgJQIAIoAgRBATYCxDcgAigCBEF/NgLINyACQQA2AgwLIAIoAgwhBSACQRBqJAAgAyAFNgIMCyADKAIMIQIgA0EQaiQAIAEgAjYCHAsgASgCHCECIAFBIGokACAAIAI2AgggACgCCARAIAAoAhgoAiggACgCBCAAKAIYKAIkEQQAIAAoAhhBADYCHAsgACAAKAIINgIcCyAAKAIcIQEgAEEgaiQAIAQgATYCAAsCQCAEKAIABEAgBCgCBCgCAEENIAQoAgAQFCAEQQA6AA8MAQsgBEEBOgAPCyAELQAPQQFxIQAgBEEQaiQAIAALbwEBfyMAQRBrIgEgADYCCCABIAEoAgg2AgQCQCABKAIELQAEQQFxRQRAIAFBADYCDAwBCyABKAIEKAIIQQNIBEAgAUECNgIMDAELIAEoAgQoAghBB0oEQCABQQE2AgwMAQsgAUEANgIMCyABKAIMCywBAX8jAEEQayIBJAAgASAANgIMIAEgASgCDDYCCCABKAIIEBUgAUEQaiQACzwBAX8jAEEQayIDJAAgAyAAOwEOIAMgATYCCCADIAI2AgRBASADKAIIIAMoAgQQtAEhACADQRBqJAAgAAvBEAECfyMAQSBrIgIkACACIAA2AhggAiABNgIUAkADQAJAIAIoAhgoAnRBhgJJBEAgAigCGBBbAkAgAigCGCgCdEGGAk8NACACKAIUDQAgAkEANgIcDAQLIAIoAhgoAnRFDQELIAJBADYCECACKAIYKAJ0QQNPBEAgAigCGCACKAIYKAJUIAIoAhgoAjggAigCGCgCbEECamotAAAgAigCGCgCSCACKAIYKAJYdHNxNgJIIAIoAhgoAkAgAigCGCgCbCACKAIYKAI0cUEBdGogAigCGCgCRCACKAIYKAJIQQF0ai8BACIAOwEAIAIgAEH//wNxNgIQIAIoAhgoAkQgAigCGCgCSEEBdGogAigCGCgCbDsBAAsgAigCGCACKAIYKAJgNgJ4IAIoAhggAigCGCgCcDYCZCACKAIYQQI2AmACQCACKAIQRQ0AIAIoAhgoAnggAigCGCgCgAFPDQAgAigCGCgCLEGGAmsgAigCGCgCbCACKAIQa0kNACACKAIYIAIoAhAQtQEhACACKAIYIAA2AmACQCACKAIYKAJgQQVLDQAgAigCGCgCiAFBAUcEQCACKAIYKAJgQQNHDQEgAigCGCgCbCACKAIYKAJwa0GAIE0NAQsgAigCGEECNgJgCwsCQAJAIAIoAhgoAnhBA0kNACACKAIYKAJgIAIoAhgoAnhLDQAgAiACKAIYIgAoAmwgACgCdGpBA2s2AgggAiACKAIYKAJ4QQNrOgAHIAIgAigCGCIAKAJsIAAoAmRBf3NqOwEEIAIoAhgiACgCpC0gACgCoC1BAXRqIAIvAQQ7AQAgAi0AByEBIAIoAhgiACgCmC0hAyAAIAAoAqAtIgBBAWo2AqAtIAAgA2ogAToAACACIAIvAQRBAWs7AQQgAigCGCACLQAHQdDdAGotAABBAnRqQZgJaiIAIAAvAQBBAWo7AQAgAigCGEGIE2oCfyACLwEEQYACSQRAIAIvAQQtANBZDAELIAIvAQRBB3ZBgAJqLQDQWQtBAnRqIgAgAC8BAEEBajsBACACIAIoAhgoAqAtIAIoAhgoApwtQQFrRjYCDCACKAIYIgAgACgCdCACKAIYKAJ4QQFrazYCdCACKAIYIgAgACgCeEECazYCeANAIAIoAhgiASgCbEEBaiEAIAEgADYCbCAAIAIoAghNBEAgAigCGCACKAIYKAJUIAIoAhgoAjggAigCGCgCbEECamotAAAgAigCGCgCSCACKAIYKAJYdHNxNgJIIAIoAhgoAkAgAigCGCgCbCACKAIYKAI0cUEBdGogAigCGCgCRCACKAIYKAJIQQF0ai8BACIAOwEAIAIgAEH//wNxNgIQIAIoAhgoAkQgAigCGCgCSEEBdGogAigCGCgCbDsBAAsgAigCGCIBKAJ4QQFrIQAgASAANgJ4IAANAAsgAigCGEEANgJoIAIoAhhBAjYCYCACKAIYIgAgACgCbEEBajYCbCACKAIMBEAgAigCGAJ/IAIoAhgoAlxBAE4EQCACKAIYKAI4IAIoAhgoAlxqDAELQQALIAIoAhgoAmwgAigCGCgCXGtBABAoIAIoAhggAigCGCgCbDYCXCACKAIYKAIAEBwgAigCGCgCACgCEEUEQCACQQA2AhwMBgsLDAELAkAgAigCGCgCaARAIAIgAigCGCIAKAI4IAAoAmxqQQFrLQAAOgADIAIoAhgiACgCpC0gACgCoC1BAXRqQQA7AQAgAi0AAyEBIAIoAhgiACgCmC0hAyAAIAAoAqAtIgBBAWo2AqAtIAAgA2ogAToAACACKAIYIAItAANBAnRqIgAgAC8BlAFBAWo7AZQBIAIgAigCGCgCoC0gAigCGCgCnC1BAWtGNgIMIAIoAgwEQCACKAIYAn8gAigCGCgCXEEATgRAIAIoAhgoAjggAigCGCgCXGoMAQtBAAsgAigCGCgCbCACKAIYKAJca0EAECggAigCGCACKAIYKAJsNgJcIAIoAhgoAgAQHAsgAigCGCIAIAAoAmxBAWo2AmwgAigCGCIAIAAoAnRBAWs2AnQgAigCGCgCACgCEEUEQCACQQA2AhwMBgsMAQsgAigCGEEBNgJoIAIoAhgiACAAKAJsQQFqNgJsIAIoAhgiACAAKAJ0QQFrNgJ0CwsMAQsLIAIoAhgoAmgEQCACIAIoAhgiACgCOCAAKAJsakEBay0AADoAAiACKAIYIgAoAqQtIAAoAqAtQQF0akEAOwEAIAItAAIhASACKAIYIgAoApgtIQMgACAAKAKgLSIAQQFqNgKgLSAAIANqIAE6AAAgAigCGCACLQACQQJ0aiIAIAAvAZQBQQFqOwGUASACIAIoAhgoAqAtIAIoAhgoApwtQQFrRjYCDCACKAIYQQA2AmgLIAIoAhgCfyACKAIYKAJsQQJJBEAgAigCGCgCbAwBC0ECCzYCtC0gAigCFEEERgRAIAIoAhgCfyACKAIYKAJcQQBOBEAgAigCGCgCOCACKAIYKAJcagwBC0EACyACKAIYKAJsIAIoAhgoAlxrQQEQKCACKAIYIAIoAhgoAmw2AlwgAigCGCgCABAcIAIoAhgoAgAoAhBFBEAgAkECNgIcDAILIAJBAzYCHAwBCyACKAIYKAKgLQRAIAIoAhgCfyACKAIYKAJcQQBOBEAgAigCGCgCOCACKAIYKAJcagwBC0EACyACKAIYKAJsIAIoAhgoAlxrQQAQKCACKAIYIAIoAhgoAmw2AlwgAigCGCgCABAcIAIoAhgoAgAoAhBFBEAgAkEANgIcDAILCyACQQE2AhwLIAIoAhwhACACQSBqJAAgAAuVDQECfyMAQSBrIgIkACACIAA2AhggAiABNgIUAkADQAJAIAIoAhgoAnRBhgJJBEAgAigCGBBbAkAgAigCGCgCdEGGAk8NACACKAIUDQAgAkEANgIcDAQLIAIoAhgoAnRFDQELIAJBADYCECACKAIYKAJ0QQNPBEAgAigCGCACKAIYKAJUIAIoAhgoAjggAigCGCgCbEECamotAAAgAigCGCgCSCACKAIYKAJYdHNxNgJIIAIoAhgoAkAgAigCGCgCbCACKAIYKAI0cUEBdGogAigCGCgCRCACKAIYKAJIQQF0ai8BACIAOwEAIAIgAEH//wNxNgIQIAIoAhgoAkQgAigCGCgCSEEBdGogAigCGCgCbDsBAAsCQCACKAIQRQ0AIAIoAhgoAixBhgJrIAIoAhgoAmwgAigCEGtJDQAgAigCGCACKAIQELUBIQAgAigCGCAANgJgCwJAIAIoAhgoAmBBA08EQCACIAIoAhgoAmBBA2s6AAsgAiACKAIYIgAoAmwgACgCcGs7AQggAigCGCIAKAKkLSAAKAKgLUEBdGogAi8BCDsBACACLQALIQEgAigCGCIAKAKYLSEDIAAgACgCoC0iAEEBajYCoC0gACADaiABOgAAIAIgAi8BCEEBazsBCCACKAIYIAItAAtB0N0Aai0AAEECdGpBmAlqIgAgAC8BAEEBajsBACACKAIYQYgTagJ/IAIvAQhBgAJJBEAgAi8BCC0A0FkMAQsgAi8BCEEHdkGAAmotANBZC0ECdGoiACAALwEAQQFqOwEAIAIgAigCGCgCoC0gAigCGCgCnC1BAWtGNgIMIAIoAhgiACAAKAJ0IAIoAhgoAmBrNgJ0AkACQCACKAIYKAJgIAIoAhgoAoABSw0AIAIoAhgoAnRBA0kNACACKAIYIgAgACgCYEEBazYCYANAIAIoAhgiACAAKAJsQQFqNgJsIAIoAhggAigCGCgCVCACKAIYKAI4IAIoAhgoAmxBAmpqLQAAIAIoAhgoAkggAigCGCgCWHRzcTYCSCACKAIYKAJAIAIoAhgoAmwgAigCGCgCNHFBAXRqIAIoAhgoAkQgAigCGCgCSEEBdGovAQAiADsBACACIABB//8DcTYCECACKAIYKAJEIAIoAhgoAkhBAXRqIAIoAhgoAmw7AQAgAigCGCIBKAJgQQFrIQAgASAANgJgIAANAAsgAigCGCIAIAAoAmxBAWo2AmwMAQsgAigCGCIAIAIoAhgoAmAgACgCbGo2AmwgAigCGEEANgJgIAIoAhggAigCGCgCOCACKAIYKAJsai0AADYCSCACKAIYIAIoAhgoAlQgAigCGCgCOCACKAIYKAJsQQFqai0AACACKAIYKAJIIAIoAhgoAlh0c3E2AkgLDAELIAIgAigCGCIAKAI4IAAoAmxqLQAAOgAHIAIoAhgiACgCpC0gACgCoC1BAXRqQQA7AQAgAi0AByEBIAIoAhgiACgCmC0hAyAAIAAoAqAtIgBBAWo2AqAtIAAgA2ogAToAACACKAIYIAItAAdBAnRqIgAgAC8BlAFBAWo7AZQBIAIgAigCGCgCoC0gAigCGCgCnC1BAWtGNgIMIAIoAhgiACAAKAJ0QQFrNgJ0IAIoAhgiACAAKAJsQQFqNgJsCyACKAIMBEAgAigCGAJ/IAIoAhgoAlxBAE4EQCACKAIYKAI4IAIoAhgoAlxqDAELQQALIAIoAhgoAmwgAigCGCgCXGtBABAoIAIoAhggAigCGCgCbDYCXCACKAIYKAIAEBwgAigCGCgCACgCEEUEQCACQQA2AhwMBAsLDAELCyACKAIYAn8gAigCGCgCbEECSQRAIAIoAhgoAmwMAQtBAgs2ArQtIAIoAhRBBEYEQCACKAIYAn8gAigCGCgCXEEATgRAIAIoAhgoAjggAigCGCgCXGoMAQtBAAsgAigCGCgCbCACKAIYKAJca0EBECggAigCGCACKAIYKAJsNgJcIAIoAhgoAgAQHCACKAIYKAIAKAIQRQRAIAJBAjYCHAwCCyACQQM2AhwMAQsgAigCGCgCoC0EQCACKAIYAn8gAigCGCgCXEEATgRAIAIoAhgoAjggAigCGCgCXGoMAQtBAAsgAigCGCgCbCACKAIYKAJca0EAECggAigCGCACKAIYKAJsNgJcIAIoAhgoAgAQHCACKAIYKAIAKAIQRQRAIAJBADYCHAwCCwsgAkEBNgIcCyACKAIcIQAgAkEgaiQAIAALBgBBtJsBCykBAX8jAEEQayICJAAgAiAANgIMIAIgATYCCCACKAIIEBUgAkEQaiQACzoBAX8jAEEQayIDJAAgAyAANgIMIAMgATYCCCADIAI2AgQgAygCCCADKAIEbBAYIQAgA0EQaiQAIAALzgUBAX8jAEHQAGsiBSQAIAUgADYCRCAFIAE2AkAgBSACNgI8IAUgAzcDMCAFIAQ2AiwgBSAFKAJANgIoAkACQAJAAkACQAJAAkACQAJAIAUoAiwODwABAgMFBgcHBwcHBwcHBAcLAn8gBSgCRCEBIAUoAighAiMAQeAAayIAJAAgACABNgJYIAAgAjYCVCAAIAAoAlggAEHIAGpCDBAuIgM3AwgCQCADQgBTBEAgACgCVCAAKAJYEBcgAEF/NgJcDAELIAApAwhCDFIEQCAAKAJUQRFBABAUIABBfzYCXAwBCyAAKAJUIABByABqIABByABqQgxBABB9IAAoAlggAEEQahA4QQBIBEAgAEEANgJcDAELIAAoAjggAEEGaiAAQQRqEIEBAkAgAC0AUyAAKAI8QRh2Rg0AIAAtAFMgAC8BBkEIdkYNACAAKAJUQRtBABAUIABBfzYCXAwBCyAAQQA2AlwLIAAoAlwhASAAQeAAaiQAIAFBAEgLBEAgBUJ/NwNIDAgLIAVCADcDSAwHCyAFIAUoAkQgBSgCPCAFKQMwEC4iAzcDICADQgBTBEAgBSgCKCAFKAJEEBcgBUJ/NwNIDAcLIAUoAkAgBSgCPCAFKAI8IAUpAyBBABB9IAUgBSkDIDcDSAwGCyAFQgA3A0gMBQsgBSAFKAI8NgIcIAUoAhxBADsBMiAFKAIcIgAgACkDAEKAAYQ3AwAgBSgCHCkDAEIIg0IAUgRAIAUoAhwiACAAKQMgQgx9NwMgCyAFQgA3A0gMBAsgBUF/NgIUIAVBBTYCECAFQQQ2AgwgBUEDNgIIIAVBAjYCBCAFQQE2AgAgBUEAIAUQNjcDSAwDCyAFIAUoAiggBSgCPCAFKQMwEEI3A0gMAgsgBSgCKBC+ASAFQgA3A0gMAQsgBSgCKEESQQAQFCAFQn83A0gLIAUpA0ghAyAFQdAAaiQAIAMLBwAgAC8BMAvuAgEBfyMAQSBrIgUkACAFIAA2AhggBSABNgIUIAUgAjsBEiAFIAM2AgwgBSAENgIIAkACQAJAIAUoAghFDQAgBSgCFEUNACAFLwESQQFGDQELIAUoAhhBCGpBEkEAEBQgBUEANgIcDAELIAUoAgxBAXEEQCAFKAIYQQhqQRhBABAUIAVBADYCHAwBCyAFQRgQGCIANgIEIABFBEAgBSgCGEEIakEOQQAQFCAFQQA2AhwMAQsjAEEQayIAIAUoAgQ2AgwgACgCDEEANgIAIAAoAgxBADYCBCAAKAIMQQA2AgggBSgCBEH4rNGRATYCDCAFKAIEQYnPlZoCNgIQIAUoAgRBkPHZogM2AhQgBSgCBEEAIAUoAgggBSgCCBArrUEBEH0gBSAFKAIYIAUoAhRBAyAFKAIEEGYiADYCACAARQRAIAUoAgQQvgEgBUEANgIcDAELIAUgBSgCADYCHAsgBSgCHCEAIAVBIGokACAAC70YAQJ/IwBB8ABrIgQkACAEIAA2AmQgBCABNgJgIAQgAjcDWCAEIAM2AlQgBCAEKAJkNgJQAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAEKAJUDhQGBwIMBAUKDwADCRELEA4IEgESDRILQQBCAEEAIAQoAlAQTSEAIAQoAlAgADYCFCAARQRAIARCfzcDaAwTCyAEKAJQKAIUQgA3AzggBCgCUCgCFEIANwNAIARCADcDaAwSCyAEKAJQKAIQIQEgBCkDWCECIAQoAlAhAyMAQUBqIgAkACAAIAE2AjggACACNwMwIAAgAzYCLAJAIAApAzBQBEAgAEEAQgBBASAAKAIsEE02AjwMAQsgACkDMCAAKAI4KQMwVgRAIAAoAixBEkEAEBQgAEEANgI8DAELIAAoAjgoAigEQCAAKAIsQR1BABAUIABBADYCPAwBCyAAIAAoAjggACkDMBC/ATcDICAAIAApAzAgACgCOCgCBCAAKQMgp0EDdGopAwB9NwMYIAApAxhQBEAgACAAKQMgQgF9NwMgIAAgACgCOCgCACAAKQMgp0EEdGopAwg3AxgLIAAgACgCOCgCACAAKQMgp0EEdGopAwggACkDGH03AxAgACkDECAAKQMwVgRAIAAoAixBHEEAEBQgAEEANgI8DAELIAAgACgCOCgCACAAKQMgQgF8QQAgACgCLBBNIgE2AgwgAUUEQCAAQQA2AjwMAQsgACgCDCgCACAAKAIMKQMIQgF9p0EEdGogACkDGDcDCCAAKAIMKAIEIAAoAgwpAwinQQN0aiAAKQMwNwMAIAAoAgwgACkDMDcDMCAAKAIMAn4gACgCOCkDGCAAKAIMKQMIQgF9VARAIAAoAjgpAxgMAQsgACgCDCkDCEIBfQs3AxggACgCOCAAKAIMNgIoIAAoAgwgACgCODYCKCAAKAI4IAAoAgwpAwg3AyAgACgCDCAAKQMgQgF8NwMgIAAgACgCDDYCPAsgACgCPCEBIABBQGskACABIQAgBCgCUCAANgIUIABFBEAgBEJ/NwNoDBILIAQoAlAoAhQgBCkDWDcDOCAEKAJQKAIUIAQoAlAoAhQpAwg3A0AgBEIANwNoDBELIARCADcDaAwQCyAEKAJQKAIQEDMgBCgCUCAEKAJQKAIUNgIQIAQoAlBBADYCFCAEQgA3A2gMDwsgBCAEKAJQIAQoAmAgBCkDWBBCNwNoDA4LIAQoAlAoAhAQMyAEKAJQKAIUEDMgBCgCUBAVIARCADcDaAwNCyAEKAJQKAIQQgA3AzggBCgCUCgCEEIANwNAIARCADcDaAwMCyAEKQNYQv///////////wBWBEAgBCgCUEESQQAQFCAEQn83A2gMDAsgBCgCUCgCECEBIAQoAmAhAyAEKQNYIQIjAEFAaiIAJAAgACABNgI0IAAgAzYCMCAAIAI3AyggAAJ+IAApAyggACgCNCkDMCAAKAI0KQM4fVQEQCAAKQMoDAELIAAoAjQpAzAgACgCNCkDOH0LNwMoAkAgACkDKFAEQCAAQgA3AzgMAQsgACkDKEL///////////8AVgRAIABCfzcDOAwBCyAAIAAoAjQpA0A3AxggACAAKAI0KQM4IAAoAjQoAgQgACkDGKdBA3RqKQMAfTcDECAAQgA3AyADQCAAKQMgIAApAyhUBEAgAAJ+IAApAyggACkDIH0gACgCNCgCACAAKQMYp0EEdGopAwggACkDEH1UBEAgACkDKCAAKQMgfQwBCyAAKAI0KAIAIAApAxinQQR0aikDCCAAKQMQfQs3AwggACgCMCAAKQMgp2ogACgCNCgCACAAKQMYp0EEdGooAgAgACkDEKdqIAApAwinEBkaIAApAwggACgCNCgCACAAKQMYp0EEdGopAwggACkDEH1RBEAgACAAKQMYQgF8NwMYCyAAIAApAwggACkDIHw3AyAgAEIANwMQDAELCyAAKAI0IgEgACkDICABKQM4fDcDOCAAKAI0IAApAxg3A0AgACAAKQMgNwM4CyAAKQM4IQIgAEFAayQAIAQgAjcDaAwLCyAEQQBCAEEAIAQoAlAQTTYCTCAEKAJMRQRAIARCfzcDaAwLCyAEKAJQKAIQEDMgBCgCUCAEKAJMNgIQIARCADcDaAwKCyAEKAJQKAIUEDMgBCgCUEEANgIUIARCADcDaAwJCyAEIAQoAlAoAhAgBCgCYCAEKQNYIAQoAlAQwAGsNwNoDAgLIAQgBCgCUCgCFCAEKAJgIAQpA1ggBCgCUBDAAaw3A2gMBwsgBCkDWEI4VARAIAQoAlBBEkEAEBQgBEJ/NwNoDAcLIAQgBCgCYDYCSCAEKAJIEDsgBCgCSCAEKAJQKAIMNgIoIAQoAkggBCgCUCgCECkDMDcDGCAEKAJIIAQoAkgpAxg3AyAgBCgCSEEAOwEwIAQoAkhBADsBMiAEKAJIQtwBNwMAIARCODcDaAwGCyAEKAJQIAQoAmAoAgA2AgwgBEIANwNoDAULIARBfzYCQCAEQRM2AjwgBEELNgI4IARBDTYCNCAEQQw2AjAgBEEKNgIsIARBDzYCKCAEQQk2AiQgBEERNgIgIARBCDYCHCAEQQc2AhggBEEGNgIUIARBBTYCECAEQQQ2AgwgBEEDNgIIIARBAjYCBCAEQQE2AgAgBEEAIAQQNjcDaAwECyAEKAJQKAIQKQM4Qv///////////wBWBEAgBCgCUEEeQT0QFCAEQn83A2gMBAsgBCAEKAJQKAIQKQM4NwNoDAMLIAQoAlAoAhQpAzhC////////////AFYEQCAEKAJQQR5BPRAUIARCfzcDaAwDCyAEIAQoAlAoAhQpAzg3A2gMAgsgBCkDWEL///////////8AVgRAIAQoAlBBEkEAEBQgBEJ/NwNoDAILIAQoAlAoAhQhASAEKAJgIQMgBCkDWCECIAQoAlAhBSMAQeAAayIAJAAgACABNgJUIAAgAzYCUCAAIAI3A0ggACAFNgJEAkAgACkDSCAAKAJUKQM4IAApA0h8Qv//A3xWBEAgACgCREESQQAQFCAAQn83A1gMAQsgACAAKAJUKAIEIAAoAlQpAwinQQN0aikDADcDICAAKQMgIAAoAlQpAzggACkDSHxUBEAgACAAKAJUKQMIIAApA0ggACkDICAAKAJUKQM4fX1C//8DfEIQiHw3AxggACkDGCAAKAJUKQMQVgRAIAAgACgCVCkDEDcDECAAKQMQUARAIABCEDcDEAsDQCAAKQMQIAApAxhUBEAgACAAKQMQQgGGNwMQDAELCyAAKAJUIAApAxAgACgCRBDBAUEBcUUEQCAAKAJEQQ5BABAUIABCfzcDWAwDCwsDQCAAKAJUKQMIIAApAxhUBEBBgIAEEBghASAAKAJUKAIAIAAoAlQpAwinQQR0aiABNgIAIAEEQCAAKAJUKAIAIAAoAlQpAwinQQR0akKAgAQ3AwggACgCVCIBIAEpAwhCAXw3AwggACAAKQMgQoCABHw3AyAgACgCVCgCBCAAKAJUKQMIp0EDdGogACkDIDcDAAwCBSAAKAJEQQ5BABAUIABCfzcDWAwECwALCwsgACAAKAJUKQNANwMwIAAgACgCVCkDOCAAKAJUKAIEIAApAzCnQQN0aikDAH03AyggAEIANwM4A0AgACkDOCAAKQNIVARAIAACfiAAKQNIIAApAzh9IAAoAlQoAgAgACkDMKdBBHRqKQMIIAApAyh9VARAIAApA0ggACkDOH0MAQsgACgCVCgCACAAKQMwp0EEdGopAwggACkDKH0LNwMIIAAoAlQoAgAgACkDMKdBBHRqKAIAIAApAyinaiAAKAJQIAApAzinaiAAKQMIpxAZGiAAKQMIIAAoAlQoAgAgACkDMKdBBHRqKQMIIAApAyh9UQRAIAAgACkDMEIBfDcDMAsgACAAKQMIIAApAzh8NwM4IABCADcDKAwBCwsgACgCVCIBIAApAzggASkDOHw3AzggACgCVCAAKQMwNwNAIAAoAlQpAzggACgCVCkDMFYEQCAAKAJUIAAoAlQpAzg3AzALIAAgACkDODcDWAsgACkDWCECIABB4ABqJAAgBCACNwNoDAELIAQoAlBBHEEAEBQgBEJ/NwNoCyAEKQNoIQIgBEHwAGokACACCwcAIAAoAiALBwAgACgCAAsIAEEBQTgQdgsLhY0BJABBgAgLgQxpbnN1ZmZpY2llbnQgbWVtb3J5AG5lZWQgZGljdGlvbmFyeQAtKyAgIDBYMHgALTBYKzBYIDBYLTB4KzB4IDB4AFppcCBhcmNoaXZlIGluY29uc2lzdGVudABJbnZhbGlkIGFyZ3VtZW50AGludmFsaWQgbGl0ZXJhbC9sZW5ndGhzIHNldABpbnZhbGlkIGNvZGUgbGVuZ3RocyBzZXQAdW5rbm93biBoZWFkZXIgZmxhZ3Mgc2V0AGludmFsaWQgZGlzdGFuY2VzIHNldABpbnZhbGlkIGJpdCBsZW5ndGggcmVwZWF0AEZpbGUgYWxyZWFkeSBleGlzdHMAdG9vIG1hbnkgbGVuZ3RoIG9yIGRpc3RhbmNlIHN5bWJvbHMAaW52YWxpZCBzdG9yZWQgYmxvY2sgbGVuZ3RocwAlcyVzJXMAYnVmZmVyIGVycm9yAE5vIGVycm9yAHN0cmVhbSBlcnJvcgBUZWxsIGVycm9yAEludGVybmFsIGVycm9yAFNlZWsgZXJyb3IAV3JpdGUgZXJyb3IAZmlsZSBlcnJvcgBSZWFkIGVycm9yAFpsaWIgZXJyb3IAZGF0YSBlcnJvcgBDUkMgZXJyb3IAaW5jb21wYXRpYmxlIHZlcnNpb24AbmFuAC9kZXYvdXJhbmRvbQBpbnZhbGlkIGNvZGUgLS0gbWlzc2luZyBlbmQtb2YtYmxvY2sAaW5jb3JyZWN0IGhlYWRlciBjaGVjawBpbmNvcnJlY3QgbGVuZ3RoIGNoZWNrAGluY29ycmVjdCBkYXRhIGNoZWNrAGludmFsaWQgZGlzdGFuY2UgdG9vIGZhciBiYWNrAGhlYWRlciBjcmMgbWlzbWF0Y2gAaW5mAGludmFsaWQgd2luZG93IHNpemUAUmVhZC1vbmx5IGFyY2hpdmUATm90IGEgemlwIGFyY2hpdmUAUmVzb3VyY2Ugc3RpbGwgaW4gdXNlAE1hbGxvYyBmYWlsdXJlAGludmFsaWQgYmxvY2sgdHlwZQBGYWlsdXJlIHRvIGNyZWF0ZSB0ZW1wb3JhcnkgZmlsZQBDYW4ndCBvcGVuIGZpbGUATm8gc3VjaCBmaWxlAFByZW1hdHVyZSBlbmQgb2YgZmlsZQBDYW4ndCByZW1vdmUgZmlsZQBpbnZhbGlkIGxpdGVyYWwvbGVuZ3RoIGNvZGUAaW52YWxpZCBkaXN0YW5jZSBjb2RlAHVua25vd24gY29tcHJlc3Npb24gbWV0aG9kAHN0cmVhbSBlbmQAQ29tcHJlc3NlZCBkYXRhIGludmFsaWQATXVsdGktZGlzayB6aXAgYXJjaGl2ZXMgbm90IHN1cHBvcnRlZABPcGVyYXRpb24gbm90IHN1cHBvcnRlZABFbmNyeXB0aW9uIG1ldGhvZCBub3Qgc3VwcG9ydGVkAENvbXByZXNzaW9uIG1ldGhvZCBub3Qgc3VwcG9ydGVkAEVudHJ5IGhhcyBiZWVuIGRlbGV0ZWQAQ29udGFpbmluZyB6aXAgYXJjaGl2ZSB3YXMgY2xvc2VkAENsb3NpbmcgemlwIGFyY2hpdmUgZmFpbGVkAFJlbmFtaW5nIHRlbXBvcmFyeSBmaWxlIGZhaWxlZABFbnRyeSBoYXMgYmVlbiBjaGFuZ2VkAE5vIHBhc3N3b3JkIHByb3ZpZGVkAFdyb25nIHBhc3N3b3JkIHByb3ZpZGVkAFVua25vd24gZXJyb3IgJWQAcmIAcitiAHJ3YQAlcy5YWFhYWFgATkFOAElORgBBRQAxLjIuMTEAL3Byb2Mvc2VsZi9mZC8ALgAobnVsbCkAOiAAUEsGBwBQSwYGAFBLBQYAUEsDBABQSwECAAAAAAAAUgUAANkHAACsCAAAkQgAAIIFAACkBQAAjQUAAMUFAABvCAAANAcAAOkEAAAkBwAAAwcAAK8FAADhBgAAywgAADcIAABBBwAAWgQAALkGAABzBQAAQQQAAFcHAABYCAAAFwgAAKcGAADiCAAA9wgAAP8HAADLBgAAaAUAAMEHAAAgAEGYFAsRAQAAAAEAAAABAAAAAQAAAAEAQbwUCwkBAAAAAQAAAAIAQegUCwEBAEGIFQsBAQBBlBUL+0OWMAd3LGEO7rpRCZkZxG0Hj/RqcDWlY+mjlWSeMojbDqS43Hke6dXgiNnSlytMtgm9fLF+By2455Edv5BkELcd8iCwakhxufPeQb6EfdTaGuvk3W1RtdT0x4XTg1aYbBPAqGtkevli/ezJZYpPXAEU2WwGY2M9D/r1DQiNyCBuO14QaUzkQWDVcnFnotHkAzxH1ARL/YUN0mu1CqX6qLU1bJiyQtbJu9tA+bys42zYMnVc30XPDdbcWT3Rq6ww2SY6AN5RgFHXyBZh0L+19LQhI8SzVpmVus8Ppb24nrgCKAiIBV+y2QzGJOkLsYd8by8RTGhYqx1hwT0tZraQQdx2BnHbAbwg0pgqENXviYWxcR+1tgal5L+fM9S46KLJB3g0+QAPjqgJlhiYDuG7DWp/LT1tCJdsZJEBXGPm9FFra2JhbBzYMGWFTgBi8u2VBmx7pQEbwfQIglfED/XG2bBlUOm3Euq4vot8iLn83x3dYkkt2hXzfNOMZUzU+1hhsk3OUbU6dAC8o+Iwu9RBpd9K15XYPW3E0aT79NbTaulpQ/zZbjRGiGet0Lhg2nMtBETlHQMzX0wKqsl8Dd08cQVQqkECJxAQC76GIAzJJbVoV7OFbyAJ1Ga5n+Rhzg753l6YydkpIpjQsLSo18cXPbNZgQ20LjtcvbetbLrAIIO47bazv5oM4rYDmtKxdDlH1eqvd9KdFSbbBIMW3HMSC2PjhDtklD5qbQ2oWmp6C88O5J3/CZMnrgAKsZ4HfUSTD/DSowiHaPIBHv7CBmldV2L3y2dlgHE2bBnnBmtudhvU/uAr04laetoQzErdZ2/fufn5776OQ763F9WOsGDoo9bWfpPRocTC2DhS8t9P8We70WdXvKbdBrU/SzaySNorDdhMGwqv9koDNmB6BEHD72DfVd9nqO+ObjF5vmlGjLNhyxqDZryg0m8lNuJoUpV3DMwDRwu7uRYCIi8mBVW+O7rFKAu9spJatCsEarNcp//XwjHP0LWLntksHa7eW7DCZJsm8mPsnKNqdQqTbQKpBgmcPzYO64VnB3ITVwAFgkq/lRR6uOKuK7F7OBu2DJuO0pINvtXlt+/cfCHf2wvU0tOGQuLU8fiz3Whug9ofzRa+gVsmufbhd7Bvd0e3GOZaCIhwag//yjsGZlwLARH/nmWPaa5i+NP/a2FFz2wWeOIKoO7SDddUgwROwrMDOWEmZ6f3FmDQTUdpSdt3bj5KatGu3FrW2WYL30DwO9g3U668qcWeu95/z7JH6f+1MBzyvb2KwrrKMJOzU6ajtCQFNtC6kwbXzSlX3lS/Z9kjLnpms7hKYcQCG2hdlCtvKje+C7ShjgzDG98FWo3vAi0AAAAAQTEbGYJiNjLDUy0rBMVsZEX0d32Gp1pWx5ZBTwiK2chJu8LRiujv+svZ9OMMT7WsTX6utY4tg57PHJiHURLCShAj2VPTcPR4kkHvYVXXri4U5rU317WYHJaEgwVZmBuCGKkAm9v6LbCayzapXV135hxsbP/fP0HUng5azaIkhJXjFZ+MIEayp2F3qb6m4ejx59Dz6CSD3sNlssXaqq5dXeufRkQozGtvaf1wdq5rMTnvWiogLAkHC204HBLzNkbfsgddxnFUcO0wZWv09/Mqu7bCMaJ1kRyJNKAHkPu8nxe6jYQOed6pJTjvsjz/efNzvkjoan0bxUE8Kt5YBU958ER+YumHLU/CxhxU2wGKFZRAuw6Ng+gjpsLZOL8NxaA4TPS7IY+nlgrOlo0TCQDMXEgx10WLYvpuylPhd1Rdu7oVbKCj1j+NiJcOlpFQmNfeEanMx9L64eyTy/r1XNdich3meWvetVRAn4RPWVgSDhYZIxUP2nA4JJtBIz2na/1l5lrmfCUJy1dkONBOo66RAeKfihghzKczYP28Kq/hJK3u0D+0LYMSn2yyCYarJEjJ6hVT0ClGfvtod2Xi9nk/L7dIJDZ0GwkdNSoSBPK8U0uzjUhScN5leTHvfmD+8+bnv8L9/nyR0NU9oMvM+jaKg7sHkZp4VLyxOWWnqEuYgzsKqZgiyfq1CYjLrhBPXe9fDmz0Rs0/2W2MDsJ0QxJa8wIjQerBcGzBgEF32EfXNpcG5i2OxbUApYSEG7waikFxW7taaJjod0PZ2WxaHk8tFV9+NgycLRsn3RwAPhIAmLlTMYOgkGKui9FTtZIWxfTdV/TvxJSnwu/Vltn26bwHrqiNHLdr3jGcKu8qhe15a8qsSHDTbxtd+C4qRuHhNt5moAfFf2NU6FQiZfNN5fOyAqTCqRtnkYQwJqCfKbiuxeT5n979Oszz1nv96M+8a6mA/VqymT4Jn7J/OISrsCQcLPEVBzUyRioec3cxB7ThcEj10GtRNoNGeneyXWNO1/rLD+bh0sy1zPmNhNfgShKWrwsjjbbIcKCdiUG7hEZdIwMHbDgaxD8VMYUODihCmE9nA6lUfsD6eVWBy2JMH8U4gV70I5idpw6z3JYVqhsAVOVaMU/8mWJi19hTec4XT+FJVn76UJUt13vUHMxiE4qNLVK7ljSR6Lsf0NmgBuzzfl6twmVHbpFIbC+gU3XoNhI6qQcJI2pUJAgrZT8R5HmnlqVIvI9mG5GkJyqKveC8y/KhjdDrYt79wCPv5tm94bwU/NCnDT+DiiZ+spE/uSTQcPgVy2k7RuZCenf9W7VrZdz0Wn7FNwlT7nY4SPexrgm48J8SoTPMP4py/SSTAAAAADdqwgFu1IQDWb5GAtyoCQfrwssGsnyNBIUWTwW4URMOjzvRD9aFlw3h71UMZPkaCVOT2AgKLZ4KPUdcC3CjJhxHyeQdHneiHykdYB6sCy8bm2HtGsLfqxj1tWkZyPI1Ev+Y9xOmJrERkUxzEBRaPBUjMP4Ueo64Fk3kehfgRk041yyPOY6SyTu5+As6PO5EPwuEhj5SOsA8ZVACPVgXXjZvfZw3NsPaNQGpGDSEv1cxs9WVMOpr0zLdAREzkOVrJKePqSX+Me8nyVstJkxNYiN7J6AiIpnmIBXzJCEotHgqH966K0Zg/ClxCj4o9BxxLcN2syyayPUuraI3L8CNmnD351hxrlkec5kz3HIcJZN3K09RdnLxF3RFm9V1eNyJfk+2S38WCA19IWLPfKR0gHmTHkJ4yqAEev3KxnuwLrxsh0R+bd76OG/pkPpubIa1a1vsd2oCUjFoNTjzaQh/r2I/FW1jZqsrYVHB6WDU16Zl471kZLoDImaNaeBnIMvXSBehFUlOH1NLeXWRSvxj3k/LCRxOkrdaTKXdmE2YmsRGr/AGR/ZOQEXBJIJERDLNQXNYD0Aq5klCHYyLQ1Bo8VRnAjNVPrx1VwnWt1aMwPhTu6o6UuIUfFDVfr5R6DniWt9TIFuG7WZZsYekWDSR610D+ylcWkVvXm0vrV+AGzXht3H34O7PseLZpXPjXLM85mvZ/ucyZ7jlBQ165DhKJu8PIOTuVp6i7GH0YO3k4i/o04jt6Yo2q+u9XGnq8LgT/cfS0fyebJf+qQZV/ywQGvobetj7QsSe+XWuXPhI6QDzf4PC8iY9hPARV0bxlEEJ9KMry/X6lY33zf9P9mBdeNlXN7rYDon82jnjPtu89XHei5+z39Ih9d3lSzfc2Axr1+9mqda22O/UgbIt1QSkYtAzzqDRanDm010aJNIQ/l7FJ5ScxH4q2sZJQBjHzFZXwvs8lcOigtPBlegRwKivTcufxY/KxnvJyPERC8l0B0TMQ22GzRrTwM8tuQLOQJavkXf8bZAuQiuSGSjpk5w+pparVGSX8uoilcWA4JT4x7yfz61+npYTOJyhefqdJG+1mBMFd5lKuzGbfdHzmjA1iY0HX0uMXuENjmmLz4/snYCK2/dCi4JJBIm1I8aIiGSag78OWILmsB6A0drcgVTMk4RjplGFOhgXhw1y1Yag0OKpl7ogqM4EZqr5bqSrfHjrrksSKa8SrG+tJcatrBiB8acv6zOmdlV1pEE/t6XEKfig80M6oar9fKOdl76i0HPEtecZBrS+p0C2ic2CtwzbzbI7sQ+zYg9JsVVli7BoIte7X0gVugb2U7gxnJG5tIrevIPgHL3aXlq/7TSYvgAAAABlZ7y4i8gJqu6vtRJXl2KPMvDeN9xfayW5ONed7yi0xYpPCH1k4L1vAYcB17i/1krd2GryM3ff4FYQY1ifVxlQ+jCl6BSfEPpx+KxCyMB7362nx2dDCHJ1Jm/OzXB/rZUVGBEt+7ekP57QGIcn6M8aQo9zoqwgxrDJR3oIPq8yoFvIjhi1ZzsK0ACHsmk4UC8MX+yX4vBZhYeX5T3Rh4ZltOA63VpPj88/KDN3hhDk6uN3WFIN2O1AaL9R+KH4K/DEn5dIKjAiWk9XnuL2b0l/kwj1x32nQNUYwPxtTtCfNSu3I43FGJafoH8qJxlH/bp8IEECko/0EPfoSKg9WBSbWD+oI7aQHTHT96GJas92FA+oyqzhB3++hGDDBtJwoF63FxzmWbip9DzfFUyF58LR4IB+aQ4vy3trSHfDog8Ny8dosXMpxwRhTKC42fWYb0SQ/9P8flBm7hs32lZNJ7kOKEAFtsbvsKSjiAwcGrDbgX/XZzmReNIr9B9ukwP3JjtmkJqDiD8vke1YkylUYES0MQf4DN+oTR66z/Gm7N+S/om4LkZnF5tUAnAn7LtI8HHeL0zJMID521XnRWOcoD9r+ceD0xdoNsFyD4p5yzdd5K5Q4VxA/1ROJZjo9nOIi64W7zcW+ECCBJ0nPrwkH+khQXhVma/X4IvKsFwzO7ZZ7V7R5VWwflBH1Rns/2whO2IJRofa5+kyyIKOjnDUnu0osflRkF9W5II6MVg6gwmPp+ZuMx8IwYYNbaY6taThQL3BhvwFLylJF0pO9a/zdiIylhGeini+K5gd2ZcgS8n0eC6uSMDAAf3SpWZBahxelvd5OSpPl5afXfLxI+UFGWtNYH7X9Y7RYufrtt5fUo4JwjfptXrZRgBovCG80Oox34iPVmMwYfnWIgSeapq9pr0H2MEBvzZutK1TCQgVmk5yHf8pzqURhnu3dOHHD83ZEJKovqwqRhEZOCN2pYB1ZsbYEAF6YP6uz3KbyXPKIvGkV0eWGO+pOa39zF4RRQbuTXZjifHOjSZE3OhB+GRReS/5NB6TQdqxJlO/1prr6cb5s4yhRQtiDvAZB2lMob5RmzzbNieENZmSllD+Li6ZuVQm/N7onhJxXYx3FuE0zi42qatJihFF5j8DIIGDu3aR4OMT9lxb/VnpSZg+VfEhBoJsRGE+1KrOi8bPqTd+OEF/1l0mw26ziXZ81u7KxG/WHVkKsaHh5B4U84F5qEvXacsTsg53q1yhwrk5xn4BgP6pnOWZFSQLNqA2blEcjqcWZobCcdo+LN5vLEm505TwgQQJlea4sXtJDaMeLrEbSD7SQy1ZbvvD9tvpppFnUR+psMx6zgx0lGG5ZvEGBd4AAAAAdwcwlu4OYSyZCVG6B23EGXBq9I/pY6U1nmSVow7biDJ53Lik4NXpHpfS2YgJtkwrfrF8vee4LQeQvx2RHbcQZGqwIPLzuXFIhL5B3hra1H1t3eTr9NS1UYPThccTbJhWZGuowP1i+XqKZcnsFAFcT2MGbNn6Dz1jjQgN9TtuIMhMaRBe1WBB5KJncXI8A+TRSwTUR9INhf2lCrVrNbWo+kKymGzbu8nWrLz5QDLYbONF31x13NYNz6vRPVkm2TCsUd4AOsjXUYC/0GEWIbT0tVazxCPPupWZuL2lDygCuJ5fBYgIxgzZsrEL6SQvb3yHWGhMEcFhHau2Zi09dtxBkAHbcQaY0iC879UQKnGxhYkGtrUfn7/kpei41DN4B8miDwD5NJYJqI7hDpgYf2oNuwhtPS2RZGyX5mNcAWtrUfQcbGFihWUw2PJiAE5sBpXtGwGle4II9MH1D8RXZbDZxhK36VCLvrjq/LmIfGLdHd8V2i1JjNN88/vUTGVNsmFYOrVRzqO8AHTUuzDiSt+lQT3Yldek0cRt09b0+0Np6Wo0btn8rWeIRtpguNBEBC1zMwMd5aoKTF/dDXzJUAVxPCcCQaq+CxAQyQwghldotSUgb4WzuWbUCc5h5J9e3vkOKdnJmLDQmCLH16i0WbM9Fy60DYG3vVw7wLpsre24gyCav7O2A7biDHSx0prq1Uc5ndJ3rwTbJhVz3BaD42MLEpRkO4QNbWo+empaqOQOzwuTCf+dCgCuJ30HnrHwD5NEhwij0h4B8mhpBsL+92JXXYBlZ8sZbDZxbmsG5/7UG3aJ0yvgENp6WmfdSsz5ud9vjr7v+Re3vkNgsI7V1taj6KHRk3442MLET9/yUtG7Z/GmvFdnP7UG3UiyNkvYDSvarwobTDYDSvZBBHpg32Dvw6hn31Uxbo7vRmm+ecths4y8ZoMaJW/SoFJo4jbMDHeVuwtHAyICFrlVBSYvxbo7vrK9CygrtFqSXLNqBMLX/6e10M8xLNmei1verh2bZMKw7GPyJnVqo5wCbZMKnAkGqesONj9yB2eFBQBXE5W/SoLiuHoUe7Errgy2GziS0o6b5dW+DXzc77cL298hhtPS1PHU4kJo3bP4H9qDboG+Fs32uSZbb7B34Ri3R3eICFrm/w9qcGYGO8oRAQtcj2We//hirmlha//TFmzPRaAK4njXDdLuTgSDVDkDs8KnZyZh0GAW90lpR00+bnfbrtFqStnWWtxA3wtmN9g78Km8rlPeu57FR7LPfzC1/+m9vfIcyrrCilOzkzAktKOmutA2Bc3XBpNU3lcpI9lnv7Nmei7EYUq4XWgbAipvK5S0C743wwyOoVoF3xstAu+NAAAAABkbMUEyNmKCKy1Tw2RsxQR9d/RFVlqnhk9BlsfI2YoI0cK7Sfrv6Irj9NnLrLVPDLWufk2egy2Oh5gcz0rCElFT2SMQePRw02HvQZIurtdVN7XmFByYtdcFg4SWghuYWZsAqRiwLfrbqTbLmuZ3XV3/bGwc1EE/381aDp6VhCSijJ8V46eyRiC+qXdh8ejhpujz0OfD3oMk2sWyZV1drqpERp/rb2vMKHZw/Wk5MWuuICpa7wsHCSwSHDht30Y288ZdB7LtcFRx9GtlMLsq8/eiMcK2iRyRdZAHoDQXn7z7DoSNuiWp3nk8su84c/N5/2roSL5BxRt9WN4qPPB5TwXpYn5Ewk8th9tUHMaUFYoBjQ67QKYj6IO/ONnCOKDFDSG79EwKlqePE42WzlzMAAlF1zFIbvpii3fhU8q6u11Uo6BsFYiNP9aRlg6X3teYUMfMqRHs4frS9frLk3Ji11xreeYdQFS13llPhJ8WDhJYDxUjGSQ4cNo9I0GbZf1rp3zmWuZXywklTtA4ZAGRrqMYip/iM6fMISq8/WCtJOGvtD/Q7p8Sgy2GCbJsyUgkq9BTFer7fkYp4mV3aC8/efY2JEi3HQkbdAQSKjVLU7zyUkiNs3ll3nBgfu8x5+bz/v79wr/V0JF8zMugPYOKNvqakQe7sbxUeKinZTk7g5hLIpipCgm1+skQrsuIX+9dT0b0bA5t2T/NdMIOjPNaEkPqQSMCwWxwwdh3QYCXNtdHji3mBqUAtcW8G4SEcUGKGmhau1tDd+iYWmzZ2RUtTx4MNn5fJxstnD4AHN25mAASoIMxU4uuYpCStVPR3fTFFsTv9FfvwqeU9tmW1a4HvOm3HI2onDHea4Uq7yrKa3nt03BIrPhdG2/hRiouZt424X/FB6BU6FRjTfNlIgKy8+UbqcKkMISRZymfoCbkxa64/d6f+dbzzDrP6P17gKlrvJmyWv2ynwk+q4Q4fywcJLA1BxXxHipGMgcxd3NIcOG0UWvQ9XpGgzZjXbJ3y/rXTtLh5g/5zLXM4NeEja+WEkq2jSMLnaBwyIS7QYkDI11GGjhsBzEVP8QoDg6FZ0+YQn5UqQNVefrATGLLgYE4xR+YI/Resw6nnaoVltzlVAAb/E8xWtdiYpnOeVPYSeFPF1D6flZ71y2VYswc1C2NihM0lrtSH7vokQag2dBefvPsR2XCrWxIkW51U6AvOhI26CMJB6kIJFRqET9lK5aneeSPvEilpJEbZr2KKifyy7zg69CNocD93mLZ5u8jFLzhvQ2n0PwmioM/P5GyfnDQJLlpyxX4QuZGO1v9d3rcZWu1xX5a9O5TCTf3SDh2uAmusaESn/CKP8wzkyT9cgAAAAABwmo3A4TUbgJGvlkHCajcBsvC6wSNfLIFTxaFDhNRuA/RO48Nl4XWDFXv4Qka+WQI2JNTCp4tCgtcRz0cJqNwHeTJRx+idx4eYB0pGy8LrBrtYZsYq9/CGWm19RI18sgT95j/EbEmphBzTJEVPFoUFP4wIxa4jnoXeuRNOE1G4DmPLNc7yZKOOgv4uT9E7jw+hoQLPMA6Uj0CUGU2XhdYN5x9bzXawzY0GKkBMVe/hDCV1bMy02vqMxEB3SRr5ZAlqY+nJ+8x/iYtW8kjYk1MIqAneyDmmSIhJPMVKni0KCu63h8p/GBGKD4KcS1xHPQss3bDLvXImi83oq1wmo3AcVjn93MeWa5y3DOZd5MlHHZRTyt0F/FyddWbRX6J3Hh/S7ZPfQ0IFnzPYiF5gHSkeEIek3oEoMp7xsr9bLwusG1+RIdvOPrebvqQ6Wu1hmxqd+xbaDFSAmnzODVir38IY20VP2Erq2Zg6cFRZabX1GRkveNmIgO6Z+BpjUjXyyBJFaEXS1MfTkqRdXlP3mP8ThwJy0xat5JNmN2lRsSamEcG8K9FQE72RIIkwUHNMkRAD1hzQknmKkOLjB1U8WhQVTMCZ1d1vD5Wt9YJU/jAjFI6qrtQfBTiUb5+1VriOehbIFPfWWbthlikh7Fd65E0XCn7A15vRVpfrS9t4TUbgOD3cbfisc/u43Ol2eY8s1zn/tlr5bhnMuR6DQXvJko47uQgD+yinlbtYPRh6C/i5OntiNPrqzaK6mlcvf0TuPD80dLH/pdsnv9VBqn6GhAs+9h6G/mexEL4XK518wDpSPLCg3/whD0m8UZXEfQJQZT1yyuj942V+vZP/83ZeF1g2Lo3V9r8iQ7bPuM53nH1vN+zn4vd9SHS3DdL5ddrDNjWqWbv1O/YttUtsoHQYqQE0aDOM9PmcGrSJBpdxV7+EMSclCfG2ip+xxhAScJXVszDlTz7wdOCosAR6JXLTa+oyo/Fn8jJe8bJCxHxzEQHdM2GbUPPwNMazgK5LZGvlkCQbfx3kitCLpPpKBmWpj6cl2RUq5Ui6vKU4IDFn7zH+J5+rc+cOBOWnfp5oZi1bySZdwUTmzG7Sprz0X2NiTUwjEtfB44N4V6Pz4tpioCd7ItC99uJBEmCiMYjtYOaZIiCWA6/gB6w5oHc2tGEk8xUhVGmY4cXGDqG1XINqeLQoKggupeqZgTOq6Ru+a7reHyvKRJLrW+sEqytxiWn8YEYpjPrL6R1VXaltz9BoPgpxKE6Q/OjfP2qor6XnbXEc9C0BhnntkCnvreCzYmyzdsMsw+xO7FJD2Kwi2VVu9ciaLoVSF+4U/YGuZGcMbzeirS9HOCDv1pe2r6YNO0AAAAAuLxnZaoJyIsSta/uj2KXVzfe8DIla1/cndc4ucW0KO99CE+Kb73gZNcBhwFK1r+48mrY3eDfdzNYYxBWUBlXn+ilMPr6EJ8UQqz4cd97wMhnx6etdXIIQ83ObyaVrX9wLREYFT+kt/uHGNCeGs/oJ6Jzj0KwxiCsCHpHyaAyrz4YjshbCjtntbKHANAvUDhpl+xfDIVZ8OI95ZeHZYaH0d064LTPj09adzMoP+rkEIZSWHfjQO3YDfhRv2jwK/ihSJefxFoiMCrinldPf0lv9sf1CJPVQKd9bfzAGDWf0E6NI7crn5YYxScqf6C6/UcZAkEgfBD0j5KoSOj3mxRYPSOoP1gxHZC2iaH30xR2z2qsyqgPvn8H4QbDYIReoHDS5hwXt/SpuFlMFd880cLnhWl+gOB7yy8Ow3dIa8sND6JzsWjHYQTHKdm4oExEb5j1/NP/kO5mUH5W2jcbDrknTbYFQCiksO/GHAyIo4HbsBo5Z9d/K9J4kZNuH/Q7JvcDg5qQZpEvP4gpk1jttERgVAz4BzEeTajfpvHPuv6S3+xGLriJVJsXZ+wncAJx8Ei7yUwv3tv5gDBjRedVaz+gnNODx/nBNmgXeYoPcuRdN8tc4VCuTlT/QPbomCWui4hzFjfvFgSCQPi8PiedIekfJJlVeEGL4NevM1ywyu1ZtjtV5dFeR1B+sP/sGdViOyFs2odGCcgy6edwjo6CKO2e1JBR+bGC5FZfOlgxOqePCYMfM27mDYbBCLU6pm29QOGkBfyGwRdJKS+v9U5KMiJ284qeEZaYK754IJfZHXj0yUvASK4u0v0BwGpBZqX3ll4cTyo5eV2flpflI/HyTWsZBfXXfmDnYtGOX96268IJjlJ6tek3aABG2dC8IbyI3zHqMGNWjyLW+WGaap4EB72mvb8BwdittG42FQgJUx1yTpqlzin/t3uGEQ/H4XSSENnNKqy+qDgZEUaApXYj2MZmdWB6ARByz67+ynPJm1ek8SLvGJZH/a05qUURXsx2Te4GzvGJY9xEJo1k+EHo+S95UUGTHjRTJrHa65rWv7P5xukLRaGMGfAOYqFMaQc8m1G+hCc225aSmTUuLv5QJlS5mZ7o3vyMXXESNOEWd6k2Ls4RikmrAz/mRbuDgSDj4JF2W1z2E0npWf3xVT6YbIIGIdQ+YUTGi86qfjepz9Z/QThuwyZdfHaJs8TK7tZZHdZv4aGxCvMUHuRLqHmBE8tp16t3DrK5wqFcAX7GOZyp/oAkFZnlNqA2C44cUW6GZhanPtpxwixv3iyU07lJCQSB8LG45pWjDUl7G7EuHkPSPkj7blkt6dv2w1FnkabMsKkfdAzOema5YZTeBQbxAAA6JjsmZSZmJmMmYCYiINglyyXZJUImQCZqJmsmPCa6JcQllSE8ILYApwCsJaghkSGTIZIhkCEfIpQhsiW8JSAAIQAiACMAJAAlACYAJwAoACkAKgArACwALQAuAC8AMAAxADIAMwA0ADUANgA3ADgAOQA6ADsAPAA9AD4APwBAAEEAQgBDAEQARQBGAEcASABJAEoASwBMAE0ATgBPAFAAUQBSAFMAVABVAFYAVwBYAFkAWgBbAFwAXQBeAF8AYABhAGIAYwBkAGUAZgBnAGgAaQBqAGsAbABtAG4AbwBwAHEAcgBzAHQAdQB2AHcAeAB5AHoAewB8AH0AfgACI8cA/ADpAOIA5ADgAOUA5wDqAOsA6ADvAO4A7ADEAMUAyQDmAMYA9AD2APIA+wD5AP8A1gDcAKIAowClAKcgkgHhAO0A8wD6APEA0QCqALoAvwAQI6wAvQC8AKEAqwC7AJElkiWTJQIlJCVhJWIlViVVJWMlUSVXJV0lXCVbJRAlFCU0JSwlHCUAJTwlXiVfJVolVCVpJWYlYCVQJWwlZyVoJWQlZSVZJVglUiVTJWslaiUYJQwliCWEJYwlkCWAJbED3wCTA8ADowPDA7UAxAOmA5gDqQO0Ax4ixgO1AykiYSKxAGUiZCIgIyEj9wBIIrAAGSK3ABoifyCyAKAloABBoNkACyYUBAAAtgcAAHoJAACZBQAAWwUAALoFAAAABAAARQUAAM8FAAB6CQBB0dkAC7YQAQIDBAQFBQYGBgYHBwcHCAgICAgICAgJCQkJCQkJCQoKCgoKCgoKCgoKCgoKCgoLCwsLCwsLCwsLCwsLCwsLDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwNDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4PDw8PDw8PDw8PDw8PDw8PDw8PDw8PDw8PDw8PDw8PDw8PDw8PDw8PDw8PDw8PDw8PDw8PDw8PDw8PDw8PDw8PAAAQERISExMUFBQUFRUVFRYWFhYWFhYWFxcXFxcXFxcYGBgYGBgYGBgYGBgYGBgYGRkZGRkZGRkZGRkZGRkZGRoaGhoaGhoaGhoaGhoaGhoaGhoaGhoaGhoaGhoaGhoaGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxscHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHQABAgMEBQYHCAgJCQoKCwsMDAwMDQ0NDQ4ODg4PDw8PEBAQEBAQEBARERERERERERISEhISEhISExMTExMTExMUFBQUFBQUFBQUFBQUFBQUFRUVFRUVFRUVFRUVFRUVFRYWFhYWFhYWFhYWFhYWFhYXFxcXFxcXFxcXFxcXFxcXGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRoaGhoaGhoaGhoaGhoaGhoaGhoaGhoaGhoaGhoaGhoaGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxwQMAAAEDUAAAEBAAAeAQAADwAAAJA0AACQNQAAAAAAAB4AAAAPAAAAAAAAABA2AAAAAAAAEwAAAAcAAAAAAAAADAAIAIwACABMAAgAzAAIACwACACsAAgAbAAIAOwACAAcAAgAnAAIAFwACADcAAgAPAAIALwACAB8AAgA/AAIAAIACACCAAgAQgAIAMIACAAiAAgAogAIAGIACADiAAgAEgAIAJIACABSAAgA0gAIADIACACyAAgAcgAIAPIACAAKAAgAigAIAEoACADKAAgAKgAIAKoACABqAAgA6gAIABoACACaAAgAWgAIANoACAA6AAgAugAIAHoACAD6AAgABgAIAIYACABGAAgAxgAIACYACACmAAgAZgAIAOYACAAWAAgAlgAIAFYACADWAAgANgAIALYACAB2AAgA9gAIAA4ACACOAAgATgAIAM4ACAAuAAgArgAIAG4ACADuAAgAHgAIAJ4ACABeAAgA3gAIAD4ACAC+AAgAfgAIAP4ACAABAAgAgQAIAEEACADBAAgAIQAIAKEACABhAAgA4QAIABEACACRAAgAUQAIANEACAAxAAgAsQAIAHEACADxAAgACQAIAIkACABJAAgAyQAIACkACACpAAgAaQAIAOkACAAZAAgAmQAIAFkACADZAAgAOQAIALkACAB5AAgA+QAIAAUACACFAAgARQAIAMUACAAlAAgApQAIAGUACADlAAgAFQAIAJUACABVAAgA1QAIADUACAC1AAgAdQAIAPUACAANAAgAjQAIAE0ACADNAAgALQAIAK0ACABtAAgA7QAIAB0ACACdAAgAXQAIAN0ACAA9AAgAvQAIAH0ACAD9AAgAEwAJABMBCQCTAAkAkwEJAFMACQBTAQkA0wAJANMBCQAzAAkAMwEJALMACQCzAQkAcwAJAHMBCQDzAAkA8wEJAAsACQALAQkAiwAJAIsBCQBLAAkASwEJAMsACQDLAQkAKwAJACsBCQCrAAkAqwEJAGsACQBrAQkA6wAJAOsBCQAbAAkAGwEJAJsACQCbAQkAWwAJAFsBCQDbAAkA2wEJADsACQA7AQkAuwAJALsBCQB7AAkAewEJAPsACQD7AQkABwAJAAcBCQCHAAkAhwEJAEcACQBHAQkAxwAJAMcBCQAnAAkAJwEJAKcACQCnAQkAZwAJAGcBCQDnAAkA5wEJABcACQAXAQkAlwAJAJcBCQBXAAkAVwEJANcACQDXAQkANwAJADcBCQC3AAkAtwEJAHcACQB3AQkA9wAJAPcBCQAPAAkADwEJAI8ACQCPAQkATwAJAE8BCQDPAAkAzwEJAC8ACQAvAQkArwAJAK8BCQBvAAkAbwEJAO8ACQDvAQkAHwAJAB8BCQCfAAkAnwEJAF8ACQBfAQkA3wAJAN8BCQA/AAkAPwEJAL8ACQC/AQkAfwAJAH8BCQD/AAkA/wEJAAAABwBAAAcAIAAHAGAABwAQAAcAUAAHADAABwBwAAcACAAHAEgABwAoAAcAaAAHABgABwBYAAcAOAAHAHgABwAEAAcARAAHACQABwBkAAcAFAAHAFQABwA0AAcAdAAHAAMACACDAAgAQwAIAMMACAAjAAgAowAIAGMACADjAAgAAAAFABAABQAIAAUAGAAFAAQABQAUAAUADAAFABwABQACAAUAEgAFAAoABQAaAAUABgAFABYABQAOAAUAHgAFAAEABQARAAUACQAFABkABQAFAAUAFQAFAA0ABQAdAAUAAwAFABMABQALAAUAGwAFAAcABQAXAAUAQbDqAAtNAQAAAAEAAAABAAAAAQAAAAIAAAACAAAAAgAAAAIAAAADAAAAAwAAAAMAAAADAAAABAAAAAQAAAAEAAAABAAAAAUAAAAFAAAABQAAAAUAQaDrAAtlAQAAAAEAAAACAAAAAgAAAAMAAAADAAAABAAAAAQAAAAFAAAABQAAAAYAAAAGAAAABwAAAAcAAAAIAAAACAAAAAkAAAAJAAAACgAAAAoAAAALAAAACwAAAAwAAAAMAAAADQAAAA0AQdDsAAsjAgAAAAMAAAAHAAAAAAAAABAREgAIBwkGCgULBAwDDQIOAQ8AQYTtAAtpAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAKAAAADAAAAA4AAAAQAAAAFAAAABgAAAAcAAAAIAAAACgAAAAwAAAAOAAAAEAAAABQAAAAYAAAAHAAAACAAAAAoAAAAMAAAADgAEGE7gALegEAAAACAAAAAwAAAAQAAAAGAAAACAAAAAwAAAAQAAAAGAAAACAAAAAwAAAAQAAAAGAAAACAAAAAwAAAAAABAACAAQAAAAIAAAADAAAABAAAAAYAAAAIAAAADAAAABAAAAAYAAAAIAAAADAAAABAAAAAYAAAMS4yLjExAEGI7wALbQcAAAAEAAQACAAEAAgAAAAEAAUAEAAIAAgAAAAEAAYAIAAgAAgAAAAEAAQAEAAQAAkAAAAIABAAIAAgAAkAAAAIABAAgACAAAkAAAAIACAAgAAAAQkAAAAgAIAAAgEABAkAAAAgAAIBAgEAEAkAQYDwAAulAgMABAAFAAYABwAIAAkACgALAA0ADwARABMAFwAbAB8AIwArADMAOwBDAFMAYwBzAIMAowDDAOMAAgEAAAAAAAAQABAAEAAQABAAEAAQABAAEQARABEAEQASABIAEgASABMAEwATABMAFAAUABQAFAAVABUAFQAVABAATQDKAAAAAQACAAMABAAFAAcACQANABEAGQAhADEAQQBhAIEAwQABAYEBAQIBAwEEAQYBCAEMARABGAEgATABQAFgAAAAABAAEAAQABAAEQARABIAEgATABMAFAAUABUAFQAWABYAFwAXABgAGAAZABkAGgAaABsAGwAcABwAHQAdAEAAQAAQABEAEgAAAAgABwAJAAYACgAFAAsABAAMAAMADQACAA4AAQAPAEGw8gALwRFgBwAAAAhQAAAIEAAUCHMAEgcfAAAIcAAACDAAAAnAABAHCgAACGAAAAggAAAJoAAACAAAAAiAAAAIQAAACeAAEAcGAAAIWAAACBgAAAmQABMHOwAACHgAAAg4AAAJ0AARBxEAAAhoAAAIKAAACbAAAAgIAAAIiAAACEgAAAnwABAHBAAACFQAAAgUABUI4wATBysAAAh0AAAINAAACcgAEQcNAAAIZAAACCQAAAmoAAAIBAAACIQAAAhEAAAJ6AAQBwgAAAhcAAAIHAAACZgAFAdTAAAIfAAACDwAAAnYABIHFwAACGwAAAgsAAAJuAAACAwAAAiMAAAITAAACfgAEAcDAAAIUgAACBIAFQijABMHIwAACHIAAAgyAAAJxAARBwsAAAhiAAAIIgAACaQAAAgCAAAIggAACEIAAAnkABAHBwAACFoAAAgaAAAJlAAUB0MAAAh6AAAIOgAACdQAEgcTAAAIagAACCoAAAm0AAAICgAACIoAAAhKAAAJ9AAQBwUAAAhWAAAIFgBACAAAEwczAAAIdgAACDYAAAnMABEHDwAACGYAAAgmAAAJrAAACAYAAAiGAAAIRgAACewAEAcJAAAIXgAACB4AAAmcABQHYwAACH4AAAg+AAAJ3AASBxsAAAhuAAAILgAACbwAAAgOAAAIjgAACE4AAAn8AGAHAAAACFEAAAgRABUIgwASBx8AAAhxAAAIMQAACcIAEAcKAAAIYQAACCEAAAmiAAAIAQAACIEAAAhBAAAJ4gAQBwYAAAhZAAAIGQAACZIAEwc7AAAIeQAACDkAAAnSABEHEQAACGkAAAgpAAAJsgAACAkAAAiJAAAISQAACfIAEAcEAAAIVQAACBUAEAgCARMHKwAACHUAAAg1AAAJygARBw0AAAhlAAAIJQAACaoAAAgFAAAIhQAACEUAAAnqABAHCAAACF0AAAgdAAAJmgAUB1MAAAh9AAAIPQAACdoAEgcXAAAIbQAACC0AAAm6AAAIDQAACI0AAAhNAAAJ+gAQBwMAAAhTAAAIEwAVCMMAEwcjAAAIcwAACDMAAAnGABEHCwAACGMAAAgjAAAJpgAACAMAAAiDAAAIQwAACeYAEAcHAAAIWwAACBsAAAmWABQHQwAACHsAAAg7AAAJ1gASBxMAAAhrAAAIKwAACbYAAAgLAAAIiwAACEsAAAn2ABAHBQAACFcAAAgXAEAIAAATBzMAAAh3AAAINwAACc4AEQcPAAAIZwAACCcAAAmuAAAIBwAACIcAAAhHAAAJ7gAQBwkAAAhfAAAIHwAACZ4AFAdjAAAIfwAACD8AAAneABIHGwAACG8AAAgvAAAJvgAACA8AAAiPAAAITwAACf4AYAcAAAAIUAAACBAAFAhzABIHHwAACHAAAAgwAAAJwQAQBwoAAAhgAAAIIAAACaEAAAgAAAAIgAAACEAAAAnhABAHBgAACFgAAAgYAAAJkQATBzsAAAh4AAAIOAAACdEAEQcRAAAIaAAACCgAAAmxAAAICAAACIgAAAhIAAAJ8QAQBwQAAAhUAAAIFAAVCOMAEwcrAAAIdAAACDQAAAnJABEHDQAACGQAAAgkAAAJqQAACAQAAAiEAAAIRAAACekAEAcIAAAIXAAACBwAAAmZABQHUwAACHwAAAg8AAAJ2QASBxcAAAhsAAAILAAACbkAAAgMAAAIjAAACEwAAAn5ABAHAwAACFIAAAgSABUIowATByMAAAhyAAAIMgAACcUAEQcLAAAIYgAACCIAAAmlAAAIAgAACIIAAAhCAAAJ5QAQBwcAAAhaAAAIGgAACZUAFAdDAAAIegAACDoAAAnVABIHEwAACGoAAAgqAAAJtQAACAoAAAiKAAAISgAACfUAEAcFAAAIVgAACBYAQAgAABMHMwAACHYAAAg2AAAJzQARBw8AAAhmAAAIJgAACa0AAAgGAAAIhgAACEYAAAntABAHCQAACF4AAAgeAAAJnQAUB2MAAAh+AAAIPgAACd0AEgcbAAAIbgAACC4AAAm9AAAIDgAACI4AAAhOAAAJ/QBgBwAAAAhRAAAIEQAVCIMAEgcfAAAIcQAACDEAAAnDABAHCgAACGEAAAghAAAJowAACAEAAAiBAAAIQQAACeMAEAcGAAAIWQAACBkAAAmTABMHOwAACHkAAAg5AAAJ0wARBxEAAAhpAAAIKQAACbMAAAgJAAAIiQAACEkAAAnzABAHBAAACFUAAAgVABAIAgETBysAAAh1AAAINQAACcsAEQcNAAAIZQAACCUAAAmrAAAIBQAACIUAAAhFAAAJ6wAQBwgAAAhdAAAIHQAACZsAFAdTAAAIfQAACD0AAAnbABIHFwAACG0AAAgtAAAJuwAACA0AAAiNAAAITQAACfsAEAcDAAAIUwAACBMAFQjDABMHIwAACHMAAAgzAAAJxwARBwsAAAhjAAAIIwAACacAAAgDAAAIgwAACEMAAAnnABAHBwAACFsAAAgbAAAJlwAUB0MAAAh7AAAIOwAACdcAEgcTAAAIawAACCsAAAm3AAAICwAACIsAAAhLAAAJ9wAQBwUAAAhXAAAIFwBACAAAEwczAAAIdwAACDcAAAnPABEHDwAACGcAAAgnAAAJrwAACAcAAAiHAAAIRwAACe8AEAcJAAAIXwAACB8AAAmfABQHYwAACH8AAAg/AAAJ3wASBxsAAAhvAAAILwAACb8AAAgPAAAIjwAACE8AAAn/ABAFAQAXBQEBEwURABsFARARBQUAGQUBBBUFQQAdBQFAEAUDABgFAQIUBSEAHAUBIBIFCQAaBQEIFgWBAEAFAAAQBQIAFwWBARMFGQAbBQEYEQUHABkFAQYVBWEAHQUBYBAFBAAYBQEDFAUxABwFATASBQ0AGgUBDBYFwQBABQAAEQAKABEREQAAAAAFAAAAAAAACQAAAAALAAAAAAAAAAARAA8KERERAwoHAAEACQsLAAAJBgsAAAsABhEAAAAREREAQYGEAQshCwAAAAAAAAAAEQAKChEREQAKAAACAAkLAAAACQALAAALAEG7hAELAQwAQceEAQsVDAAAAAAMAAAAAAkMAAAAAAAMAAAMAEH1hAELAQ4AQYGFAQsVDQAAAAQNAAAAAAkOAAAAAAAOAAAOAEGvhQELARAAQbuFAQseDwAAAAAPAAAAAAkQAAAAAAAQAAAQAAASAAAAEhISAEHyhQELDhIAAAASEhIAAAAAAAAJAEGjhgELAQsAQa+GAQsVCgAAAAAKAAAAAAkLAAAAAAALAAALAEHdhgELAQwAQemGAQsnDAAAAAAMAAAAAAkMAAAAAAAMAAAMAAAwMTIzNDU2Nzg5QUJDREVGAEG0hwELARkAQduHAQsF//////8AQaCIAQtXGRJEOwI/LEcUPTMwChsGRktFNw9JDo4XA0AdPGkrNh9KLRwBICUpIQgMFRYiLhA4Pgs0MRhkdHV2L0EJfzkRI0MyQomKiwUEJignDSoeNYwHGkiTE5SVAEGAiQELig5JbGxlZ2FsIGJ5dGUgc2VxdWVuY2UARG9tYWluIGVycm9yAFJlc3VsdCBub3QgcmVwcmVzZW50YWJsZQBOb3QgYSB0dHkAUGVybWlzc2lvbiBkZW5pZWQAT3BlcmF0aW9uIG5vdCBwZXJtaXR0ZWQATm8gc3VjaCBmaWxlIG9yIGRpcmVjdG9yeQBObyBzdWNoIHByb2Nlc3MARmlsZSBleGlzdHMAVmFsdWUgdG9vIGxhcmdlIGZvciBkYXRhIHR5cGUATm8gc3BhY2UgbGVmdCBvbiBkZXZpY2UAT3V0IG9mIG1lbW9yeQBSZXNvdXJjZSBidXN5AEludGVycnVwdGVkIHN5c3RlbSBjYWxsAFJlc291cmNlIHRlbXBvcmFyaWx5IHVuYXZhaWxhYmxlAEludmFsaWQgc2VlawBDcm9zcy1kZXZpY2UgbGluawBSZWFkLW9ubHkgZmlsZSBzeXN0ZW0ARGlyZWN0b3J5IG5vdCBlbXB0eQBDb25uZWN0aW9uIHJlc2V0IGJ5IHBlZXIAT3BlcmF0aW9uIHRpbWVkIG91dABDb25uZWN0aW9uIHJlZnVzZWQASG9zdCBpcyBkb3duAEhvc3QgaXMgdW5yZWFjaGFibGUAQWRkcmVzcyBpbiB1c2UAQnJva2VuIHBpcGUASS9PIGVycm9yAE5vIHN1Y2ggZGV2aWNlIG9yIGFkZHJlc3MAQmxvY2sgZGV2aWNlIHJlcXVpcmVkAE5vIHN1Y2ggZGV2aWNlAE5vdCBhIGRpcmVjdG9yeQBJcyBhIGRpcmVjdG9yeQBUZXh0IGZpbGUgYnVzeQBFeGVjIGZvcm1hdCBlcnJvcgBJbnZhbGlkIGFyZ3VtZW50AEFyZ3VtZW50IGxpc3QgdG9vIGxvbmcAU3ltYm9saWMgbGluayBsb29wAEZpbGVuYW1lIHRvbyBsb25nAFRvbyBtYW55IG9wZW4gZmlsZXMgaW4gc3lzdGVtAE5vIGZpbGUgZGVzY3JpcHRvcnMgYXZhaWxhYmxlAEJhZCBmaWxlIGRlc2NyaXB0b3IATm8gY2hpbGQgcHJvY2VzcwBCYWQgYWRkcmVzcwBGaWxlIHRvbyBsYXJnZQBUb28gbWFueSBsaW5rcwBObyBsb2NrcyBhdmFpbGFibGUAUmVzb3VyY2UgZGVhZGxvY2sgd291bGQgb2NjdXIAU3RhdGUgbm90IHJlY292ZXJhYmxlAFByZXZpb3VzIG93bmVyIGRpZWQAT3BlcmF0aW9uIGNhbmNlbGVkAEZ1bmN0aW9uIG5vdCBpbXBsZW1lbnRlZABObyBtZXNzYWdlIG9mIGRlc2lyZWQgdHlwZQBJZGVudGlmaWVyIHJlbW92ZWQARGV2aWNlIG5vdCBhIHN0cmVhbQBObyBkYXRhIGF2YWlsYWJsZQBEZXZpY2UgdGltZW91dABPdXQgb2Ygc3RyZWFtcyByZXNvdXJjZXMATGluayBoYXMgYmVlbiBzZXZlcmVkAFByb3RvY29sIGVycm9yAEJhZCBtZXNzYWdlAEZpbGUgZGVzY3JpcHRvciBpbiBiYWQgc3RhdGUATm90IGEgc29ja2V0AERlc3RpbmF0aW9uIGFkZHJlc3MgcmVxdWlyZWQATWVzc2FnZSB0b28gbGFyZ2UAUHJvdG9jb2wgd3JvbmcgdHlwZSBmb3Igc29ja2V0AFByb3RvY29sIG5vdCBhdmFpbGFibGUAUHJvdG9jb2wgbm90IHN1cHBvcnRlZABTb2NrZXQgdHlwZSBub3Qgc3VwcG9ydGVkAE5vdCBzdXBwb3J0ZWQAUHJvdG9jb2wgZmFtaWx5IG5vdCBzdXBwb3J0ZWQAQWRkcmVzcyBmYW1pbHkgbm90IHN1cHBvcnRlZCBieSBwcm90b2NvbABBZGRyZXNzIG5vdCBhdmFpbGFibGUATmV0d29yayBpcyBkb3duAE5ldHdvcmsgdW5yZWFjaGFibGUAQ29ubmVjdGlvbiByZXNldCBieSBuZXR3b3JrAENvbm5lY3Rpb24gYWJvcnRlZABObyBidWZmZXIgc3BhY2UgYXZhaWxhYmxlAFNvY2tldCBpcyBjb25uZWN0ZWQAU29ja2V0IG5vdCBjb25uZWN0ZWQAQ2Fubm90IHNlbmQgYWZ0ZXIgc29ja2V0IHNodXRkb3duAE9wZXJhdGlvbiBhbHJlYWR5IGluIHByb2dyZXNzAE9wZXJhdGlvbiBpbiBwcm9ncmVzcwBTdGFsZSBmaWxlIGhhbmRsZQBSZW1vdGUgSS9PIGVycm9yAFF1b3RhIGV4Y2VlZGVkAE5vIG1lZGl1bSBmb3VuZABXcm9uZyBtZWRpdW0gdHlwZQBObyBlcnJvciBpbmZvcm1hdGlvbgBBkJcBC1JQUFAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABEAAAASAAAACwAAAAwAAAANAAAADgAAAA8AAAAQAAAAEQAAAAEAAAAIAAAAlEsAALRLAEGQmQELAgxQAEHImQELCR8AAADkTAAAAwBB5JkBC4wBLfRRWM+MscBG9rXLKTEDxwRbcDC0Xf0geH+LmthZKVBoSImrp1YDbP+3zYg/1He0K6WjcPG65Kj8QYP92W/hinovLXSWBx8NCV4Ddixw90ClLKdvV0GoqnTfoFhkA0rHxDxTrq9fGAQVseNtKIarDKS/Q/DpUIE5VxZSN/////////////////////8="; if (!isDataURI(wasmBinaryFile)) { wasmBinaryFile = locateFile(wasmBinaryFile); } function getBinary(file) { try { if (file == wasmBinaryFile && wasmBinary) { return new Uint8Array(wasmBinary); } var binary = tryParseAsDataURI(file); if (binary) { return binary; } if (readBinary) { return readBinary(file); } else { throw "sync fetching of the wasm failed: you can preload it to Module['wasmBinary'] manually, or emcc.py will do that for you when generating HTML (but not JS)"; } } catch (err) { abort(err); } } function instantiateSync(file, info) { var instance; var module; var binary; try { binary = getBinary(file); module = new WebAssembly.Module(binary); instance = new WebAssembly.Instance(module, info); } catch (e) { var str = e.toString(); err("failed to compile wasm module: " + str); if (str.includes("imported Memory") || str.includes("memory import")) { err( "Memory size incompatibility issues may be due to changing INITIAL_MEMORY at runtime to something too large. Use ALLOW_MEMORY_GROWTH to allow any size memory (and also make sure not to set INITIAL_MEMORY at runtime to something smaller than it was at compile time)." ); } throw e; } return [instance, module]; } function createWasm() { var info = { a: asmLibraryArg }; function receiveInstance(instance, module) { var exports = instance.exports; Module["asm"] = exports; wasmMemory = Module["asm"]["u"]; updateGlobalBufferAndViews(wasmMemory.buffer); wasmTable = Module["asm"]["za"]; addOnInit(Module["asm"]["v"]); removeRunDependency("wasm-instantiate"); } addRunDependency("wasm-instantiate"); if (Module["instantiateWasm"]) { try { var exports = Module["instantiateWasm"](info, receiveInstance); return exports; } catch (e) { err("Module.instantiateWasm callback failed with error: " + e); return false; } } var result = instantiateSync(wasmBinaryFile, info); receiveInstance(result[0]); return Module["asm"]; } var tempDouble; var tempI64; function callRuntimeCallbacks(callbacks) { while (callbacks.length > 0) { var callback = callbacks.shift(); if (typeof callback == "function") { callback(Module); continue; } var func = callback.func; if (typeof func === "number") { if (callback.arg === undefined) { wasmTable.get(func)(); } else { wasmTable.get(func)(callback.arg); } } else { func(callback.arg === undefined ? null : callback.arg); } } } function _gmtime_r(time, tmPtr) { var date = new Date(HEAP32[time >> 2] * 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(); HEAP32[(tmPtr + 36) >> 2] = 0; HEAP32[(tmPtr + 32) >> 2] = 0; 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; if (!_gmtime_r.GMTString) _gmtime_r.GMTString = allocateUTF8("GMT"); HEAP32[(tmPtr + 40) >> 2] = _gmtime_r.GMTString; return tmPtr; } function ___gmtime_r(a0, a1) { return _gmtime_r(a0, a1); } var PATH = { splitPath: function(filename) { var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; return splitPathRe.exec(filename).slice(1); }, normalizeArray: function(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: function(path) { var isAbsolute = path.charAt(0) === "/", trailingSlash = path.substr(-1) === "/"; path = PATH.normalizeArray( path.split("/").filter(function(p) { return !!p; }), !isAbsolute ).join("/"); if (!path && !isAbsolute) { path = "."; } if (path && trailingSlash) { path += "/"; } return (isAbsolute ? "/" : "") + path; }, dirname: function(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: function(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); }, extname: function(path) { return PATH.splitPath(path)[3]; }, join: function() { var paths = Array.prototype.slice.call(arguments, 0); return PATH.normalize(paths.join("/")); }, join2: function(l, r) { return PATH.normalize(l + "/" + r); } }; function getRandomDevice() { if ( typeof crypto === "object" && typeof crypto["getRandomValues"] === "function" ) { var randomBuffer = new Uint8Array(1); return function() { crypto.getRandomValues(randomBuffer); return randomBuffer[0]; }; } else if (ENVIRONMENT_IS_NODE) { try { var crypto_module = __webpack_require__(6113); return function() { return crypto_module["randomBytes"](1)[0]; }; } catch (e) {} } return function() { abort("randomDevice"); }; } 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.charAt(0) === "/"; } resolvedPath = PATH.normalizeArray( resolvedPath.split("/").filter(function(p) { return !!p; }), !resolvedAbsolute ).join("/"); return (resolvedAbsolute ? "/" : "") + resolvedPath || "."; }, relative: function(from, to) { from = PATH_FS.resolve(from).substr(1); to = PATH_FS.resolve(to).substr(1); function trim(arr) { var start = 0; for (; start < arr.length; start++) { if (arr[start] !== "") break; } var end = arr.length - 1; for (; end >= 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; i < length; i++) { if (fromParts[i] !== toParts[i]) { samePartsLength = i; break; } } var outputParts = []; for (var i = samePartsLength; i < fromParts.length; i++) { outputParts.push(".."); } outputParts = outputParts.concat(toParts.slice(samePartsLength)); return outputParts.join("/"); } }; 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; i < length; i++) { var result; try { result = stream.tty.ops.get_char(stream.tty); } catch (e) { throw new FS.ErrnoError(29); } if (result === undefined && bytesRead === 0) { throw new FS.ErrnoError(6); } if (result === null || result === undefined) break; bytesRead++; buffer[offset + i] = result; } if (bytesRead) { stream.node.timestamp = Date.now(); } return bytesRead; }, write: function(stream, buffer, offset, length, pos) { if (!stream.tty || !stream.tty.ops.put_char) { throw new FS.ErrnoError(60); } try { for (var i = 0; i < length; i++) { stream.tty.ops.put_char(stream.tty, buffer[offset + i]); } } catch (e) { throw new FS.ErrnoError(29); } if (length) { stream.node.timestamp = Date.now(); } return i; } }, default_tty_ops: { get_char: function(tty) { if (!tty.input.length) { var result = null; if (ENVIRONMENT_IS_NODE) { var BUFSIZE = 256; var buf = Buffer.alloc ? Buffer.alloc(BUFSIZE) : new Buffer(BUFSIZE); var bytesRead = 0; try { bytesRead = nodeFS.readSync( process.stdin.fd, buf, 0, BUFSIZE, null ); } catch (e) { if (e.toString().includes("EOF")) bytesRead = 0; else throw e; } if (bytesRead > 0) { result = buf.slice(0, bytesRead).toString("utf-8"); } else { result = null; } } else if ( typeof window != "undefined" && typeof window.prompt == "function" ) { result = window.prompt("Input: "); if (result !== null) { result += "\n"; } } else if (typeof readline == "function") { result = readline(); if (result !== null) { result += "\n"; } } if (!result) { return null; } tty.input = intArrayFromString(result, true); } return tty.input.shift(); }, put_char: function(tty, val) { if (val === null || val === 10) { out(UTF8ArrayToString(tty.output, 0)); tty.output = []; } else { if (val != 0) tty.output.push(val); } }, flush: function(tty) { if (tty.output && tty.output.length > 0) { 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 mmapAlloc(size) { var alignedSize = alignMemory(size, 65536); var ptr = _malloc(alignedSize); while (size < alignedSize) HEAP8[ptr + size++] = 0; return ptr; } 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 < CAPACITY_DOUBLING_MAX ? 2 : 1.125)) >>> 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; i < size; i++) buffer[offset + i] = contents[position + i]; } return size; }, write: function(stream, buffer, offset, length, position, canOwn) { if (buffer.buffer === HEAP8.buffer) { canOwn = false; } if (!length) return 0; var node = stream.node; node.timestamp = Date.now(); if (buffer.subarray && (!node.contents || node.contents.subarray)) { if (canOwn) { node.contents = buffer.subarray(offset, offset + length); node.usedBytes = length; return length; } else if (node.usedBytes === 0 && position === 0) { node.contents = buffer.slice(offset, offset + length); node.usedBytes = length; return length; } else if (position + length <= node.usedBytes) { node.contents.set(buffer.subarray(offset, offset + length), position); return length; } } MEMFS.expandFileStorage(node, position + length); if (node.contents.subarray && buffer.subarray) { node.contents.set(buffer.subarray(offset, offset + length), position); } else { for (var i = 0; i < length; i++) { node.contents[position + i] = buffer[offset + i]; } } node.usedBytes = Math.max(node.usedBytes, position + length); return length; }, llseek: function(stream, offset, whence) { var position = offset; if (whence === 1) { position += stream.position; } else if (whence === 2) { if (FS.isFile(stream.node.mode)) { position += stream.node.usedBytes; } } if (position < 0) { throw new FS.ErrnoError(28); } return position; }, allocate: function(stream, offset, length) { MEMFS.expandFileStorage(stream.node, offset + length); stream.node.usedBytes = Math.max(stream.node.usedBytes, offset + length); }, mmap: function(stream, address, length, position, prot, flags) { if (address !== 0) { throw new FS.ErrnoError(28); } if (!FS.isFile(stream.node.mode)) { throw new FS.ErrnoError(43); } var ptr; var allocated; var contents = stream.node.contents; if (!(flags & 2) && contents.buffer === buffer) { allocated = false; ptr = contents.byteOffset; } else { if (position > 0 || position + length < contents.length) { if (contents.subarray) { contents = contents.subarray(position, position + length); } else { contents = Array.prototype.slice.call( contents, position, position + length ); } } allocated = true; ptr = mmapAlloc(length); if (!ptr) { throw new FS.ErrnoError(48); } HEAP8.set(contents, ptr); } return { ptr: ptr, allocated: allocated }; }, msync: function(stream, buffer, offset, length, mmapFlags) { if (!FS.isFile(stream.node.mode)) { throw new FS.ErrnoError(43); } if (mmapFlags & 2) { return 0; } var bytesWritten = MEMFS.stream_ops.write( stream, buffer, 0, length, offset, false ); return 0; } } }; var 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 }; var NODEFS = { isWindows: false, staticInit: function() { NODEFS.isWindows = !!process.platform.match(/^win/); var flags = { fs: fs.constants }; if (flags["fs"]) { flags = flags["fs"]; } NODEFS.flagsForNodeMap = { 1024: flags["O_APPEND"], 64: flags["O_CREAT"], 128: flags["O_EXCL"], 256: flags["O_NOCTTY"], 0: flags["O_RDONLY"], 2: flags["O_RDWR"], 4096: flags["O_SYNC"], 512: flags["O_TRUNC"], 1: flags["O_WRONLY"] }; }, bufferFrom: function(arrayBuffer) { return Buffer["alloc"] ? Buffer.from(arrayBuffer) : new Buffer(arrayBuffer); }, convertNodeCode: function(e) { var code = e.code; return ERRNO_CODES[code]; }, mount: function(mount) { return NODEFS.createNode(null, "/", NODEFS.getMode(mount.opts.root), 0); }, createNode: function(parent, name, mode, dev) { if (!FS.isDir(mode) && !FS.isFile(mode) && !FS.isLink(mode)) { throw new FS.ErrnoError(28); } var node = FS.createNode(parent, name, mode); node.node_ops = NODEFS.node_ops; node.stream_ops = NODEFS.stream_ops; return node; }, getMode: function(path) { var stat; try { stat = fs.lstatSync(path); if (NODEFS.isWindows) { stat.mode = stat.mode | ((stat.mode & 292) >> 2); } } catch (e) { if (!e.code) throw e; throw new FS.ErrnoError(NODEFS.convertNodeCode(e)); } return stat.mode; }, realPath: function(node) { var parts = []; while (node.parent !== node) { parts.push(node.name); node = node.parent; } parts.push(node.mount.opts.root); parts.reverse(); return PATH.join.apply(null, parts); }, flagsForNode: function(flags) { flags &= ~2097152; flags &= ~2048; flags &= ~32768; flags &= ~524288; var newFlags = 0; for (var k in NODEFS.flagsForNodeMap) { if (flags & k) { newFlags |= NODEFS.flagsForNodeMap[k]; flags ^= k; } } if (!flags) { return newFlags; } else { throw new FS.ErrnoError(28); } }, node_ops: { getattr: function(node) { var path = NODEFS.realPath(node); var stat; try { stat = fs.lstatSync(path); } catch (e) { if (!e.code) throw e; throw new FS.ErrnoError(NODEFS.convertNodeCode(e)); } if (NODEFS.isWindows && !stat.blksize) { stat.blksize = 4096; } if (NODEFS.isWindows && !stat.blocks) { stat.blocks = ((stat.size + stat.blksize - 1) / stat.blksize) | 0; } return { dev: stat.dev, ino: stat.ino, mode: stat.mode, nlink: stat.nlink, uid: stat.uid, gid: stat.gid, rdev: stat.rdev, size: stat.size, atime: stat.atime, mtime: stat.mtime, ctime: stat.ctime, blksize: stat.blksize, blocks: stat.blocks }; }, setattr: function(node, attr) { var path = NODEFS.realPath(node); try { if (attr.mode !== undefined) { fs.chmodSync(path, attr.mode); node.mode = attr.mode; } if (attr.timestamp !== undefined) { var date = new Date(attr.timestamp); fs.utimesSync(path, date, date); } if (attr.size !== undefined) { fs.truncateSync(path, attr.size); } } catch (e) { if (!e.code) throw e; throw new FS.ErrnoError(NODEFS.convertNodeCode(e)); } }, lookup: function(parent, name) { var path = PATH.join2(NODEFS.realPath(parent), name); var mode = NODEFS.getMode(path); return NODEFS.createNode(parent, name, mode); }, mknod: function(parent, name, mode, dev) { var node = NODEFS.createNode(parent, name, mode, dev); var path = NODEFS.realPath(node); try { if (FS.isDir(node.mode)) { fs.mkdirSync(path, node.mode); } else { fs.writeFileSync(path, "", { mode: node.mode }); } } catch (e) { if (!e.code) throw e; throw new FS.ErrnoError(NODEFS.convertNodeCode(e)); } return node; }, rename: function(oldNode, newDir, newName) { var oldPath = NODEFS.realPath(oldNode); var newPath = PATH.join2(NODEFS.realPath(newDir), newName); try { fs.renameSync(oldPath, newPath); } catch (e) { if (!e.code) throw e; throw new FS.ErrnoError(NODEFS.convertNodeCode(e)); } oldNode.name = newName; }, unlink: function(parent, name) { var path = PATH.join2(NODEFS.realPath(parent), name); try { fs.unlinkSync(path); } catch (e) { if (!e.code) throw e; throw new FS.ErrnoError(NODEFS.convertNodeCode(e)); } }, rmdir: function(parent, name) { var path = PATH.join2(NODEFS.realPath(parent), name); try { fs.rmdirSync(path); } catch (e) { if (!e.code) throw e; throw new FS.ErrnoError(NODEFS.convertNodeCode(e)); } }, readdir: function(node) { var path = NODEFS.realPath(node); try { return fs.readdirSync(path); } catch (e) { if (!e.code) throw e; throw new FS.ErrnoError(NODEFS.convertNodeCode(e)); } }, symlink: function(parent, newName, oldPath) { var newPath = PATH.join2(NODEFS.realPath(parent), newName); try { fs.symlinkSync(oldPath, newPath); } catch (e) { if (!e.code) throw e; throw new FS.ErrnoError(NODEFS.convertNodeCode(e)); } }, readlink: function(node) { var path = NODEFS.realPath(node); try { path = fs.readlinkSync(path); path = NODEJS_PATH.relative( NODEJS_PATH.resolve(node.mount.opts.root), path ); return path; } catch (e) { if (!e.code) throw e; throw new FS.ErrnoError(NODEFS.convertNodeCode(e)); } } }, stream_ops: { open: function(stream) { var path = NODEFS.realPath(stream.node); try { if (FS.isFile(stream.node.mode)) { stream.nfd = fs.openSync(path, NODEFS.flagsForNode(stream.flags)); } } catch (e) { if (!e.code) throw e; throw new FS.ErrnoError(NODEFS.convertNodeCode(e)); } }, close: function(stream) { try { if (FS.isFile(stream.node.mode) && stream.nfd) { fs.closeSync(stream.nfd); } } catch (e) { if (!e.code) throw e; throw new FS.ErrnoError(NODEFS.convertNodeCode(e)); } }, read: function(stream, buffer, offset, length, position) { if (length === 0) return 0; try { return fs.readSync( stream.nfd, NODEFS.bufferFrom(buffer.buffer), offset, length, position ); } catch (e) { throw new FS.ErrnoError(NODEFS.convertNodeCode(e)); } }, write: function(stream, buffer, offset, length, position) { try { return fs.writeSync( stream.nfd, NODEFS.bufferFrom(buffer.buffer), offset, length, position ); } catch (e) { throw new FS.ErrnoError(NODEFS.convertNodeCode(e)); } }, llseek: function(stream, offset, whence) { var position = offset; if (whence === 1) { position += stream.position; } else if (whence === 2) { if (FS.isFile(stream.node.mode)) { try { var stat = fs.fstatSync(stream.nfd); position += stat.size; } catch (e) { throw new FS.ErrnoError(NODEFS.convertNodeCode(e)); } } } if (position < 0) { throw new FS.ErrnoError(28); } return position; }, mmap: function(stream, address, length, position, prot, flags) { if (address !== 0) { throw new FS.ErrnoError(28); } if (!FS.isFile(stream.node.mode)) { throw new FS.ErrnoError(43); } var ptr = mmapAlloc(length); NODEFS.stream_ops.read(stream, HEAP8, ptr, length, position); return { ptr: ptr, allocated: true }; }, msync: function(stream, buffer, offset, length, mmapFlags) { if (!FS.isFile(stream.node.mode)) { throw new FS.ErrnoError(43); } if (mmapFlags & 2) { return 0; } var bytesWritten = NODEFS.stream_ops.write( stream, buffer, 0, length, offset, false ); return 0; } } }; var NODERAWFS = { lookupPath: function(path) { return { path: path, node: { mode: NODEFS.getMode(path) } }; }, createStandardStreams: function() { FS.streams[0] = { fd: 0, nfd: 0, position: 0, path: "", flags: 0, tty: true, seekable: false }; for (var i = 1; i < 3; i++) { FS.streams[i] = { fd: i, nfd: i, position: 0, path: "", flags: 577, tty: true, seekable: false }; } }, cwd: function() { return process.cwd(); }, chdir: function() { process.chdir.apply(void 0, arguments); }, mknod: function(path, mode) { if (FS.isDir(path)) { fs.mkdirSync(path, mode); } else { fs.writeFileSync(path, "", { mode: mode }); } }, mkdir: function() { fs.mkdirSync.apply(void 0, arguments); }, symlink: function() { fs.symlinkSync.apply(void 0, arguments); }, rename: function() { fs.renameSync.apply(void 0, arguments); }, rmdir: function() { fs.rmdirSync.apply(void 0, arguments); }, readdir: function() { fs.readdirSync.apply(void 0, arguments); }, unlink: function() { fs.unlinkSync.apply(void 0, arguments); }, readlink: function() { return fs.readlinkSync.apply(void 0, arguments); }, stat: function() { return fs.statSync.apply(void 0, arguments); }, lstat: function() { return fs.lstatSync.apply(void 0, arguments); }, chmod: function() { fs.chmodSync.apply(void 0, arguments); }, fchmod: function() { fs.fchmodSync.apply(void 0, arguments); }, chown: function() { fs.chownSync.apply(void 0, arguments); }, fchown: function() { fs.fchownSync.apply(void 0, arguments); }, truncate: function() { fs.truncateSync.apply(void 0, arguments); }, ftruncate: function(fd, len) { if (len < 0) { throw new FS.ErrnoError(28); } fs.ftruncateSync.apply(void 0, arguments); }, utime: function() { fs.utimesSync.apply(void 0, arguments); }, open: function(path, flags, mode, suggestFD) { if (typeof flags === "string") { flags = VFS.modeStringToFlags(flags); } var nfd = fs.openSync(path, NODEFS.flagsForNode(flags), mode); var fd = suggestFD != null ? suggestFD : FS.nextfd(nfd); var stream = { fd: fd, nfd: nfd, position: 0, path: path, flags: flags, seekable: true }; FS.streams[fd] = stream; return stream; }, close: function(stream) { if (!stream.stream_ops) { fs.closeSync(stream.nfd); } FS.closeStream(stream.fd); }, llseek: function(stream, offset, whence) { if (stream.stream_ops) { return VFS.llseek(stream, offset, whence); } var position = offset; if (whence === 1) { position += stream.position; } else if (whence === 2) { position += fs.fstatSync(stream.nfd).size; } else if (whence !== 0) { throw new FS.ErrnoError(ERRNO_CODES.EINVAL); } if (position < 0) { throw new FS.ErrnoError(ERRNO_CODES.EINVAL); } stream.position = position; return position; }, read: function(stream, buffer, offset, length, position) { if (stream.stream_ops) { return VFS.read(stream, buffer, offset, length, position); } var seeking = typeof position !== "undefined"; if (!seeking && stream.seekable) position = stream.position; var bytesRead = fs.readSync( stream.nfd, NODEFS.bufferFrom(buffer.buffer), offset, length, position ); if (!seeking) stream.position += bytesRead; return bytesRead; }, write: function(stream, buffer, offset, length, position) { if (stream.stream_ops) { return VFS.write(stream, buffer, offset, length, position); } if (stream.flags & +"1024") { FS.llseek(stream, 0, +"2"); } var seeking = typeof position !== "undefined"; if (!seeking && stream.seekable) position = stream.position; var bytesWritten = fs.writeSync( stream.nfd, NODEFS.bufferFrom(buffer.buffer), offset, length, position ); if (!seeking) stream.position += bytesWritten; return bytesWritten; }, allocate: function() { throw new FS.ErrnoError(ERRNO_CODES.EOPNOTSUPP); }, mmap: function(stream, address, length, position, prot, flags) { if (stream.stream_ops) { return VFS.mmap(stream, address, length, position, prot, flags); } if (address !== 0) { throw new FS.ErrnoError(28); } var ptr = mmapAlloc(length); FS.read(stream, HEAP8, ptr, length, position); return { ptr: ptr, allocated: true }; }, msync: function(stream, buffer, offset, length, mmapFlags) { if (stream.stream_ops) { return VFS.msync(stream, buffer, offset, length, mmapFlags); } if (mmapFlags & 2) { return 0; } FS.write(stream, buffer, 0, length, offset); return 0; }, munmap: function() { return 0; }, ioctl: function() { throw new FS.ErrnoError(ERRNO_CODES.ENOTTY); } }; var FS = { root: null, mounts: [], devices: {}, streams: [], nextInode: 1, nameTable: null, currentPath: "/", initialized: false, ignorePermissions: true, trackingDelegate: {}, tracking: { openFlags: { READ: 1, WRITE: 2 } }, ErrnoError: null, genericErrors: {}, filesystems: null, syncFSRequests: 0, lookupPath: function(path, opts) { path = PATH_FS.resolve(FS.cwd(), path); opts = opts || {}; if (!path) return { path: "", node: null }; var defaults = { follow_mount: true, recurse_count: 0 }; for (var key in defaults) { if (opts[key] === undefined) { opts[key] = defaults[key]; } } if (opts.recurse_count > 8) { throw new FS.ErrnoError(32); } var parts = PATH.normalizeArray( path.split("/").filter(function(p) { return !!p; }), false ); var current = FS.root; var current_path = "/"; for (var i = 0; i < parts.length; i++) { var islast = i === parts.length - 1; if (islast && opts.parent) { break; } current = FS.lookupNode(current, parts[i]); current_path = PATH.join2(current_path, parts[i]); if (FS.isMountpoint(current)) { if (!islast || (islast && opts.follow_mount)) { current = current.mounted.root; } } if (!islast || opts.follow) { var count = 0; while (FS.isLink(current.mode)) { var link = FS.readlink(current_path); current_path = PATH_FS.resolve(PATH.dirname(current_path), link); var lookup = FS.lookupPath(current_path, { recurse_count: opts.recurse_count }); current = lookup.node; if (count++ > 40) { throw new FS.ErrnoError(32); } } } } return { path: current_path, node: current }; }, getPath: function(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: function(parentid, name) { var hash = 0; for (var i = 0; i < name.length; i++) { hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0; } return ((parentid + hash) >>> 0) % FS.nameTable.length; }, hashAddNode: function(node) { var hash = FS.hashName(node.parent.id, node.name); node.name_next = FS.nameTable[hash]; FS.nameTable[hash] = node; }, hashRemoveNode: function(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: function(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: function(parent, name, mode, rdev) { var node = new FS.FSNode(parent, name, mode, rdev); FS.hashAddNode(node); return node; }, destroyNode: function(node) { FS.hashRemoveNode(node); }, isRoot: function(node) { return node === node.parent; }, isMountpoint: function(node) { return !!node.mounted; }, isFile: function(mode) { return (mode & 61440) === 32768; }, isDir: function(mode) { return (mode & 61440) === 16384; }, isLink: function(mode) { return (mode & 61440) === 40960; }, isChrdev: function(mode) { return (mode & 61440) === 8192; }, isBlkdev: function(mode) { return (mode & 61440) === 24576; }, isFIFO: function(mode) { return (mode & 61440) === 4096; }, isSocket: function(mode) { return (mode & 49152) === 49152; }, flagModes: { r: 0, "r+": 2, w: 577, "w+": 578, a: 1089, "a+": 1090 }, modeStringToFlags: function(str) { var flags = FS.flagModes[str]; if (typeof flags === "undefined") { throw new Error("Unknown file open mode: " + str); } return flags; }, flagsToPermissionString: function(flag) { var perms = ["r", "w", "rw"][flag & 3]; if (flag & 512) { perms += "w"; } return perms; }, nodePermissions: function(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: function(dir) { var errCode = FS.nodePermissions(dir, "x"); if (errCode) return errCode; if (!dir.node_ops.lookup) return 2; return 0; }, mayCreate: function(dir, name) { try { var node = FS.lookupNode(dir, name); return 20; } catch (e) {} return FS.nodePermissions(dir, "wx"); }, mayDelete: function(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: function(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: function(fd_start, fd_end) { fd_start = fd_start || 0; fd_end = 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: function(fd) { return FS.streams[fd]; }, createStream: function(stream, fd_start, fd_end) { if (!FS.FSStream) { FS.FSStream = function() {}; 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; } } }; } var newStream = new FS.FSStream(); for (var p in stream) { newStream[p] = stream[p]; } stream = newStream; var fd = FS.nextfd(fd_start, fd_end); stream.fd = fd; FS.streams[fd] = stream; return stream; }, closeStream: function(fd) { FS.streams[fd] = null; }, chrdev_stream_ops: { open: function(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: function() { throw new FS.ErrnoError(70); } }, major: function(dev) { return dev >> 8; }, minor: function(dev) { return dev & 255; }, makedev: function(ma, mi) { return (ma << 8) | mi; }, registerDevice: function(dev, ops) { FS.devices[dev] = { stream_ops: ops }; }, getDevice: function(dev) { return FS.devices[dev]; }, getMounts: function(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: function(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(function(mount) { if (!mount.type.syncfs) { return done(null); } mount.type.syncfs(mount, populate, done); }); }, mount: function(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: function(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(function(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: function(parent, name) { return parent.node_ops.lookup(parent, name); }, mknod: function(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: function(path, mode) { mode = mode !== undefined ? mode : 438; mode &= 4095; mode |= 32768; return FS.mknod(path, mode, 0); }, mkdir: function(path, mode) { mode = mode !== undefined ? mode : 511; mode &= 511 | 512; mode |= 16384; return FS.mknod(path, mode, 0); }, mkdirTree: function(path, mode) { var dirs = path.split("/"); var d = ""; for (var i = 0; i < dirs.length; ++i) { if (!dirs[i]) continue; d += "/" + dirs[i]; try { FS.mkdir(d, mode); } catch (e) { if (e.errno != 20) throw e; } } }, mkdev: function(path, mode, dev) { if (typeof dev === "undefined") { dev = mode; mode = 438; } mode |= 8192; return FS.mknod(path, mode, dev); }, symlink: function(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: function(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); } } try { if (FS.trackingDelegate["willMovePath"]) { FS.trackingDelegate["willMovePath"](old_path, new_path); } } catch (e) { err( "FS.trackingDelegate['willMovePath']('" + old_path + "', '" + new_path + "') threw an exception: " + e.message ); } 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); } try { if (FS.trackingDelegate["onMovePath"]) FS.trackingDelegate["onMovePath"](old_path, new_path); } catch (e) { err( "FS.trackingDelegate['onMovePath']('" + old_path + "', '" + new_path + "') threw an exception: " + e.message ); } }, rmdir: function(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); } try { if (FS.trackingDelegate["willDeletePath"]) { FS.trackingDelegate["willDeletePath"](path); } } catch (e) { err( "FS.trackingDelegate['willDeletePath']('" + path + "') threw an exception: " + e.message ); } parent.node_ops.rmdir(parent, name); FS.destroyNode(node); try { if (FS.trackingDelegate["onDeletePath"]) FS.trackingDelegate["onDeletePath"](path); } catch (e) { err( "FS.trackingDelegate['onDeletePath']('" + path + "') threw an exception: " + e.message ); } }, readdir: function(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: function(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, 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); } try { if (FS.trackingDelegate["willDeletePath"]) { FS.trackingDelegate["willDeletePath"](path); } } catch (e) { err( "FS.trackingDelegate['willDeletePath']('" + path + "') threw an exception: " + e.message ); } parent.node_ops.unlink(parent, name); FS.destroyNode(node); try { if (FS.trackingDelegate["onDeletePath"]) FS.trackingDelegate["onDeletePath"](path); } catch (e) { err( "FS.trackingDelegate['onDeletePath']('" + path + "') threw an exception: " + e.message ); } }, readlink: function(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: function(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: function(path) { return FS.stat(path, true); }, chmod: function(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: function(path, mode) { FS.chmod(path, mode, true); }, fchmod: function(fd, mode) { var stream = FS.getStream(fd); if (!stream) { throw new FS.ErrnoError(8); } FS.chmod(stream.node, mode); }, chown: function(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: function(path, uid, gid) { FS.chown(path, uid, gid, true); }, fchown: function(fd, uid, gid) { var stream = FS.getStream(fd); if (!stream) { throw new FS.ErrnoError(8); } FS.chown(stream.node, uid, gid); }, truncate: function(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: function(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: function(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: function(path, flags, mode, fd_start, fd_end) { 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) { 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 }, fd_start, fd_end ); 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; err("FS.trackingDelegate error on read file: " + path); } } try { if (FS.trackingDelegate["onOpenFile"]) { var trackingFlags = 0; if ((flags & 2097155) !== 1) { trackingFlags |= FS.tracking.openFlags.READ; } if ((flags & 2097155) !== 0) { trackingFlags |= FS.tracking.openFlags.WRITE; } FS.trackingDelegate["onOpenFile"](path, trackingFlags); } } catch (e) { err( "FS.trackingDelegate['onOpenFile']('" + path + "', flags) threw an exception: " + e.message ); } return stream; }, close: function(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: function(stream) { return stream.fd === null; }, llseek: function(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: function(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: function(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; try { if (stream.path && FS.trackingDelegate["onWriteToFile"]) FS.trackingDelegate["onWriteToFile"](stream.path); } catch (e) { err( "FS.trackingDelegate['onWriteToFile']('" + stream.path + "') threw an exception: " + e.message ); } return bytesWritten; }, allocate: function(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: function(stream, address, 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, address, length, position, prot, flags ); }, msync: function(stream, buffer, offset, length, mmapFlags) { if (!stream || !stream.stream_ops.msync) { return 0; } return stream.stream_ops.msync(stream, buffer, offset, length, mmapFlags); }, munmap: function(stream) { return 0; }, ioctl: function(stream, cmd, arg) { if (!stream.stream_ops.ioctl) { throw new FS.ErrnoError(59); } return stream.stream_ops.ioctl(stream, cmd, arg); }, readFile: function(path, opts) { opts = 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: function(path, data, opts) { opts = 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: function() { return FS.currentPath; }, chdir: function(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: function() { FS.mkdir("/tmp"); FS.mkdir("/home"); FS.mkdir("/home/web_user"); }, createDefaultDevices: function() { FS.mkdir("/dev"); FS.registerDevice(FS.makedev(1, 3), { read: function() { return 0; }, write: function(stream, buffer, offset, length, pos) { return 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: function() { FS.mkdir("/proc"); var proc_self = FS.mkdir("/proc/self"); FS.mkdir("/proc/self/fd"); FS.mount( { mount: function() { var node = FS.createNode(proc_self, "fd", 16384 | 511, 73); node.node_ops = { lookup: function(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: function() { return stream.path; } } }; ret.parent = ret; return ret; } }; return node; } }, {}, "/proc/self/fd" ); }, createStandardStreams: function() { 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: function() { 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(function(code) { FS.genericErrors[code] = new FS.ErrnoError(code); FS.genericErrors[code].stack = ""; }); }, staticInit: function() { FS.ensureErrnoError(); FS.nameTable = new Array(4096); FS.mount(MEMFS, {}, "/"); FS.createDefaultDirectories(); FS.createDefaultDevices(); FS.createSpecialDirectories(); FS.filesystems = { MEMFS: MEMFS, NODEFS: NODEFS }; }, init: function(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: function() { FS.init.initialized = false; var fflush = Module["_fflush"]; if (fflush) fflush(0); for (var i = 0; i < FS.streams.length; i++) { var stream = FS.streams[i]; if (!stream) { continue; } FS.close(stream); } }, getMode: function(canRead, canWrite) { var mode = 0; if (canRead) mode |= 292 | 73; if (canWrite) mode |= 146; return mode; }, findObject: function(path, dontResolveLastLink) { var ret = FS.analyzePath(path, dontResolveLastLink); if (ret.exists) { return ret.object; } else { return null; } }, analyzePath: function(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: function(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: function(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: function(parent, name, data, canRead, canWrite, canOwn) { var path = name ? PATH.join2( typeof parent === "string" ? parent : FS.getPath(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 < len; ++i) arr[i] = data.charCodeAt(i); data = arr; } FS.chmod(node, mode | 146); var stream = FS.open(node, 577); FS.write(stream, data, 0, data.length, 0, canOwn); FS.close(stream); FS.chmod(node, mode); } return node; }, createDevice: function(parent, name, input, output) { 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: function(stream) { stream.seekable = false; }, close: function(stream) { if (output && output.buffer && output.buffer.length) { output(10); } }, read: function(stream, buffer, offset, length, pos) { var bytesRead = 0; for (var i = 0; i < length; i++) { var result; try { result = input(); } catch (e) { throw new FS.ErrnoError(29); } if (result === undefined && bytesRead === 0) { throw new FS.ErrnoError(6); } if (result === null || result === undefined) break; bytesRead++; buffer[offset + i] = result; } if (bytesRead) { stream.node.timestamp = Date.now(); } return bytesRead; }, write: function(stream, buffer, offset, length, pos) { for (var i = 0; i < length; i++) { try { output(buffer[offset + i]); } catch (e) { throw new FS.ErrnoError(29); } } if (length) { stream.node.timestamp = Date.now(); } return i; } }); return FS.mkdev(path, mode, dev); }, forceLoadFile: function(obj) { 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: function(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 = function(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); if (typeof Uint8Array != "undefined") 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 || []); } else { return intArrayFromString(xhr.responseText || "", true); } }; var lazyArray = this; lazyArray.setDataGetter(function(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(function(key) { var fn = node.stream_ops[key]; stream_ops[key] = function forceLoadLazyFile() { FS.forceLoadFile(node); return fn.apply(null, arguments); }; }); stream_ops.read = function stream_ops_read( stream, buffer, offset, length, position ) { FS.forceLoadFile(node); 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 < size; i++) { buffer[offset + i] = contents[position + i]; } } else { for (var i = 0; i < size; i++) { buffer[offset + i] = contents.get(position + i); } } return size; }; node.stream_ops = stream_ops; return node; }, createPreloadedFile: function( parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish ) { Browser.init(); 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); } var handled = false; Module["preloadPlugins"].forEach(function(plugin) { if (handled) return; if (plugin["canHandle"](fullname)) { plugin["handle"](byteArray, fullname, finish, function() { if (onerror) onerror(); removeRunDependency(dep); }); handled = true; } }); if (!handled) finish(byteArray); } addRunDependency(dep); if (typeof url == "string") { Browser.asyncLoad( url, function(byteArray) { processData(byteArray); }, onerror ); } else { processData(url); } }, indexedDB: function() { return ( window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB ); }, DB_NAME: function() { return "EM_FS_" + window.location.pathname; }, DB_VERSION: 20, DB_STORE_NAME: "FILE_DATA", saveFilesToDB: function(paths, onload, onerror) { onload = onload || function() {}; onerror = onerror || function() {}; var indexedDB = FS.indexedDB(); try { var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION); } catch (e) { return onerror(e); } openRequest.onupgradeneeded = function openRequest_onupgradeneeded() { out("creating db"); var db = openRequest.result; db.createObjectStore(FS.DB_STORE_NAME); }; openRequest.onsuccess = function 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(function(path) { var putRequest = files.put(FS.analyzePath(path).object.contents, path); putRequest.onsuccess = function putRequest_onsuccess() { ok++; if (ok + fail == total) finish(); }; putRequest.onerror = function putRequest_onerror() { fail++; if (ok + fail == total) finish(); }; }); transaction.onerror = onerror; }; openRequest.onerror = onerror; }, loadFilesFromDB: function(paths, onload, onerror) { onload = onload || function() {}; onerror = onerror || function() {}; 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 = function 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(function(path) { var getRequest = files.get(path); getRequest.onsuccess = function 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 = function getRequest_onerror() { fail++; if (ok + fail == total) finish(); }; }); transaction.onerror = onerror; }; openRequest.onerror = onerror; } }; var SYSCALLS = { mappings: {}, DEFAULT_POLLMASK: 5, umask: 511, calculateAt: function(dirfd, path, allowEmpty) { if (path[0] === "/") { 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 + 4) >> 2] = 0; 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; HEAP32[(buf + 32) >> 2] = 0; (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; HEAP32[(buf + 56) >> 2] = (stat.atime.getTime() / 1e3) | 0; HEAP32[(buf + 60) >> 2] = 0; HEAP32[(buf + 64) >> 2] = (stat.mtime.getTime() / 1e3) | 0; HEAP32[(buf + 68) >> 2] = 0; HEAP32[(buf + 72) >> 2] = (stat.ctime.getTime() / 1e3) | 0; HEAP32[(buf + 76) >> 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 + 80) >> 2] = tempI64[0]), (HEAP32[(buf + 84) >> 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); }, doMkdir: function(path, mode) { path = PATH.normalize(path); if (path[path.length - 1] === "/") path = path.substr(0, path.length - 1); FS.mkdir(path, mode, 0); return 0; }, doMknod: function(path, mode, dev) { switch (mode & 61440) { case 32768: case 8192: case 24576: case 4096: case 49152: break; default: return -28; } FS.mknod(path, mode, dev); return 0; }, doReadlink: function(path, buf, bufsize) { 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; }, doAccess: function(path, amode) { if (amode & ~7) { return -28; } var node; var lookup = FS.lookupPath(path, { follow: true }); 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; }, doDup: function(path, flags, suggestFD) { var suggest = FS.getStream(suggestFD); if (suggest) FS.close(suggest); return FS.open(path, flags, 0, suggestFD, suggestFD).fd; }, doReadv: function(stream, iov, iovcnt, offset) { var ret = 0; for (var i = 0; i < iovcnt; i++) { var ptr = HEAP32[(iov + i * 8) >> 2]; var len = HEAP32[(iov + (i * 8 + 4)) >> 2]; var curr = FS.read(stream, HEAP8, ptr, len, offset); if (curr < 0) return -1; ret += curr; if (curr < len) break; } return ret; }, doWritev: function(stream, iov, iovcnt, offset) { var ret = 0; for (var i = 0; i < iovcnt; i++) { var ptr = HEAP32[(iov + i * 8) >> 2]; var len = HEAP32[(iov + (i * 8 + 4)) >> 2]; var curr = FS.write(stream, HEAP8, ptr, len, offset); if (curr < 0) return -1; ret += curr; } return ret; }, 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; }, get64: function(low, high) { return low; } }; function ___sys_chmod(path, mode) { try { path = SYSCALLS.getStr(path); FS.chmod(path, mode); return 0; } catch (e) { if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); return -e.errno; } } function setErrNo(value) { HEAP32[___errno_location() >> 2] = value; return value; } function ___sys_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.open(stream.path, stream.flags, 0, 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 12: { var arg = SYSCALLS.get(); var offset = 0; HEAP16[(arg + offset) >> 1] = 2; return 0; } case 13: case 14: 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)) abort(e); return -e.errno; } } function ___sys_fstat64(fd, buf) { try { var stream = SYSCALLS.getStreamFromFD(fd); return SYSCALLS.doStat(FS.stat, stream.path, buf); } catch (e) { if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); return -e.errno; } } function ___sys_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: abort("bad ioctl syscall " + op); } } catch (e) { if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); return -e.errno; } } function ___sys_open(path, flags, varargs) { SYSCALLS.varargs = varargs; try { var pathname = SYSCALLS.getStr(path); var mode = varargs ? SYSCALLS.get() : 0; var stream = FS.open(pathname, flags, mode); return stream.fd; } catch (e) { if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); return -e.errno; } } function ___sys_rename(old_path, new_path) { try { old_path = SYSCALLS.getStr(old_path); new_path = SYSCALLS.getStr(new_path); FS.rename(old_path, new_path); return 0; } catch (e) { if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); return -e.errno; } } function ___sys_rmdir(path) { try { path = SYSCALLS.getStr(path); FS.rmdir(path); return 0; } catch (e) { if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); return -e.errno; } } function ___sys_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)) abort(e); return -e.errno; } } function ___sys_unlink(path) { try { path = SYSCALLS.getStr(path); FS.unlink(path); return 0; } catch (e) { if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); return -e.errno; } } 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 = 2147483648; if (requestedSize > maxHeapSize) { return false; } for (var cutDown = 1; cutDown <= 4; cutDown *= 2) { var overGrownHeapSize = oldSize * (1 + 0.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 _fd_close(fd) { try { var stream = SYSCALLS.getStreamFromFD(fd); FS.close(stream); return 0; } catch (e) { if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(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)) abort(e); return e.errno; } } function _fd_read(fd, iov, iovcnt, pnum) { try { var stream = SYSCALLS.getStreamFromFD(fd); var num = SYSCALLS.doReadv(stream, iov, iovcnt); HEAP32[pnum >> 2] = num; return 0; } catch (e) { if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); return e.errno; } } function _fd_seek(fd, offset_low, offset_high, whence, newOffset) { try { var stream = SYSCALLS.getStreamFromFD(fd); var HIGH_OFFSET = 4294967296; var offset = offset_high * HIGH_OFFSET + (offset_low >>> 0); var DOUBLE_LIMIT = 9007199254740992; if (offset <= -DOUBLE_LIMIT || offset >= DOUBLE_LIMIT) { return -61; } 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)) abort(e); return e.errno; } } function _fd_write(fd, iov, iovcnt, pnum) { try { var stream = SYSCALLS.getStreamFromFD(fd); var num = SYSCALLS.doWritev(stream, iov, iovcnt); HEAP32[pnum >> 2] = num; return 0; } catch (e) { if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); return e.errno; } } function _setTempRet0(val) { setTempRet0(val); } function _time(ptr) { var ret = (Date.now() / 1e3) | 0; if (ptr) { HEAP32[ptr >> 2] = ret; } return ret; } function _tzset() { if (_tzset.called) return; _tzset.called = true; 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[__get_timezone() >> 2] = stdTimezoneOffset * 60; HEAP32[__get_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 < winterOffset) { HEAP32[__get_tzname() >> 2] = winterNamePtr; HEAP32[(__get_tzname() + 4) >> 2] = summerNamePtr; } else { HEAP32[__get_tzname() >> 2] = summerNamePtr; HEAP32[(__get_tzname() + 4) >> 2] = winterNamePtr; } } function _timegm(tmPtr) { _tzset(); var time = Date.UTC( HEAP32[(tmPtr + 20) >> 2] + 1900, HEAP32[(tmPtr + 16) >> 2], HEAP32[(tmPtr + 12) >> 2], HEAP32[(tmPtr + 8) >> 2], HEAP32[(tmPtr + 4) >> 2], HEAP32[tmPtr >> 2], 0 ); var date = new Date(time); 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; return (date.getTime() / 1e3) | 0; } 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(); if (ENVIRONMENT_IS_NODE) { var fs = frozenFs; var NODEJS_PATH = __webpack_require__(71017); NODEFS.staticInit(); } if (ENVIRONMENT_IS_NODE) { var _wrapNodeError = function(func) { return function() { try { return func.apply(this, arguments); } catch (e) { if (!e.code) throw e; throw new FS.ErrnoError(ERRNO_CODES[e.code]); } }; }; var VFS = Object.assign({}, FS); for (var _key in NODERAWFS) FS[_key] = _wrapNodeError(NODERAWFS[_key]); } else { throw new Error( "NODERAWFS is currently only supported on Node.js environment." ); } function intArrayFromString(stringy, dontAddNull, length) { var len = length > 0 ? 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 decodeBase64 = typeof atob === "function" ? atob : function(input) { var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); do { enc1 = keyStr.indexOf(input.charAt(i++)); enc2 = keyStr.indexOf(input.charAt(i++)); enc3 = keyStr.indexOf(input.charAt(i++)); enc4 = keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 !== 64) { output = output + String.fromCharCode(chr2); } if (enc4 !== 64) { output = output + String.fromCharCode(chr3); } } while (i < input.length); return output; }; function intArrayFromBase64(s) { if (typeof ENVIRONMENT_IS_NODE === "boolean" && ENVIRONMENT_IS_NODE) { var buf; try { buf = Buffer.from(s, "base64"); } catch (_) { buf = new Buffer(s, "base64"); } return new Uint8Array(buf["buffer"], buf["byteOffset"], buf["byteLength"]); } try { var decoded = decodeBase64(s); var bytes = new Uint8Array(decoded.length); for (var i = 0; i < decoded.length; ++i) { bytes[i] = decoded.charCodeAt(i); } return bytes; } catch (_) { throw new Error("Converting base64 string to bytes failed."); } } function tryParseAsDataURI(filename) { if (!isDataURI(filename)) { return; } return intArrayFromBase64(filename.slice(dataURIPrefix.length)); } var asmLibraryArg = { l: ___gmtime_r, p: ___sys_chmod, e: ___sys_fcntl64, k: ___sys_fstat64, o: ___sys_ioctl, q: ___sys_open, i: ___sys_rename, r: ___sys_rmdir, c: ___sys_stat64, h: ___sys_unlink, s: _emscripten_memcpy_big, t: _emscripten_resize_heap, f: _fd_close, j: _fd_fdstat_get, g: _fd_read, n: _fd_seek, d: _fd_write, a: _setTempRet0, b: _time, m: _timegm }; var asm = createWasm(); var ___wasm_call_ctors = (Module["___wasm_call_ctors"] = asm["v"]); var _zipstruct_stat = (Module["_zipstruct_stat"] = asm["w"]); var _zipstruct_statS = (Module["_zipstruct_statS"] = asm["x"]); var _zipstruct_stat_name = (Module["_zipstruct_stat_name"] = asm["y"]); var _zipstruct_stat_index = (Module["_zipstruct_stat_index"] = asm["z"]); var _zipstruct_stat_size = (Module["_zipstruct_stat_size"] = asm["A"]); var _zipstruct_stat_mtime = (Module["_zipstruct_stat_mtime"] = asm["B"]); var _zipstruct_stat_crc = (Module["_zipstruct_stat_crc"] = asm["C"]); var _zipstruct_error = (Module["_zipstruct_error"] = asm["D"]); var _zipstruct_errorS = (Module["_zipstruct_errorS"] = asm["E"]); var _zipstruct_error_code_zip = (Module["_zipstruct_error_code_zip"] = asm["F"]); var _zipstruct_stat_comp_size = (Module["_zipstruct_stat_comp_size"] = asm["G"]); var _zipstruct_stat_comp_method = (Module["_zipstruct_stat_comp_method"] = asm["H"]); var _zip_close = (Module["_zip_close"] = asm["I"]); var _zip_delete = (Module["_zip_delete"] = asm["J"]); var _zip_dir_add = (Module["_zip_dir_add"] = asm["K"]); var _zip_discard = (Module["_zip_discard"] = asm["L"]); var _zip_error_init_with_code = (Module["_zip_error_init_with_code"] = asm["M"]); var _zip_get_error = (Module["_zip_get_error"] = asm["N"]); var _zip_file_get_error = (Module["_zip_file_get_error"] = asm["O"]); var _zip_error_strerror = (Module["_zip_error_strerror"] = asm["P"]); var _zip_fclose = (Module["_zip_fclose"] = asm["Q"]); var _zip_file_add = (Module["_zip_file_add"] = asm["R"]); var _zip_file_get_external_attributes = (Module[ "_zip_file_get_external_attributes" ] = asm["S"]); var _zip_file_set_external_attributes = (Module[ "_zip_file_set_external_attributes" ] = asm["T"]); var _zip_file_set_mtime = (Module["_zip_file_set_mtime"] = asm["U"]); var _zip_fopen = (Module["_zip_fopen"] = asm["V"]); var _zip_fopen_index = (Module["_zip_fopen_index"] = asm["W"]); var _zip_fread = (Module["_zip_fread"] = asm["X"]); var _zip_get_name = (Module["_zip_get_name"] = asm["Y"]); var _zip_get_num_entries = (Module["_zip_get_num_entries"] = asm["Z"]); var _zip_name_locate = (Module["_zip_name_locate"] = asm["_"]); var _zip_open = (Module["_zip_open"] = asm["$"]); var _zip_open_from_source = (Module["_zip_open_from_source"] = asm["aa"]); var _zip_set_file_compression = (Module["_zip_set_file_compression"] = asm["ba"]); var _zip_source_buffer = (Module["_zip_source_buffer"] = asm["ca"]); var _zip_source_buffer_create = (Module["_zip_source_buffer_create"] = asm["da"]); var _zip_source_close = (Module["_zip_source_close"] = asm["ea"]); var _zip_source_error = (Module["_zip_source_error"] = asm["fa"]); var _zip_source_free = (Module["_zip_source_free"] = asm["ga"]); var _zip_source_keep = (Module["_zip_source_keep"] = asm["ha"]); var _zip_source_open = (Module["_zip_source_open"] = asm["ia"]); var _zip_source_read = (Module["_zip_source_read"] = asm["ja"]); var _zip_source_seek = (Module["_zip_source_seek"] = asm["ka"]); var _zip_source_set_mtime = (Module["_zip_source_set_mtime"] = asm["la"]); var _zip_source_tell = (Module["_zip_source_tell"] = asm["ma"]); var _zip_stat = (Module["_zip_stat"] = asm["na"]); var _zip_stat_index = (Module["_zip_stat_index"] = asm["oa"]); var _zip_ext_count_symlinks = (Module["_zip_ext_count_symlinks"] = asm["pa"]); var ___errno_location = (Module["___errno_location"] = asm["qa"]); var __get_tzname = (Module["__get_tzname"] = asm["ra"]); var __get_daylight = (Module["__get_daylight"] = asm["sa"]); var __get_timezone = (Module["__get_timezone"] = asm["ta"]); var stackSave = (Module["stackSave"] = asm["ua"]); var stackRestore = (Module["stackRestore"] = asm["va"]); var stackAlloc = (Module["stackAlloc"] = asm["wa"]); var _malloc = (Module["_malloc"] = asm["xa"]); var _free = (Module["_free"] = asm["ya"]); Module["cwrap"] = cwrap; Module["getValue"] = getValue; var calledRun; dependenciesFulfilled = function runCaller() { if (!calledRun) run(); if (!calledRun) dependenciesFulfilled = runCaller; }; 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(); if (Module["onRuntimeInitialized"]) Module["onRuntimeInitialized"](); postRun(); } if (Module["setStatus"]) { Module["setStatus"]("Running..."); setTimeout(function() { setTimeout(function() { Module["setStatus"](""); }, 1); doRun(); }, 1); } else { doRun(); } } Module["run"] = run; if (Module["preInit"]) { if (typeof Module["preInit"] == "function") Module["preInit"] = [Module["preInit"]]; while (Module["preInit"].length > 0) { Module["preInit"].pop()(); } } run(); /***/ }), /***/ 86385: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.makeInterface = exports.Errors = void 0; const number64 = [ `number`, `number`, // high ]; var Errors; (function (Errors) { Errors[Errors["ZIP_ER_OK"] = 0] = "ZIP_ER_OK"; Errors[Errors["ZIP_ER_MULTIDISK"] = 1] = "ZIP_ER_MULTIDISK"; Errors[Errors["ZIP_ER_RENAME"] = 2] = "ZIP_ER_RENAME"; Errors[Errors["ZIP_ER_CLOSE"] = 3] = "ZIP_ER_CLOSE"; Errors[Errors["ZIP_ER_SEEK"] = 4] = "ZIP_ER_SEEK"; Errors[Errors["ZIP_ER_READ"] = 5] = "ZIP_ER_READ"; Errors[Errors["ZIP_ER_WRITE"] = 6] = "ZIP_ER_WRITE"; Errors[Errors["ZIP_ER_CRC"] = 7] = "ZIP_ER_CRC"; Errors[Errors["ZIP_ER_ZIPCLOSED"] = 8] = "ZIP_ER_ZIPCLOSED"; Errors[Errors["ZIP_ER_NOENT"] = 9] = "ZIP_ER_NOENT"; Errors[Errors["ZIP_ER_EXISTS"] = 10] = "ZIP_ER_EXISTS"; Errors[Errors["ZIP_ER_OPEN"] = 11] = "ZIP_ER_OPEN"; Errors[Errors["ZIP_ER_TMPOPEN"] = 12] = "ZIP_ER_TMPOPEN"; Errors[Errors["ZIP_ER_ZLIB"] = 13] = "ZIP_ER_ZLIB"; Errors[Errors["ZIP_ER_MEMORY"] = 14] = "ZIP_ER_MEMORY"; Errors[Errors["ZIP_ER_CHANGED"] = 15] = "ZIP_ER_CHANGED"; Errors[Errors["ZIP_ER_COMPNOTSUPP"] = 16] = "ZIP_ER_COMPNOTSUPP"; Errors[Errors["ZIP_ER_EOF"] = 17] = "ZIP_ER_EOF"; Errors[Errors["ZIP_ER_INVAL"] = 18] = "ZIP_ER_INVAL"; Errors[Errors["ZIP_ER_NOZIP"] = 19] = "ZIP_ER_NOZIP"; Errors[Errors["ZIP_ER_INTERNAL"] = 20] = "ZIP_ER_INTERNAL"; Errors[Errors["ZIP_ER_INCONS"] = 21] = "ZIP_ER_INCONS"; Errors[Errors["ZIP_ER_REMOVE"] = 22] = "ZIP_ER_REMOVE"; Errors[Errors["ZIP_ER_DELETED"] = 23] = "ZIP_ER_DELETED"; Errors[Errors["ZIP_ER_ENCRNOTSUPP"] = 24] = "ZIP_ER_ENCRNOTSUPP"; Errors[Errors["ZIP_ER_RDONLY"] = 25] = "ZIP_ER_RDONLY"; Errors[Errors["ZIP_ER_NOPASSWD"] = 26] = "ZIP_ER_NOPASSWD"; Errors[Errors["ZIP_ER_WRONGPASSWD"] = 27] = "ZIP_ER_WRONGPASSWD"; Errors[Errors["ZIP_ER_OPNOTSUPP"] = 28] = "ZIP_ER_OPNOTSUPP"; Errors[Errors["ZIP_ER_INUSE"] = 29] = "ZIP_ER_INUSE"; Errors[Errors["ZIP_ER_TELL"] = 30] = "ZIP_ER_TELL"; Errors[Errors["ZIP_ER_COMPRESSED_DATA"] = 31] = "ZIP_ER_COMPRESSED_DATA"; })(Errors = exports.Errors || (exports.Errors = {})); const makeInterface = (libzip) => ({ // Those are getters because they can change after memory growth get HEAP8() { return libzip.HEAP8; }, get HEAPU8() { return libzip.HEAPU8; }, errors: Errors, SEEK_SET: 0, SEEK_CUR: 1, SEEK_END: 2, ZIP_CHECKCONS: 4, ZIP_CREATE: 1, ZIP_EXCL: 2, ZIP_TRUNCATE: 8, ZIP_RDONLY: 16, ZIP_FL_OVERWRITE: 8192, ZIP_FL_COMPRESSED: 4, ZIP_OPSYS_DOS: 0x00, ZIP_OPSYS_AMIGA: 0x01, ZIP_OPSYS_OPENVMS: 0x02, ZIP_OPSYS_UNIX: 0x03, ZIP_OPSYS_VM_CMS: 0x04, ZIP_OPSYS_ATARI_ST: 0x05, ZIP_OPSYS_OS_2: 0x06, ZIP_OPSYS_MACINTOSH: 0x07, ZIP_OPSYS_Z_SYSTEM: 0x08, ZIP_OPSYS_CPM: 0x09, ZIP_OPSYS_WINDOWS_NTFS: 0x0a, ZIP_OPSYS_MVS: 0x0b, ZIP_OPSYS_VSE: 0x0c, ZIP_OPSYS_ACORN_RISC: 0x0d, ZIP_OPSYS_VFAT: 0x0e, ZIP_OPSYS_ALTERNATE_MVS: 0x0f, ZIP_OPSYS_BEOS: 0x10, ZIP_OPSYS_TANDEM: 0x11, ZIP_OPSYS_OS_400: 0x12, ZIP_OPSYS_OS_X: 0x13, ZIP_CM_DEFAULT: -1, ZIP_CM_STORE: 0, ZIP_CM_DEFLATE: 8, uint08S: libzip._malloc(1), uint16S: libzip._malloc(2), uint32S: libzip._malloc(4), uint64S: libzip._malloc(8), malloc: libzip._malloc, free: libzip._free, getValue: libzip.getValue, open: libzip.cwrap(`zip_open`, `number`, [`string`, `number`, `number`]), openFromSource: libzip.cwrap(`zip_open_from_source`, `number`, [`number`, `number`, `number`]), close: libzip.cwrap(`zip_close`, `number`, [`number`]), discard: libzip.cwrap(`zip_discard`, null, [`number`]), getError: libzip.cwrap(`zip_get_error`, `number`, [`number`]), getName: libzip.cwrap(`zip_get_name`, `string`, [`number`, `number`, `number`]), getNumEntries: libzip.cwrap(`zip_get_num_entries`, `number`, [`number`, `number`]), delete: libzip.cwrap(`zip_delete`, `number`, [`number`, `number`]), stat: libzip.cwrap(`zip_stat`, `number`, [`number`, `string`, `number`, `number`]), statIndex: libzip.cwrap(`zip_stat_index`, `number`, [`number`, ...number64, `number`, `number`]), fopen: libzip.cwrap(`zip_fopen`, `number`, [`number`, `string`, `number`]), fopenIndex: libzip.cwrap(`zip_fopen_index`, `number`, [`number`, ...number64, `number`]), fread: libzip.cwrap(`zip_fread`, `number`, [`number`, `number`, `number`, `number`]), fclose: libzip.cwrap(`zip_fclose`, `number`, [`number`]), dir: { add: libzip.cwrap(`zip_dir_add`, `number`, [`number`, `string`]), }, file: { add: libzip.cwrap(`zip_file_add`, `number`, [`number`, `string`, `number`, `number`]), getError: libzip.cwrap(`zip_file_get_error`, `number`, [`number`]), getExternalAttributes: libzip.cwrap(`zip_file_get_external_attributes`, `number`, [`number`, ...number64, `number`, `number`, `number`]), setExternalAttributes: libzip.cwrap(`zip_file_set_external_attributes`, `number`, [`number`, ...number64, `number`, `number`, `number`]), setMtime: libzip.cwrap(`zip_file_set_mtime`, `number`, [`number`, ...number64, `number`, `number`]), setCompression: libzip.cwrap(`zip_set_file_compression`, `number`, [`number`, ...number64, `number`, `number`]), }, ext: { countSymlinks: libzip.cwrap(`zip_ext_count_symlinks`, `number`, [`number`]), }, error: { initWithCode: libzip.cwrap(`zip_error_init_with_code`, null, [`number`, `number`]), strerror: libzip.cwrap(`zip_error_strerror`, `string`, [`number`]), }, name: { locate: libzip.cwrap(`zip_name_locate`, `number`, [`number`, `string`, `number`]), }, source: { fromUnattachedBuffer: libzip.cwrap(`zip_source_buffer_create`, `number`, [`number`, `number`, `number`, `number`]), fromBuffer: libzip.cwrap(`zip_source_buffer`, `number`, [`number`, `number`, ...number64, `number`]), free: libzip.cwrap(`zip_source_free`, null, [`number`]), keep: libzip.cwrap(`zip_source_keep`, null, [`number`]), open: libzip.cwrap(`zip_source_open`, `number`, [`number`]), close: libzip.cwrap(`zip_source_close`, `number`, [`number`]), seek: libzip.cwrap(`zip_source_seek`, `number`, [`number`, ...number64, `number`]), tell: libzip.cwrap(`zip_source_tell`, `number`, [`number`]), read: libzip.cwrap(`zip_source_read`, `number`, [`number`, `number`, `number`]), error: libzip.cwrap(`zip_source_error`, `number`, [`number`]), setMtime: libzip.cwrap(`zip_source_set_mtime`, `number`, [`number`, `number`]), }, struct: { stat: libzip.cwrap(`zipstruct_stat`, `number`, []), statS: libzip.cwrap(`zipstruct_statS`, `number`, []), statName: libzip.cwrap(`zipstruct_stat_name`, `string`, [`number`]), statIndex: libzip.cwrap(`zipstruct_stat_index`, `number`, [`number`]), statSize: libzip.cwrap(`zipstruct_stat_size`, `number`, [`number`]), statCompSize: libzip.cwrap(`zipstruct_stat_comp_size`, `number`, [`number`]), statCompMethod: libzip.cwrap(`zipstruct_stat_comp_method`, `number`, [`number`]), statMtime: libzip.cwrap(`zipstruct_stat_mtime`, `number`, [`number`]), statCrc: libzip.cwrap(`zipstruct_stat_crc`, `number`, [`number`]), error: libzip.cwrap(`zipstruct_error`, `number`, []), errorS: libzip.cwrap(`zipstruct_errorS`, `number`, []), errorCodeZip: libzip.cwrap(`zipstruct_error_code_zip`, `number`, [`number`]), }, }); exports.makeInterface = makeInterface; /***/ }), /***/ 40364: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getLibzipPromise = exports.getLibzipSync = void 0; const makeInterface_1 = __webpack_require__(86385); let mod = null; function getLibzipSync() { if (mod === null) mod = makeInterface_1.makeInterface(__webpack_require__(7861)); return mod; } exports.getLibzipSync = getLibzipSync; async function getLibzipPromise() { return getLibzipSync(); } exports.getLibzipPromise = getLibzipPromise; /***/ }), /***/ 7615: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __nested_webpack_require_187__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __nested_webpack_require_187__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __nested_webpack_require_187__.m = modules; /******/ /******/ // expose the module cache /******/ __nested_webpack_require_187__.c = installedModules; /******/ /******/ // identity function for calling harmony imports with the correct context /******/ __nested_webpack_require_187__.i = function(value) { return value; }; /******/ /******/ // define getter function for harmony exports /******/ __nested_webpack_require_187__.d = function(exports, name, getter) { /******/ if(!__nested_webpack_require_187__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __nested_webpack_require_187__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __nested_webpack_require_187__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __nested_webpack_require_187__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __nested_webpack_require_187__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __nested_webpack_require_187__(__nested_webpack_require_187__.s = 14); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports) { module.exports = __webpack_require__(71017); /***/ }), /* 1 */ /***/ (function(module, exports, __nested_webpack_require_2716__) { "use strict"; exports.__esModule = true; var _promise = __nested_webpack_require_2716__(173); var _promise2 = _interopRequireDefault(_promise); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function (fn) { return function () { var gen = fn.apply(this, arguments); return new _promise2.default(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return _promise2.default.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }; /***/ }), /* 2 */ /***/ (function(module, exports) { module.exports = __webpack_require__(73837); /***/ }), /* 3 */ /***/ (function(module, exports) { module.exports = __webpack_require__(57147); /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class MessageError extends Error { constructor(msg, code) { super(msg); this.code = code; } } exports.MessageError = MessageError; class ProcessSpawnError extends MessageError { constructor(msg, code, process) { super(msg, code); this.process = process; } } exports.ProcessSpawnError = ProcessSpawnError; class SecurityError extends MessageError {} exports.SecurityError = SecurityError; class ProcessTermError extends MessageError {} exports.ProcessTermError = ProcessTermError; class ResponseError extends Error { constructor(msg, responseCode) { super(msg); this.responseCode = responseCode; } } exports.ResponseError = ResponseError; /***/ }), /* 5 */ /***/ (function(module, exports, __nested_webpack_require_4709__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getFirstSuitableFolder = exports.readFirstAvailableStream = exports.makeTempDir = exports.hardlinksWork = exports.writeFilePreservingEol = exports.getFileSizeOnDisk = exports.walk = exports.symlink = exports.find = exports.readJsonAndFile = exports.readJson = exports.readFileAny = exports.hardlinkBulk = exports.copyBulk = exports.unlink = exports.glob = exports.link = exports.chmod = exports.lstat = exports.exists = exports.mkdirp = exports.stat = exports.access = exports.rename = exports.readdir = exports.realpath = exports.readlink = exports.writeFile = exports.open = exports.readFileBuffer = exports.lockQueue = exports.constants = undefined; var _asyncToGenerator2; function _load_asyncToGenerator() { return _asyncToGenerator2 = _interopRequireDefault(__nested_webpack_require_4709__(1)); } let buildActionsForCopy = (() => { var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, events, possibleExtraneous, reporter) { // let build = (() => { var _ref5 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) { const src = data.src, dest = data.dest, type = data.type; const onFresh = data.onFresh || noop; const onDone = data.onDone || noop; // TODO https://github.com/yarnpkg/yarn/issues/3751 // related to bundled dependencies handling if (files.has(dest.toLowerCase())) { reporter.verbose(`The case-insensitive file ${dest} shouldn't be copied twice in one bulk copy`); } else { files.add(dest.toLowerCase()); } if (type === 'symlink') { yield mkdirp((_path || _load_path()).default.dirname(dest)); onFresh(); actions.symlink.push({ dest, linkname: src }); onDone(); return; } if (events.ignoreBasenames.indexOf((_path || _load_path()).default.basename(src)) >= 0) { // ignored file return; } const srcStat = yield lstat(src); let srcFiles; if (srcStat.isDirectory()) { srcFiles = yield readdir(src); } let destStat; try { // try accessing the destination destStat = yield lstat(dest); } catch (e) { // proceed if destination doesn't exist, otherwise error if (e.code !== 'ENOENT') { throw e; } } // if destination exists if (destStat) { const bothSymlinks = srcStat.isSymbolicLink() && destStat.isSymbolicLink(); const bothFolders = srcStat.isDirectory() && destStat.isDirectory(); const bothFiles = srcStat.isFile() && destStat.isFile(); // EINVAL access errors sometimes happen which shouldn't because node shouldn't be giving // us modes that aren't valid. investigate this, it's generally safe to proceed. /* if (srcStat.mode !== destStat.mode) { try { await access(dest, srcStat.mode); } catch (err) {} } */ if (bothFiles && artifactFiles.has(dest)) { // this file gets changed during build, likely by a custom install script. Don't bother checking it. onDone(); reporter.verbose(reporter.lang('verboseFileSkipArtifact', src)); return; } if (bothFiles && srcStat.size === destStat.size && (0, (_fsNormalized || _load_fsNormalized()).fileDatesEqual)(srcStat.mtime, destStat.mtime)) { // we can safely assume this is the same file onDone(); reporter.verbose(reporter.lang('verboseFileSkip', src, dest, srcStat.size, +srcStat.mtime)); return; } if (bothSymlinks) { const srcReallink = yield readlink(src); if (srcReallink === (yield readlink(dest))) { // if both symlinks are the same then we can continue on onDone(); reporter.verbose(reporter.lang('verboseFileSkipSymlink', src, dest, srcReallink)); return; } } if (bothFolders) { // mark files that aren't in this folder as possibly extraneous const destFiles = yield readdir(dest); invariant(srcFiles, 'src files not initialised'); for (var _iterator4 = destFiles, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) { var _ref6; if (_isArray4) { if (_i4 >= _iterator4.length) break; _ref6 = _iterator4[_i4++]; } else { _i4 = _iterator4.next(); if (_i4.done) break; _ref6 = _i4.value; } const file = _ref6; if (srcFiles.indexOf(file) < 0) { const loc = (_path || _load_path()).default.join(dest, file); possibleExtraneous.add(loc); if ((yield lstat(loc)).isDirectory()) { for (var _iterator5 = yield readdir(loc), _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : _iterator5[Symbol.iterator]();;) { var _ref7; if (_isArray5) { if (_i5 >= _iterator5.length) break; _ref7 = _iterator5[_i5++]; } else { _i5 = _iterator5.next(); if (_i5.done) break; _ref7 = _i5.value; } const file = _ref7; possibleExtraneous.add((_path || _load_path()).default.join(loc, file)); } } } } } } if (destStat && destStat.isSymbolicLink()) { yield (0, (_fsNormalized || _load_fsNormalized()).unlink)(dest); destStat = null; } if (srcStat.isSymbolicLink()) { onFresh(); const linkname = yield readlink(src); actions.symlink.push({ dest, linkname }); onDone(); } else if (srcStat.isDirectory()) { if (!destStat) { reporter.verbose(reporter.lang('verboseFileFolder', dest)); yield mkdirp(dest); } const destParts = dest.split((_path || _load_path()).default.sep); while (destParts.length) { files.add(destParts.join((_path || _load_path()).default.sep).toLowerCase()); destParts.pop(); } // push all files to queue invariant(srcFiles, 'src files not initialised'); let remaining = srcFiles.length; if (!remaining) { onDone(); } for (var _iterator6 = srcFiles, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : _iterator6[Symbol.iterator]();;) { var _ref8; if (_isArray6) { if (_i6 >= _iterator6.length) break; _ref8 = _iterator6[_i6++]; } else { _i6 = _iterator6.next(); if (_i6.done) break; _ref8 = _i6.value; } const file = _ref8; queue.push({ dest: (_path || _load_path()).default.join(dest, file), onFresh, onDone: function (_onDone) { function onDone() { return _onDone.apply(this, arguments); } onDone.toString = function () { return _onDone.toString(); }; return onDone; }(function () { if (--remaining === 0) { onDone(); } }), src: (_path || _load_path()).default.join(src, file) }); } } else if (srcStat.isFile()) { onFresh(); actions.file.push({ src, dest, atime: srcStat.atime, mtime: srcStat.mtime, mode: srcStat.mode }); onDone(); } else { throw new Error(`unsure how to copy this: ${src}`); } }); return function build(_x5) { return _ref5.apply(this, arguments); }; })(); const artifactFiles = new Set(events.artifactFiles || []); const files = new Set(); // initialise events for (var _iterator = queue, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { var _ref2; if (_isArray) { if (_i >= _iterator.length) break; _ref2 = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref2 = _i.value; } const item = _ref2; const onDone = item.onDone; item.onDone = function () { events.onProgress(item.dest); if (onDone) { onDone(); } }; } events.onStart(queue.length); // start building actions const actions = { file: [], symlink: [], link: [] }; // custom concurrency logic as we're always executing stacks of CONCURRENT_QUEUE_ITEMS queue items // at a time due to the requirement to push items onto the queue while (queue.length) { const items = queue.splice(0, CONCURRENT_QUEUE_ITEMS); yield Promise.all(items.map(build)); } // simulate the existence of some files to prevent considering them extraneous for (var _iterator2 = artifactFiles, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { var _ref3; if (_isArray2) { if (_i2 >= _iterator2.length) break; _ref3 = _iterator2[_i2++]; } else { _i2 = _iterator2.next(); if (_i2.done) break; _ref3 = _i2.value; } const file = _ref3; if (possibleExtraneous.has(file)) { reporter.verbose(reporter.lang('verboseFilePhantomExtraneous', file)); possibleExtraneous.delete(file); } } for (var _iterator3 = possibleExtraneous, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) { var _ref4; if (_isArray3) { if (_i3 >= _iterator3.length) break; _ref4 = _iterator3[_i3++]; } else { _i3 = _iterator3.next(); if (_i3.done) break; _ref4 = _i3.value; } const loc = _ref4; if (files.has(loc.toLowerCase())) { possibleExtraneous.delete(loc); } } return actions; }); return function buildActionsForCopy(_x, _x2, _x3, _x4) { return _ref.apply(this, arguments); }; })(); let buildActionsForHardlink = (() => { var _ref9 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, events, possibleExtraneous, reporter) { // let build = (() => { var _ref13 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) { const src = data.src, dest = data.dest; const onFresh = data.onFresh || noop; const onDone = data.onDone || noop; if (files.has(dest.toLowerCase())) { // Fixes issue https://github.com/yarnpkg/yarn/issues/2734 // When bulk hardlinking we have A -> B structure that we want to hardlink to A1 -> B1, // package-linker passes that modules A1 and B1 need to be hardlinked, // the recursive linking algorithm of A1 ends up scheduling files in B1 to be linked twice which will case // an exception. onDone(); return; } files.add(dest.toLowerCase()); if (events.ignoreBasenames.indexOf((_path || _load_path()).default.basename(src)) >= 0) { // ignored file return; } const srcStat = yield lstat(src); let srcFiles; if (srcStat.isDirectory()) { srcFiles = yield readdir(src); } const destExists = yield exists(dest); if (destExists) { const destStat = yield lstat(dest); const bothSymlinks = srcStat.isSymbolicLink() && destStat.isSymbolicLink(); const bothFolders = srcStat.isDirectory() && destStat.isDirectory(); const bothFiles = srcStat.isFile() && destStat.isFile(); if (srcStat.mode !== destStat.mode) { try { yield access(dest, srcStat.mode); } catch (err) { // EINVAL access errors sometimes happen which shouldn't because node shouldn't be giving // us modes that aren't valid. investigate this, it's generally safe to proceed. reporter.verbose(err); } } if (bothFiles && artifactFiles.has(dest)) { // this file gets changed during build, likely by a custom install script. Don't bother checking it. onDone(); reporter.verbose(reporter.lang('verboseFileSkipArtifact', src)); return; } // correct hardlink if (bothFiles && srcStat.ino !== null && srcStat.ino === destStat.ino) { onDone(); reporter.verbose(reporter.lang('verboseFileSkip', src, dest, srcStat.ino)); return; } if (bothSymlinks) { const srcReallink = yield readlink(src); if (srcReallink === (yield readlink(dest))) { // if both symlinks are the same then we can continue on onDone(); reporter.verbose(reporter.lang('verboseFileSkipSymlink', src, dest, srcReallink)); return; } } if (bothFolders) { // mark files that aren't in this folder as possibly extraneous const destFiles = yield readdir(dest); invariant(srcFiles, 'src files not initialised'); for (var _iterator10 = destFiles, _isArray10 = Array.isArray(_iterator10), _i10 = 0, _iterator10 = _isArray10 ? _iterator10 : _iterator10[Symbol.iterator]();;) { var _ref14; if (_isArray10) { if (_i10 >= _iterator10.length) break; _ref14 = _iterator10[_i10++]; } else { _i10 = _iterator10.next(); if (_i10.done) break; _ref14 = _i10.value; } const file = _ref14; if (srcFiles.indexOf(file) < 0) { const loc = (_path || _load_path()).default.join(dest, file); possibleExtraneous.add(loc); if ((yield lstat(loc)).isDirectory()) { for (var _iterator11 = yield readdir(loc), _isArray11 = Array.isArray(_iterator11), _i11 = 0, _iterator11 = _isArray11 ? _iterator11 : _iterator11[Symbol.iterator]();;) { var _ref15; if (_isArray11) { if (_i11 >= _iterator11.length) break; _ref15 = _iterator11[_i11++]; } else { _i11 = _iterator11.next(); if (_i11.done) break; _ref15 = _i11.value; } const file = _ref15; possibleExtraneous.add((_path || _load_path()).default.join(loc, file)); } } } } } } if (srcStat.isSymbolicLink()) { onFresh(); const linkname = yield readlink(src); actions.symlink.push({ dest, linkname }); onDone(); } else if (srcStat.isDirectory()) { reporter.verbose(reporter.lang('verboseFileFolder', dest)); yield mkdirp(dest); const destParts = dest.split((_path || _load_path()).default.sep); while (destParts.length) { files.add(destParts.join((_path || _load_path()).default.sep).toLowerCase()); destParts.pop(); } // push all files to queue invariant(srcFiles, 'src files not initialised'); let remaining = srcFiles.length; if (!remaining) { onDone(); } for (var _iterator12 = srcFiles, _isArray12 = Array.isArray(_iterator12), _i12 = 0, _iterator12 = _isArray12 ? _iterator12 : _iterator12[Symbol.iterator]();;) { var _ref16; if (_isArray12) { if (_i12 >= _iterator12.length) break; _ref16 = _iterator12[_i12++]; } else { _i12 = _iterator12.next(); if (_i12.done) break; _ref16 = _i12.value; } const file = _ref16; queue.push({ onFresh, src: (_path || _load_path()).default.join(src, file), dest: (_path || _load_path()).default.join(dest, file), onDone: function (_onDone2) { function onDone() { return _onDone2.apply(this, arguments); } onDone.toString = function () { return _onDone2.toString(); }; return onDone; }(function () { if (--remaining === 0) { onDone(); } }) }); } } else if (srcStat.isFile()) { onFresh(); actions.link.push({ src, dest, removeDest: destExists }); onDone(); } else { throw new Error(`unsure how to copy this: ${src}`); } }); return function build(_x10) { return _ref13.apply(this, arguments); }; })(); const artifactFiles = new Set(events.artifactFiles || []); const files = new Set(); // initialise events for (var _iterator7 = queue, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : _iterator7[Symbol.iterator]();;) { var _ref10; if (_isArray7) { if (_i7 >= _iterator7.length) break; _ref10 = _iterator7[_i7++]; } else { _i7 = _iterator7.next(); if (_i7.done) break; _ref10 = _i7.value; } const item = _ref10; const onDone = item.onDone || noop; item.onDone = function () { events.onProgress(item.dest); onDone(); }; } events.onStart(queue.length); // start building actions const actions = { file: [], symlink: [], link: [] }; // custom concurrency logic as we're always executing stacks of CONCURRENT_QUEUE_ITEMS queue items // at a time due to the requirement to push items onto the queue while (queue.length) { const items = queue.splice(0, CONCURRENT_QUEUE_ITEMS); yield Promise.all(items.map(build)); } // simulate the existence of some files to prevent considering them extraneous for (var _iterator8 = artifactFiles, _isArray8 = Array.isArray(_iterator8), _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : _iterator8[Symbol.iterator]();;) { var _ref11; if (_isArray8) { if (_i8 >= _iterator8.length) break; _ref11 = _iterator8[_i8++]; } else { _i8 = _iterator8.next(); if (_i8.done) break; _ref11 = _i8.value; } const file = _ref11; if (possibleExtraneous.has(file)) { reporter.verbose(reporter.lang('verboseFilePhantomExtraneous', file)); possibleExtraneous.delete(file); } } for (var _iterator9 = possibleExtraneous, _isArray9 = Array.isArray(_iterator9), _i9 = 0, _iterator9 = _isArray9 ? _iterator9 : _iterator9[Symbol.iterator]();;) { var _ref12; if (_isArray9) { if (_i9 >= _iterator9.length) break; _ref12 = _iterator9[_i9++]; } else { _i9 = _iterator9.next(); if (_i9.done) break; _ref12 = _i9.value; } const loc = _ref12; if (files.has(loc.toLowerCase())) { possibleExtraneous.delete(loc); } } return actions; }); return function buildActionsForHardlink(_x6, _x7, _x8, _x9) { return _ref9.apply(this, arguments); }; })(); let copyBulk = exports.copyBulk = (() => { var _ref17 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, reporter, _events) { const events = { onStart: _events && _events.onStart || noop, onProgress: _events && _events.onProgress || noop, possibleExtraneous: _events ? _events.possibleExtraneous : new Set(), ignoreBasenames: _events && _events.ignoreBasenames || [], artifactFiles: _events && _events.artifactFiles || [] }; const actions = yield buildActionsForCopy(queue, events, events.possibleExtraneous, reporter); events.onStart(actions.file.length + actions.symlink.length + actions.link.length); const fileActions = actions.file; const currentlyWriting = new Map(); yield (_promise || _load_promise()).queue(fileActions, (() => { var _ref18 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) { let writePromise; while (writePromise = currentlyWriting.get(data.dest)) { yield writePromise; } reporter.verbose(reporter.lang('verboseFileCopy', data.src, data.dest)); const copier = (0, (_fsNormalized || _load_fsNormalized()).copyFile)(data, function () { return currentlyWriting.delete(data.dest); }); currentlyWriting.set(data.dest, copier); events.onProgress(data.dest); return copier; }); return function (_x14) { return _ref18.apply(this, arguments); }; })(), CONCURRENT_QUEUE_ITEMS); // we need to copy symlinks last as they could reference files we were copying const symlinkActions = actions.symlink; yield (_promise || _load_promise()).queue(symlinkActions, function (data) { const linkname = (_path || _load_path()).default.resolve((_path || _load_path()).default.dirname(data.dest), data.linkname); reporter.verbose(reporter.lang('verboseFileSymlink', data.dest, linkname)); return symlink(linkname, data.dest); }); }); return function copyBulk(_x11, _x12, _x13) { return _ref17.apply(this, arguments); }; })(); let hardlinkBulk = exports.hardlinkBulk = (() => { var _ref19 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, reporter, _events) { const events = { onStart: _events && _events.onStart || noop, onProgress: _events && _events.onProgress || noop, possibleExtraneous: _events ? _events.possibleExtraneous : new Set(), artifactFiles: _events && _events.artifactFiles || [], ignoreBasenames: [] }; const actions = yield buildActionsForHardlink(queue, events, events.possibleExtraneous, reporter); events.onStart(actions.file.length + actions.symlink.length + actions.link.length); const fileActions = actions.link; yield (_promise || _load_promise()).queue(fileActions, (() => { var _ref20 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) { reporter.verbose(reporter.lang('verboseFileLink', data.src, data.dest)); if (data.removeDest) { yield (0, (_fsNormalized || _load_fsNormalized()).unlink)(data.dest); } yield link(data.src, data.dest); }); return function (_x18) { return _ref20.apply(this, arguments); }; })(), CONCURRENT_QUEUE_ITEMS); // we need to copy symlinks last as they could reference files we were copying const symlinkActions = actions.symlink; yield (_promise || _load_promise()).queue(symlinkActions, function (data) { const linkname = (_path || _load_path()).default.resolve((_path || _load_path()).default.dirname(data.dest), data.linkname); reporter.verbose(reporter.lang('verboseFileSymlink', data.dest, linkname)); return symlink(linkname, data.dest); }); }); return function hardlinkBulk(_x15, _x16, _x17) { return _ref19.apply(this, arguments); }; })(); let readFileAny = exports.readFileAny = (() => { var _ref21 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (files) { for (var _iterator13 = files, _isArray13 = Array.isArray(_iterator13), _i13 = 0, _iterator13 = _isArray13 ? _iterator13 : _iterator13[Symbol.iterator]();;) { var _ref22; if (_isArray13) { if (_i13 >= _iterator13.length) break; _ref22 = _iterator13[_i13++]; } else { _i13 = _iterator13.next(); if (_i13.done) break; _ref22 = _i13.value; } const file = _ref22; if (yield exists(file)) { return readFile(file); } } return null; }); return function readFileAny(_x19) { return _ref21.apply(this, arguments); }; })(); let readJson = exports.readJson = (() => { var _ref23 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (loc) { return (yield readJsonAndFile(loc)).object; }); return function readJson(_x20) { return _ref23.apply(this, arguments); }; })(); let readJsonAndFile = exports.readJsonAndFile = (() => { var _ref24 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (loc) { const file = yield readFile(loc); try { return { object: (0, (_map || _load_map()).default)(JSON.parse(stripBOM(file))), content: file }; } catch (err) { err.message = `${loc}: ${err.message}`; throw err; } }); return function readJsonAndFile(_x21) { return _ref24.apply(this, arguments); }; })(); let find = exports.find = (() => { var _ref25 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (filename, dir) { const parts = dir.split((_path || _load_path()).default.sep); while (parts.length) { const loc = parts.concat(filename).join((_path || _load_path()).default.sep); if (yield exists(loc)) { return loc; } else { parts.pop(); } } return false; }); return function find(_x22, _x23) { return _ref25.apply(this, arguments); }; })(); let symlink = exports.symlink = (() => { var _ref26 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (src, dest) { try { const stats = yield lstat(dest); if (stats.isSymbolicLink()) { const resolved = yield realpath(dest); if (resolved === src) { return; } } } catch (err) { if (err.code !== 'ENOENT') { throw err; } } // We use rimraf for unlink which never throws an ENOENT on missing target yield (0, (_fsNormalized || _load_fsNormalized()).unlink)(dest); if (process.platform === 'win32') { // use directory junctions if possible on win32, this requires absolute paths yield fsSymlink(src, dest, 'junction'); } else { // use relative paths otherwise which will be retained if the directory is moved let relative; try { relative = (_path || _load_path()).default.relative((_fs || _load_fs()).default.realpathSync((_path || _load_path()).default.dirname(dest)), (_fs || _load_fs()).default.realpathSync(src)); } catch (err) { if (err.code !== 'ENOENT') { throw err; } relative = (_path || _load_path()).default.relative((_path || _load_path()).default.dirname(dest), src); } // When path.relative returns an empty string for the current directory, we should instead use // '.', which is a valid fs.symlink target. yield fsSymlink(relative || '.', dest); } }); return function symlink(_x24, _x25) { return _ref26.apply(this, arguments); }; })(); let walk = exports.walk = (() => { var _ref27 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (dir, relativeDir, ignoreBasenames = new Set()) { let files = []; let filenames = yield readdir(dir); if (ignoreBasenames.size) { filenames = filenames.filter(function (name) { return !ignoreBasenames.has(name); }); } for (var _iterator14 = filenames, _isArray14 = Array.isArray(_iterator14), _i14 = 0, _iterator14 = _isArray14 ? _iterator14 : _iterator14[Symbol.iterator]();;) { var _ref28; if (_isArray14) { if (_i14 >= _iterator14.length) break; _ref28 = _iterator14[_i14++]; } else { _i14 = _iterator14.next(); if (_i14.done) break; _ref28 = _i14.value; } const name = _ref28; const relative = relativeDir ? (_path || _load_path()).default.join(relativeDir, name) : name; const loc = (_path || _load_path()).default.join(dir, name); const stat = yield lstat(loc); files.push({ relative, basename: name, absolute: loc, mtime: +stat.mtime }); if (stat.isDirectory()) { files = files.concat((yield walk(loc, relative, ignoreBasenames))); } } return files; }); return function walk(_x26, _x27) { return _ref27.apply(this, arguments); }; })(); let getFileSizeOnDisk = exports.getFileSizeOnDisk = (() => { var _ref29 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (loc) { const stat = yield lstat(loc); const size = stat.size, blockSize = stat.blksize; return Math.ceil(size / blockSize) * blockSize; }); return function getFileSizeOnDisk(_x28) { return _ref29.apply(this, arguments); }; })(); let getEolFromFile = (() => { var _ref30 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (path) { if (!(yield exists(path))) { return undefined; } const buffer = yield readFileBuffer(path); for (let i = 0; i < buffer.length; ++i) { if (buffer[i] === cr) { return '\r\n'; } if (buffer[i] === lf) { return '\n'; } } return undefined; }); return function getEolFromFile(_x29) { return _ref30.apply(this, arguments); }; })(); let writeFilePreservingEol = exports.writeFilePreservingEol = (() => { var _ref31 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (path, data) { const eol = (yield getEolFromFile(path)) || (_os || _load_os()).default.EOL; if (eol !== '\n') { data = data.replace(/\n/g, eol); } yield writeFile(path, data); }); return function writeFilePreservingEol(_x30, _x31) { return _ref31.apply(this, arguments); }; })(); let hardlinksWork = exports.hardlinksWork = (() => { var _ref32 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (dir) { const filename = 'test-file' + Math.random(); const file = (_path || _load_path()).default.join(dir, filename); const fileLink = (_path || _load_path()).default.join(dir, filename + '-link'); try { yield writeFile(file, 'test'); yield link(file, fileLink); } catch (err) { return false; } finally { yield (0, (_fsNormalized || _load_fsNormalized()).unlink)(file); yield (0, (_fsNormalized || _load_fsNormalized()).unlink)(fileLink); } return true; }); return function hardlinksWork(_x32) { return _ref32.apply(this, arguments); }; })(); // not a strict polyfill for Node's fs.mkdtemp let makeTempDir = exports.makeTempDir = (() => { var _ref33 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (prefix) { const dir = (_path || _load_path()).default.join((_os || _load_os()).default.tmpdir(), `yarn-${prefix || ''}-${Date.now()}-${Math.random()}`); yield (0, (_fsNormalized || _load_fsNormalized()).unlink)(dir); yield mkdirp(dir); return dir; }); return function makeTempDir(_x33) { return _ref33.apply(this, arguments); }; })(); let readFirstAvailableStream = exports.readFirstAvailableStream = (() => { var _ref34 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (paths) { for (var _iterator15 = paths, _isArray15 = Array.isArray(_iterator15), _i15 = 0, _iterator15 = _isArray15 ? _iterator15 : _iterator15[Symbol.iterator]();;) { var _ref35; if (_isArray15) { if (_i15 >= _iterator15.length) break; _ref35 = _iterator15[_i15++]; } else { _i15 = _iterator15.next(); if (_i15.done) break; _ref35 = _i15.value; } const path = _ref35; try { const fd = yield open(path, 'r'); return (_fs || _load_fs()).default.createReadStream(path, { fd }); } catch (err) { // Try the next one } } return null; }); return function readFirstAvailableStream(_x34) { return _ref34.apply(this, arguments); }; })(); let getFirstSuitableFolder = exports.getFirstSuitableFolder = (() => { var _ref36 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (paths, mode = constants.W_OK | constants.X_OK) { const result = { skipped: [], folder: null }; for (var _iterator16 = paths, _isArray16 = Array.isArray(_iterator16), _i16 = 0, _iterator16 = _isArray16 ? _iterator16 : _iterator16[Symbol.iterator]();;) { var _ref37; if (_isArray16) { if (_i16 >= _iterator16.length) break; _ref37 = _iterator16[_i16++]; } else { _i16 = _iterator16.next(); if (_i16.done) break; _ref37 = _i16.value; } const folder = _ref37; try { yield mkdirp(folder); yield access(folder, mode); result.folder = folder; return result; } catch (error) { result.skipped.push({ error, folder }); } } return result; }); return function getFirstSuitableFolder(_x35) { return _ref36.apply(this, arguments); }; })(); exports.copy = copy; exports.readFile = readFile; exports.readFileRaw = readFileRaw; exports.normalizeOS = normalizeOS; var _fs; function _load_fs() { return _fs = _interopRequireDefault(__nested_webpack_require_4709__(3)); } var _glob; function _load_glob() { return _glob = _interopRequireDefault(__nested_webpack_require_4709__(75)); } var _os; function _load_os() { return _os = _interopRequireDefault(__nested_webpack_require_4709__(36)); } var _path; function _load_path() { return _path = _interopRequireDefault(__nested_webpack_require_4709__(0)); } var _blockingQueue; function _load_blockingQueue() { return _blockingQueue = _interopRequireDefault(__nested_webpack_require_4709__(84)); } var _promise; function _load_promise() { return _promise = _interopRequireWildcard(__nested_webpack_require_4709__(40)); } var _promise2; function _load_promise2() { return _promise2 = __nested_webpack_require_4709__(40); } var _map; function _load_map() { return _map = _interopRequireDefault(__nested_webpack_require_4709__(20)); } var _fsNormalized; function _load_fsNormalized() { return _fsNormalized = __nested_webpack_require_4709__(164); } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const constants = exports.constants = typeof (_fs || _load_fs()).default.constants !== 'undefined' ? (_fs || _load_fs()).default.constants : { R_OK: (_fs || _load_fs()).default.R_OK, W_OK: (_fs || _load_fs()).default.W_OK, X_OK: (_fs || _load_fs()).default.X_OK }; const lockQueue = exports.lockQueue = new (_blockingQueue || _load_blockingQueue()).default('fs lock'); const readFileBuffer = exports.readFileBuffer = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.readFile); const open = exports.open = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.open); const writeFile = exports.writeFile = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.writeFile); const readlink = exports.readlink = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.readlink); const realpath = exports.realpath = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.realpath); const readdir = exports.readdir = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.readdir); const rename = exports.rename = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.rename); const access = exports.access = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.access); const stat = exports.stat = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.stat); const mkdirp = exports.mkdirp = (0, (_promise2 || _load_promise2()).promisify)(__nested_webpack_require_4709__(116)); const exists = exports.exists = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.exists, true); const lstat = exports.lstat = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.lstat); const chmod = exports.chmod = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.chmod); const link = exports.link = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.link); const glob = exports.glob = (0, (_promise2 || _load_promise2()).promisify)((_glob || _load_glob()).default); exports.unlink = (_fsNormalized || _load_fsNormalized()).unlink; // fs.copyFile uses the native file copying instructions on the system, performing much better // than any JS-based solution and consumes fewer resources. Repeated testing to fine tune the // concurrency level revealed 128 as the sweet spot on a quad-core, 16 CPU Intel system with SSD. const CONCURRENT_QUEUE_ITEMS = (_fs || _load_fs()).default.copyFile ? 128 : 4; const fsSymlink = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.symlink); const invariant = __nested_webpack_require_4709__(7); const stripBOM = __nested_webpack_require_4709__(122); const noop = () => {}; function copy(src, dest, reporter) { return copyBulk([{ src, dest }], reporter); } function _readFile(loc, encoding) { return new Promise((resolve, reject) => { (_fs || _load_fs()).default.readFile(loc, encoding, function (err, content) { if (err) { reject(err); } else { resolve(content); } }); }); } function readFile(loc) { return _readFile(loc, 'utf8').then(normalizeOS); } function readFileRaw(loc) { return _readFile(loc, 'binary'); } function normalizeOS(body) { return body.replace(/\r\n/g, '\n'); } const cr = '\r'.charCodeAt(0); const lf = '\n'.charCodeAt(0); /***/ }), /* 6 */ /***/ (function(module, exports, __nested_webpack_require_44107__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getPathKey = getPathKey; const os = __nested_webpack_require_44107__(36); const path = __nested_webpack_require_44107__(0); const userHome = __nested_webpack_require_44107__(45).default; var _require = __nested_webpack_require_44107__(171); const getCacheDir = _require.getCacheDir, getConfigDir = _require.getConfigDir, getDataDir = _require.getDataDir; const isWebpackBundle = __nested_webpack_require_44107__(227); const DEPENDENCY_TYPES = exports.DEPENDENCY_TYPES = ['devDependencies', 'dependencies', 'optionalDependencies', 'peerDependencies']; const RESOLUTIONS = exports.RESOLUTIONS = 'resolutions'; const MANIFEST_FIELDS = exports.MANIFEST_FIELDS = [RESOLUTIONS, ...DEPENDENCY_TYPES]; const SUPPORTED_NODE_VERSIONS = exports.SUPPORTED_NODE_VERSIONS = '^4.8.0 || ^5.7.0 || ^6.2.2 || >=8.0.0'; const YARN_REGISTRY = exports.YARN_REGISTRY = 'https://registry.yarnpkg.com'; const YARN_DOCS = exports.YARN_DOCS = 'https://yarnpkg.com/en/docs/cli/'; const YARN_INSTALLER_SH = exports.YARN_INSTALLER_SH = 'https://yarnpkg.com/install.sh'; const YARN_INSTALLER_MSI = exports.YARN_INSTALLER_MSI = 'https://yarnpkg.com/latest.msi'; const SELF_UPDATE_VERSION_URL = exports.SELF_UPDATE_VERSION_URL = 'https://yarnpkg.com/latest-version'; // cache version, bump whenever we make backwards incompatible changes const CACHE_VERSION = exports.CACHE_VERSION = 2; // lockfile version, bump whenever we make backwards incompatible changes const LOCKFILE_VERSION = exports.LOCKFILE_VERSION = 1; // max amount of network requests to perform concurrently const NETWORK_CONCURRENCY = exports.NETWORK_CONCURRENCY = 8; // HTTP timeout used when downloading packages const NETWORK_TIMEOUT = exports.NETWORK_TIMEOUT = 30 * 1000; // in milliseconds // max amount of child processes to execute concurrently const CHILD_CONCURRENCY = exports.CHILD_CONCURRENCY = 5; const REQUIRED_PACKAGE_KEYS = exports.REQUIRED_PACKAGE_KEYS = ['name', 'version', '_uid']; function getPreferredCacheDirectories() { const preferredCacheDirectories = [getCacheDir()]; if (process.getuid) { // $FlowFixMe: process.getuid exists, dammit preferredCacheDirectories.push(path.join(os.tmpdir(), `.yarn-cache-${process.getuid()}`)); } preferredCacheDirectories.push(path.join(os.tmpdir(), `.yarn-cache`)); return preferredCacheDirectories; } const PREFERRED_MODULE_CACHE_DIRECTORIES = exports.PREFERRED_MODULE_CACHE_DIRECTORIES = getPreferredCacheDirectories(); const CONFIG_DIRECTORY = exports.CONFIG_DIRECTORY = getConfigDir(); const DATA_DIRECTORY = exports.DATA_DIRECTORY = getDataDir(); const LINK_REGISTRY_DIRECTORY = exports.LINK_REGISTRY_DIRECTORY = path.join(DATA_DIRECTORY, 'link'); const GLOBAL_MODULE_DIRECTORY = exports.GLOBAL_MODULE_DIRECTORY = path.join(DATA_DIRECTORY, 'global'); const NODE_BIN_PATH = exports.NODE_BIN_PATH = process.execPath; const YARN_BIN_PATH = exports.YARN_BIN_PATH = getYarnBinPath(); // Webpack needs to be configured with node.__dirname/__filename = false function getYarnBinPath() { if (isWebpackBundle) { return __filename; } else { return path.join(__dirname, '..', 'bin', 'yarn.js'); } } const NODE_MODULES_FOLDER = exports.NODE_MODULES_FOLDER = 'node_modules'; const NODE_PACKAGE_JSON = exports.NODE_PACKAGE_JSON = 'package.json'; const POSIX_GLOBAL_PREFIX = exports.POSIX_GLOBAL_PREFIX = `${process.env.DESTDIR || ''}/usr/local`; const FALLBACK_GLOBAL_PREFIX = exports.FALLBACK_GLOBAL_PREFIX = path.join(userHome, '.yarn'); const META_FOLDER = exports.META_FOLDER = '.yarn-meta'; const INTEGRITY_FILENAME = exports.INTEGRITY_FILENAME = '.yarn-integrity'; const LOCKFILE_FILENAME = exports.LOCKFILE_FILENAME = 'yarn.lock'; const METADATA_FILENAME = exports.METADATA_FILENAME = '.yarn-metadata.json'; const TARBALL_FILENAME = exports.TARBALL_FILENAME = '.yarn-tarball.tgz'; const CLEAN_FILENAME = exports.CLEAN_FILENAME = '.yarnclean'; const NPM_LOCK_FILENAME = exports.NPM_LOCK_FILENAME = 'package-lock.json'; const NPM_SHRINKWRAP_FILENAME = exports.NPM_SHRINKWRAP_FILENAME = 'npm-shrinkwrap.json'; const DEFAULT_INDENT = exports.DEFAULT_INDENT = ' '; const SINGLE_INSTANCE_PORT = exports.SINGLE_INSTANCE_PORT = 31997; const SINGLE_INSTANCE_FILENAME = exports.SINGLE_INSTANCE_FILENAME = '.yarn-single-instance'; const ENV_PATH_KEY = exports.ENV_PATH_KEY = getPathKey(process.platform, process.env); function getPathKey(platform, env) { let pathKey = 'PATH'; // windows calls its path "Path" usually, but this is not guaranteed. if (platform === 'win32') { pathKey = 'Path'; for (const key in env) { if (key.toLowerCase() === 'path') { pathKey = key; } } } return pathKey; } const VERSION_COLOR_SCHEME = exports.VERSION_COLOR_SCHEME = { major: 'red', premajor: 'red', minor: 'yellow', preminor: 'yellow', patch: 'green', prepatch: 'green', prerelease: 'red', unchanged: 'white', unknown: 'red' }; /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var NODE_ENV = "production"; var invariant = function(condition, format, a, b, c, d, e, f) { if (NODE_ENV !== 'production') { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error( 'Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.' ); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error( format.replace(/%s/g, function() { return args[argIndex++]; }) ); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; module.exports = invariant; /***/ }), /* 8 */, /* 9 */ /***/ (function(module, exports) { module.exports = __webpack_require__(6113); /***/ }), /* 10 */, /* 11 */ /***/ (function(module, exports) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self // eslint-disable-next-line no-new-func : Function('return this')(); if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef /***/ }), /* 12 */ /***/ (function(module, exports, __nested_webpack_require_51177__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.sortAlpha = sortAlpha; exports.entries = entries; exports.removePrefix = removePrefix; exports.removeSuffix = removeSuffix; exports.addSuffix = addSuffix; exports.hyphenate = hyphenate; exports.camelCase = camelCase; exports.compareSortedArrays = compareSortedArrays; exports.sleep = sleep; const _camelCase = __nested_webpack_require_51177__(176); function sortAlpha(a, b) { // sort alphabetically in a deterministic way const shortLen = Math.min(a.length, b.length); for (let i = 0; i < shortLen; i++) { const aChar = a.charCodeAt(i); const bChar = b.charCodeAt(i); if (aChar !== bChar) { return aChar - bChar; } } return a.length - b.length; } function entries(obj) { const entries = []; if (obj) { for (const key in obj) { entries.push([key, obj[key]]); } } return entries; } function removePrefix(pattern, prefix) { if (pattern.startsWith(prefix)) { pattern = pattern.slice(prefix.length); } return pattern; } function removeSuffix(pattern, suffix) { if (pattern.endsWith(suffix)) { return pattern.slice(0, -suffix.length); } return pattern; } function addSuffix(pattern, suffix) { if (!pattern.endsWith(suffix)) { return pattern + suffix; } return pattern; } function hyphenate(str) { return str.replace(/[A-Z]/g, match => { return '-' + match.charAt(0).toLowerCase(); }); } function camelCase(str) { if (/[A-Z]/.test(str)) { return null; } else { return _camelCase(str); } } function compareSortedArrays(array1, array2) { if (array1.length !== array2.length) { return false; } for (let i = 0, len = array1.length; i < len; i++) { if (array1[i] !== array2[i]) { return false; } } return true; } function sleep(ms) { return new Promise(resolve => { setTimeout(resolve, ms); }); } /***/ }), /* 13 */ /***/ (function(module, exports, __nested_webpack_require_53169__) { var store = __nested_webpack_require_53169__(107)('wks'); var uid = __nested_webpack_require_53169__(111); var Symbol = __nested_webpack_require_53169__(11).Symbol; var USE_SYMBOL = typeof Symbol == 'function'; var $exports = module.exports = function (name) { return store[name] || (store[name] = USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); }; $exports.store = store; /***/ }), /* 14 */ /***/ (function(module, exports, __nested_webpack_require_53619__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.stringify = exports.parse = undefined; var _asyncToGenerator2; function _load_asyncToGenerator() { return _asyncToGenerator2 = _interopRequireDefault(__nested_webpack_require_53619__(1)); } var _parse; function _load_parse() { return _parse = __nested_webpack_require_53619__(81); } Object.defineProperty(exports, 'parse', { enumerable: true, get: function get() { return _interopRequireDefault(_parse || _load_parse()).default; } }); var _stringify; function _load_stringify() { return _stringify = __nested_webpack_require_53619__(150); } Object.defineProperty(exports, 'stringify', { enumerable: true, get: function get() { return _interopRequireDefault(_stringify || _load_stringify()).default; } }); exports.implodeEntry = implodeEntry; exports.explodeEntry = explodeEntry; var _misc; function _load_misc() { return _misc = __nested_webpack_require_53619__(12); } var _normalizePattern; function _load_normalizePattern() { return _normalizePattern = __nested_webpack_require_53619__(29); } var _parse2; function _load_parse2() { return _parse2 = _interopRequireDefault(__nested_webpack_require_53619__(81)); } var _constants; function _load_constants() { return _constants = __nested_webpack_require_53619__(6); } var _fs; function _load_fs() { return _fs = _interopRequireWildcard(__nested_webpack_require_53619__(5)); } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const invariant = __nested_webpack_require_53619__(7); const path = __nested_webpack_require_53619__(0); const ssri = __nested_webpack_require_53619__(55); function getName(pattern) { return (0, (_normalizePattern || _load_normalizePattern()).normalizePattern)(pattern).name; } function blankObjectUndefined(obj) { return obj && Object.keys(obj).length ? obj : undefined; } function keyForRemote(remote) { return remote.resolved || (remote.reference && remote.hash ? `${remote.reference}#${remote.hash}` : null); } function serializeIntegrity(integrity) { // We need this because `Integrity.toString()` does not use sorting to ensure a stable string output // See https://git.io/vx2Hy return integrity.toString().split(' ').sort().join(' '); } function implodeEntry(pattern, obj) { const inferredName = getName(pattern); const integrity = obj.integrity ? serializeIntegrity(obj.integrity) : ''; const imploded = { name: inferredName === obj.name ? undefined : obj.name, version: obj.version, uid: obj.uid === obj.version ? undefined : obj.uid, resolved: obj.resolved, registry: obj.registry === 'npm' ? undefined : obj.registry, dependencies: blankObjectUndefined(obj.dependencies), optionalDependencies: blankObjectUndefined(obj.optionalDependencies), permissions: blankObjectUndefined(obj.permissions), prebuiltVariants: blankObjectUndefined(obj.prebuiltVariants) }; if (integrity) { imploded.integrity = integrity; } return imploded; } function explodeEntry(pattern, obj) { obj.optionalDependencies = obj.optionalDependencies || {}; obj.dependencies = obj.dependencies || {}; obj.uid = obj.uid || obj.version; obj.permissions = obj.permissions || {}; obj.registry = obj.registry || 'npm'; obj.name = obj.name || getName(pattern); const integrity = obj.integrity; if (integrity && integrity.isIntegrity) { obj.integrity = ssri.parse(integrity); } return obj; } class Lockfile { constructor({ cache, source, parseResultType } = {}) { this.source = source || ''; this.cache = cache; this.parseResultType = parseResultType; } // source string if the `cache` was parsed // if true, we're parsing an old yarn file and need to update integrity fields hasEntriesExistWithoutIntegrity() { if (!this.cache) { return false; } for (const key in this.cache) { // $FlowFixMe - `this.cache` is clearly defined at this point if (!/^.*@(file:|http)/.test(key) && this.cache[key] && !this.cache[key].integrity) { return true; } } return false; } static fromDirectory(dir, reporter) { return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { // read the manifest in this directory const lockfileLoc = path.join(dir, (_constants || _load_constants()).LOCKFILE_FILENAME); let lockfile; let rawLockfile = ''; let parseResult; if (yield (_fs || _load_fs()).exists(lockfileLoc)) { rawLockfile = yield (_fs || _load_fs()).readFile(lockfileLoc); parseResult = (0, (_parse2 || _load_parse2()).default)(rawLockfile, lockfileLoc); if (reporter) { if (parseResult.type === 'merge') { reporter.info(reporter.lang('lockfileMerged')); } else if (parseResult.type === 'conflict') { reporter.warn(reporter.lang('lockfileConflict')); } } lockfile = parseResult.object; } else if (reporter) { reporter.info(reporter.lang('noLockfileFound')); } return new Lockfile({ cache: lockfile, source: rawLockfile, parseResultType: parseResult && parseResult.type }); })(); } getLocked(pattern) { const cache = this.cache; if (!cache) { return undefined; } const shrunk = pattern in cache && cache[pattern]; if (typeof shrunk === 'string') { return this.getLocked(shrunk); } else if (shrunk) { explodeEntry(pattern, shrunk); return shrunk; } return undefined; } removePattern(pattern) { const cache = this.cache; if (!cache) { return; } delete cache[pattern]; } getLockfile(patterns) { const lockfile = {}; const seen = new Map(); // order by name so that lockfile manifest is assigned to the first dependency with this manifest // the others that have the same remoteKey will just refer to the first // ordering allows for consistency in lockfile when it is serialized const sortedPatternsKeys = Object.keys(patterns).sort((_misc || _load_misc()).sortAlpha); for (var _iterator = sortedPatternsKeys, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } const pattern = _ref; const pkg = patterns[pattern]; const remote = pkg._remote, ref = pkg._reference; invariant(ref, 'Package is missing a reference'); invariant(remote, 'Package is missing a remote'); const remoteKey = keyForRemote(remote); const seenPattern = remoteKey && seen.get(remoteKey); if (seenPattern) { // no point in duplicating it lockfile[pattern] = seenPattern; // if we're relying on our name being inferred and two of the patterns have // different inferred names then we need to set it if (!seenPattern.name && getName(pattern) !== pkg.name) { seenPattern.name = pkg.name; } continue; } const obj = implodeEntry(pattern, { name: pkg.name, version: pkg.version, uid: pkg._uid, resolved: remote.resolved, integrity: remote.integrity, registry: remote.registry, dependencies: pkg.dependencies, peerDependencies: pkg.peerDependencies, optionalDependencies: pkg.optionalDependencies, permissions: ref.permissions, prebuiltVariants: pkg.prebuiltVariants }); lockfile[pattern] = obj; if (remoteKey) { seen.set(remoteKey, obj); } } return lockfile; } } exports.default = Lockfile; /***/ }), /* 15 */, /* 16 */, /* 17 */ /***/ (function(module, exports) { module.exports = __webpack_require__(12781); /***/ }), /* 18 */, /* 19 */, /* 20 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = nullify; function nullify(obj = {}) { if (Array.isArray(obj)) { for (var _iterator = obj, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } const item = _ref; nullify(item); } } else if (obj !== null && typeof obj === 'object' || typeof obj === 'function') { Object.setPrototypeOf(obj, null); // for..in can only be applied to 'object', not 'function' if (typeof obj === 'object') { for (const key in obj) { nullify(obj[key]); } } } return obj; } /***/ }), /* 21 */, /* 22 */ /***/ (function(module, exports) { module.exports = __webpack_require__(39491); /***/ }), /* 23 */ /***/ (function(module, exports) { var core = module.exports = { version: '2.5.7' }; if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef /***/ }), /* 24 */, /* 25 */, /* 26 */, /* 27 */ /***/ (function(module, exports, __nested_webpack_require_63175__) { var isObject = __nested_webpack_require_63175__(34); module.exports = function (it) { if (!isObject(it)) throw TypeError(it + ' is not an object!'); return it; }; /***/ }), /* 28 */, /* 29 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.normalizePattern = normalizePattern; /** * Explode and normalize a pattern into its name and range. */ function normalizePattern(pattern) { let hasVersion = false; let range = 'latest'; let name = pattern; // if we're a scope then remove the @ and add it back later let isScoped = false; if (name[0] === '@') { isScoped = true; name = name.slice(1); } // take first part as the name const parts = name.split('@'); if (parts.length > 1) { name = parts.shift(); range = parts.join('@'); if (range) { hasVersion = true; } else { range = '*'; } } // add back @ scope suffix if (isScoped) { name = `@${name}`; } return { name, range, hasVersion }; } /***/ }), /* 30 */, /* 31 */ /***/ (function(module, exports, __nested_webpack_require_64321__) { var dP = __nested_webpack_require_64321__(50); var createDesc = __nested_webpack_require_64321__(106); module.exports = __nested_webpack_require_64321__(33) ? function (object, key, value) { return dP.f(object, key, createDesc(1, value)); } : function (object, key, value) { object[key] = value; return object; }; /***/ }), /* 32 */ /***/ (function(module, exports, __nested_webpack_require_64680__) { /* eslint-disable node/no-deprecated-api */ var buffer = __nested_webpack_require_64680__(63) var Buffer = buffer.Buffer // alternative to using Object.keys for old browsers function copyProps (src, dst) { for (var key in src) { dst[key] = src[key] } } if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { module.exports = buffer } else { // Copy properties from require('buffer') copyProps(buffer, exports) exports.Buffer = SafeBuffer } function SafeBuffer (arg, encodingOrOffset, length) { return Buffer(arg, encodingOrOffset, length) } // Copy static methods from Buffer copyProps(Buffer, SafeBuffer) SafeBuffer.from = function (arg, encodingOrOffset, length) { if (typeof arg === 'number') { throw new TypeError('Argument must not be a number') } return Buffer(arg, encodingOrOffset, length) } SafeBuffer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } var buf = Buffer(size) if (fill !== undefined) { if (typeof encoding === 'string') { buf.fill(fill, encoding) } else { buf.fill(fill) } } else { buf.fill(0) } return buf } SafeBuffer.allocUnsafe = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return Buffer(size) } SafeBuffer.allocUnsafeSlow = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return buffer.SlowBuffer(size) } /***/ }), /* 33 */ /***/ (function(module, exports, __nested_webpack_require_66293__) { // Thank's IE8 for his funny defineProperty module.exports = !__nested_webpack_require_66293__(85)(function () { return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; }); /***/ }), /* 34 */ /***/ (function(module, exports) { module.exports = function (it) { return typeof it === 'object' ? it !== null : typeof it === 'function'; }; /***/ }), /* 35 */ /***/ (function(module, exports) { module.exports = {}; /***/ }), /* 36 */ /***/ (function(module, exports) { module.exports = __webpack_require__(22037); /***/ }), /* 37 */, /* 38 */, /* 39 */, /* 40 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.wait = wait; exports.promisify = promisify; exports.queue = queue; function wait(delay) { return new Promise(resolve => { setTimeout(resolve, delay); }); } function promisify(fn, firstData) { return function (...args) { return new Promise(function (resolve, reject) { args.push(function (err, ...result) { let res = result; if (result.length <= 1) { res = result[0]; } if (firstData) { res = err; err = null; } if (err) { reject(err); } else { resolve(res); } }); fn.apply(null, args); }); }; } function queue(arr, promiseProducer, concurrency = Infinity) { concurrency = Math.min(concurrency, arr.length); // clone arr = arr.slice(); const results = []; let total = arr.length; if (!total) { return Promise.resolve(results); } return new Promise((resolve, reject) => { for (let i = 0; i < concurrency; i++) { next(); } function next() { const item = arr.shift(); const promise = promiseProducer(item); promise.then(function (result) { results.push(result); total--; if (total === 0) { resolve(results); } else { if (arr.length) { next(); } } }, reject); } }); } /***/ }), /* 41 */ /***/ (function(module, exports, __nested_webpack_require_68465__) { var global = __nested_webpack_require_68465__(11); var core = __nested_webpack_require_68465__(23); var ctx = __nested_webpack_require_68465__(48); var hide = __nested_webpack_require_68465__(31); var has = __nested_webpack_require_68465__(49); var PROTOTYPE = 'prototype'; var $export = function (type, name, source) { var IS_FORCED = type & $export.F; var IS_GLOBAL = type & $export.G; var IS_STATIC = type & $export.S; var IS_PROTO = type & $export.P; var IS_BIND = type & $export.B; var IS_WRAP = type & $export.W; var exports = IS_GLOBAL ? core : core[name] || (core[name] = {}); var expProto = exports[PROTOTYPE]; var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]; var key, own, out; if (IS_GLOBAL) source = name; for (key in source) { // contains in native own = !IS_FORCED && target && target[key] !== undefined; if (own && has(exports, key)) continue; // export native or passed out = own ? target[key] : source[key]; // prevent global pollution for namespaces exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] // bind timers to global for call from export context : IS_BIND && own ? ctx(out, global) // wrap global constructors for prevent change them in library : IS_WRAP && target[key] == out ? (function (C) { var F = function (a, b, c) { if (this instanceof C) { switch (arguments.length) { case 0: return new C(); case 1: return new C(a); case 2: return new C(a, b); } return new C(a, b, c); } return C.apply(this, arguments); }; F[PROTOTYPE] = C[PROTOTYPE]; return F; // make static versions for prototype methods })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% if (IS_PROTO) { (exports.virtual || (exports.virtual = {}))[key] = out; // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out); } } }; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap $export.U = 64; // safe $export.R = 128; // real proto method for `library` module.exports = $export; /***/ }), /* 42 */ /***/ (function(module, exports, __nested_webpack_require_70917__) { try { var util = __nested_webpack_require_70917__(2); if (typeof util.inherits !== 'function') throw ''; module.exports = util.inherits; } catch (e) { module.exports = __nested_webpack_require_70917__(224); } /***/ }), /* 43 */, /* 44 */, /* 45 */ /***/ (function(module, exports, __nested_webpack_require_71206__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.home = undefined; var _rootUser; function _load_rootUser() { return _rootUser = _interopRequireDefault(__nested_webpack_require_71206__(169)); } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const path = __nested_webpack_require_71206__(0); const home = exports.home = __nested_webpack_require_71206__(36).homedir(); const userHomeDir = (_rootUser || _load_rootUser()).default ? path.resolve('/usr/local/share') : home; exports.default = userHomeDir; /***/ }), /* 46 */ /***/ (function(module, exports) { module.exports = function (it) { if (typeof it != 'function') throw TypeError(it + ' is not a function!'); return it; }; /***/ }), /* 47 */ /***/ (function(module, exports) { var toString = {}.toString; module.exports = function (it) { return toString.call(it).slice(8, -1); }; /***/ }), /* 48 */ /***/ (function(module, exports, __nested_webpack_require_72188__) { // optional / simple context binding var aFunction = __nested_webpack_require_72188__(46); module.exports = function (fn, that, length) { aFunction(fn); if (that === undefined) return fn; switch (length) { case 1: return function (a) { return fn.call(that, a); }; case 2: return function (a, b) { return fn.call(that, a, b); }; case 3: return function (a, b, c) { return fn.call(that, a, b, c); }; } return function (/* ...args */) { return fn.apply(that, arguments); }; }; /***/ }), /* 49 */ /***/ (function(module, exports) { var hasOwnProperty = {}.hasOwnProperty; module.exports = function (it, key) { return hasOwnProperty.call(it, key); }; /***/ }), /* 50 */ /***/ (function(module, exports, __nested_webpack_require_72962__) { var anObject = __nested_webpack_require_72962__(27); var IE8_DOM_DEFINE = __nested_webpack_require_72962__(184); var toPrimitive = __nested_webpack_require_72962__(201); var dP = Object.defineProperty; exports.f = __nested_webpack_require_72962__(33) ? Object.defineProperty : function defineProperty(O, P, Attributes) { anObject(O); P = toPrimitive(P, true); anObject(Attributes); if (IE8_DOM_DEFINE) try { return dP(O, P, Attributes); } catch (e) { /* empty */ } if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); if ('value' in Attributes) O[P] = Attributes.value; return O; }; /***/ }), /* 51 */, /* 52 */, /* 53 */, /* 54 */ /***/ (function(module, exports) { module.exports = __webpack_require__(82361); /***/ }), /* 55 */ /***/ (function(module, exports, __nested_webpack_require_73754__) { "use strict"; const Buffer = __nested_webpack_require_73754__(32).Buffer const crypto = __nested_webpack_require_73754__(9) const Transform = __nested_webpack_require_73754__(17).Transform const SPEC_ALGORITHMS = ['sha256', 'sha384', 'sha512'] const BASE64_REGEX = /^[a-z0-9+/]+(?:=?=?)$/i const SRI_REGEX = /^([^-]+)-([^?]+)([?\S*]*)$/ const STRICT_SRI_REGEX = /^([^-]+)-([A-Za-z0-9+/=]{44,88})(\?[\x21-\x7E]*)*$/ const VCHAR_REGEX = /^[\x21-\x7E]+$/ class Hash { get isHash () { return true } constructor (hash, opts) { const strict = !!(opts && opts.strict) this.source = hash.trim() // 3.1. Integrity metadata (called "Hash" by ssri) // https://w3c.github.io/webappsec-subresource-integrity/#integrity-metadata-description const match = this.source.match( strict ? STRICT_SRI_REGEX : SRI_REGEX ) if (!match) { return } if (strict && !SPEC_ALGORITHMS.some(a => a === match[1])) { return } this.algorithm = match[1] this.digest = match[2] const rawOpts = match[3] this.options = rawOpts ? rawOpts.slice(1).split('?') : [] } hexDigest () { return this.digest && Buffer.from(this.digest, 'base64').toString('hex') } toJSON () { return this.toString() } toString (opts) { if (opts && opts.strict) { // Strict mode enforces the standard as close to the foot of the // letter as it can. if (!( // The spec has very restricted productions for algorithms. // https://www.w3.org/TR/CSP2/#source-list-syntax SPEC_ALGORITHMS.some(x => x === this.algorithm) && // Usually, if someone insists on using a "different" base64, we // leave it as-is, since there's multiple standards, and the // specified is not a URL-safe variant. // https://www.w3.org/TR/CSP2/#base64_value this.digest.match(BASE64_REGEX) && // Option syntax is strictly visual chars. // https://w3c.github.io/webappsec-subresource-integrity/#grammardef-option-expression // https://tools.ietf.org/html/rfc5234#appendix-B.1 (this.options || []).every(opt => opt.match(VCHAR_REGEX)) )) { return '' } } const options = this.options && this.options.length ? `?${this.options.join('?')}` : '' return `${this.algorithm}-${this.digest}${options}` } } class Integrity { get isIntegrity () { return true } toJSON () { return this.toString() } toString (opts) { opts = opts || {} let sep = opts.sep || ' ' if (opts.strict) { // Entries must be separated by whitespace, according to spec. sep = sep.replace(/\S+/g, ' ') } return Object.keys(this).map(k => { return this[k].map(hash => { return Hash.prototype.toString.call(hash, opts) }).filter(x => x.length).join(sep) }).filter(x => x.length).join(sep) } concat (integrity, opts) { const other = typeof integrity === 'string' ? integrity : stringify(integrity, opts) return parse(`${this.toString(opts)} ${other}`, opts) } hexDigest () { return parse(this, {single: true}).hexDigest() } match (integrity, opts) { const other = parse(integrity, opts) const algo = other.pickAlgorithm(opts) return ( this[algo] && other[algo] && this[algo].find(hash => other[algo].find(otherhash => hash.digest === otherhash.digest ) ) ) || false } pickAlgorithm (opts) { const pickAlgorithm = (opts && opts.pickAlgorithm) || getPrioritizedHash const keys = Object.keys(this) if (!keys.length) { throw new Error(`No algorithms available for ${ JSON.stringify(this.toString()) }`) } return keys.reduce((acc, algo) => { return pickAlgorithm(acc, algo) || acc }) } } module.exports.parse = parse function parse (sri, opts) { opts = opts || {} if (typeof sri === 'string') { return _parse(sri, opts) } else if (sri.algorithm && sri.digest) { const fullSri = new Integrity() fullSri[sri.algorithm] = [sri] return _parse(stringify(fullSri, opts), opts) } else { return _parse(stringify(sri, opts), opts) } } function _parse (integrity, opts) { // 3.4.3. Parse metadata // https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata if (opts.single) { return new Hash(integrity, opts) } return integrity.trim().split(/\s+/).reduce((acc, string) => { const hash = new Hash(string, opts) if (hash.algorithm && hash.digest) { const algo = hash.algorithm if (!acc[algo]) { acc[algo] = [] } acc[algo].push(hash) } return acc }, new Integrity()) } module.exports.stringify = stringify function stringify (obj, opts) { if (obj.algorithm && obj.digest) { return Hash.prototype.toString.call(obj, opts) } else if (typeof obj === 'string') { return stringify(parse(obj, opts), opts) } else { return Integrity.prototype.toString.call(obj, opts) } } module.exports.fromHex = fromHex function fromHex (hexDigest, algorithm, opts) { const optString = (opts && opts.options && opts.options.length) ? `?${opts.options.join('?')}` : '' return parse( `${algorithm}-${ Buffer.from(hexDigest, 'hex').toString('base64') }${optString}`, opts ) } module.exports.fromData = fromData function fromData (data, opts) { opts = opts || {} const algorithms = opts.algorithms || ['sha512'] const optString = opts.options && opts.options.length ? `?${opts.options.join('?')}` : '' return algorithms.reduce((acc, algo) => { const digest = crypto.createHash(algo).update(data).digest('base64') const hash = new Hash( `${algo}-${digest}${optString}`, opts ) if (hash.algorithm && hash.digest) { const algo = hash.algorithm if (!acc[algo]) { acc[algo] = [] } acc[algo].push(hash) } return acc }, new Integrity()) } module.exports.fromStream = fromStream function fromStream (stream, opts) { opts = opts || {} const P = opts.Promise || Promise const istream = integrityStream(opts) return new P((resolve, reject) => { stream.pipe(istream) stream.on('error', reject) istream.on('error', reject) let sri istream.on('integrity', s => { sri = s }) istream.on('end', () => resolve(sri)) istream.on('data', () => {}) }) } module.exports.checkData = checkData function checkData (data, sri, opts) { opts = opts || {} sri = parse(sri, opts) if (!Object.keys(sri).length) { if (opts.error) { throw Object.assign( new Error('No valid integrity hashes to check against'), { code: 'EINTEGRITY' } ) } else { return false } } const algorithm = sri.pickAlgorithm(opts) const digest = crypto.createHash(algorithm).update(data).digest('base64') const newSri = parse({algorithm, digest}) const match = newSri.match(sri, opts) if (match || !opts.error) { return match } else if (typeof opts.size === 'number' && (data.length !== opts.size)) { const err = new Error(`data size mismatch when checking ${sri}.\n Wanted: ${opts.size}\n Found: ${data.length}`) err.code = 'EBADSIZE' err.found = data.length err.expected = opts.size err.sri = sri throw err } else { const err = new Error(`Integrity checksum failed when using ${algorithm}: Wanted ${sri}, but got ${newSri}. (${data.length} bytes)`) err.code = 'EINTEGRITY' err.found = newSri err.expected = sri err.algorithm = algorithm err.sri = sri throw err } } module.exports.checkStream = checkStream function checkStream (stream, sri, opts) { opts = opts || {} const P = opts.Promise || Promise const checker = integrityStream(Object.assign({}, opts, { integrity: sri })) return new P((resolve, reject) => { stream.pipe(checker) stream.on('error', reject) checker.on('error', reject) let sri checker.on('verified', s => { sri = s }) checker.on('end', () => resolve(sri)) checker.on('data', () => {}) }) } module.exports.integrityStream = integrityStream function integrityStream (opts) { opts = opts || {} // For verification const sri = opts.integrity && parse(opts.integrity, opts) const goodSri = sri && Object.keys(sri).length const algorithm = goodSri && sri.pickAlgorithm(opts) const digests = goodSri && sri[algorithm] // Calculating stream const algorithms = Array.from( new Set( (opts.algorithms || ['sha512']) .concat(algorithm ? [algorithm] : []) ) ) const hashes = algorithms.map(crypto.createHash) let streamSize = 0 const stream = new Transform({ transform (chunk, enc, cb) { streamSize += chunk.length hashes.forEach(h => h.update(chunk, enc)) cb(null, chunk, enc) } }).on('end', () => { const optString = (opts.options && opts.options.length) ? `?${opts.options.join('?')}` : '' const newSri = parse(hashes.map((h, i) => { return `${algorithms[i]}-${h.digest('base64')}${optString}` }).join(' '), opts) // Integrity verification mode const match = goodSri && newSri.match(sri, opts) if (typeof opts.size === 'number' && streamSize !== opts.size) { const err = new Error(`stream size mismatch when checking ${sri}.\n Wanted: ${opts.size}\n Found: ${streamSize}`) err.code = 'EBADSIZE' err.found = streamSize err.expected = opts.size err.sri = sri stream.emit('error', err) } else if (opts.integrity && !match) { const err = new Error(`${sri} integrity checksum failed when using ${algorithm}: wanted ${digests} but got ${newSri}. (${streamSize} bytes)`) err.code = 'EINTEGRITY' err.found = newSri err.expected = digests err.algorithm = algorithm err.sri = sri stream.emit('error', err) } else { stream.emit('size', streamSize) stream.emit('integrity', newSri) match && stream.emit('verified', match) } }) return stream } module.exports.create = createIntegrity function createIntegrity (opts) { opts = opts || {} const algorithms = opts.algorithms || ['sha512'] const optString = opts.options && opts.options.length ? `?${opts.options.join('?')}` : '' const hashes = algorithms.map(crypto.createHash) return { update: function (chunk, enc) { hashes.forEach(h => h.update(chunk, enc)) return this }, digest: function (enc) { const integrity = algorithms.reduce((acc, algo) => { const digest = hashes.shift().digest('base64') const hash = new Hash( `${algo}-${digest}${optString}`, opts ) if (hash.algorithm && hash.digest) { const algo = hash.algorithm if (!acc[algo]) { acc[algo] = [] } acc[algo].push(hash) } return acc }, new Integrity()) return integrity } } } const NODE_HASHES = new Set(crypto.getHashes()) // This is a Best Effort™ at a reasonable priority for hash algos const DEFAULT_PRIORITY = [ 'md5', 'whirlpool', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512', // TODO - it's unclear _which_ of these Node will actually use as its name // for the algorithm, so we guesswork it based on the OpenSSL names. 'sha3', 'sha3-256', 'sha3-384', 'sha3-512', 'sha3_256', 'sha3_384', 'sha3_512' ].filter(algo => NODE_HASHES.has(algo)) function getPrioritizedHash (algo1, algo2) { return DEFAULT_PRIORITY.indexOf(algo1.toLowerCase()) >= DEFAULT_PRIORITY.indexOf(algo2.toLowerCase()) ? algo1 : algo2 } /***/ }), /* 56 */, /* 57 */, /* 58 */, /* 59 */, /* 60 */ /***/ (function(module, exports, __nested_webpack_require_85443__) { module.exports = minimatch minimatch.Minimatch = Minimatch var path = { sep: '/' } try { path = __nested_webpack_require_85443__(0) } catch (er) {} var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} var expand = __nested_webpack_require_85443__(175) var plTypes = { '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, '?': { open: '(?:', close: ')?' }, '+': { open: '(?:', close: ')+' }, '*': { open: '(?:', close: ')*' }, '@': { open: '(?:', close: ')' } } // any single thing other than / // don't need to escape / when using new RegExp() var qmark = '[^/]' // * => any number of characters var star = qmark + '*?' // ** when dots are allowed. Anything goes, except .. and . // not (^ or / followed by one or two dots followed by $ or /), // followed by anything, any number of times. var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' // not a ^ or / followed by a dot, // followed by anything, any number of times. var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' // characters that need to be escaped in RegExp. var reSpecials = charSet('().*{}+?[]^$\\!') // "abc" -> { a:true, b:true, c:true } function charSet (s) { return s.split('').reduce(function (set, c) { set[c] = true return set }, {}) } // normalizes slashes. var slashSplit = /\/+/ minimatch.filter = filter function filter (pattern, options) { options = options || {} return function (p, i, list) { return minimatch(p, pattern, options) } } function ext (a, b) { a = a || {} b = b || {} var t = {} Object.keys(b).forEach(function (k) { t[k] = b[k] }) Object.keys(a).forEach(function (k) { t[k] = a[k] }) return t } minimatch.defaults = function (def) { if (!def || !Object.keys(def).length) return minimatch var orig = minimatch var m = function minimatch (p, pattern, options) { return orig.minimatch(p, pattern, ext(def, options)) } m.Minimatch = function Minimatch (pattern, options) { return new orig.Minimatch(pattern, ext(def, options)) } return m } Minimatch.defaults = function (def) { if (!def || !Object.keys(def).length) return Minimatch return minimatch.defaults(def).Minimatch } function minimatch (p, pattern, options) { if (typeof pattern !== 'string') { throw new TypeError('glob pattern string required') } if (!options) options = {} // shortcut: comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { return false } // "" only matches "" if (pattern.trim() === '') return p === '' return new Minimatch(pattern, options).match(p) } function Minimatch (pattern, options) { if (!(this instanceof Minimatch)) { return new Minimatch(pattern, options) } if (typeof pattern !== 'string') { throw new TypeError('glob pattern string required') } if (!options) options = {} pattern = pattern.trim() // windows support: need to use /, not \ if (path.sep !== '/') { pattern = pattern.split(path.sep).join('/') } this.options = options this.set = [] this.pattern = pattern this.regexp = null this.negate = false this.comment = false this.empty = false // make the set of regexps etc. this.make() } Minimatch.prototype.debug = function () {} Minimatch.prototype.make = make function make () { // don't do it more than once. if (this._made) return var pattern = this.pattern var options = this.options // empty patterns and comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { this.comment = true return } if (!pattern) { this.empty = true return } // step 1: figure out negation, etc. this.parseNegate() // step 2: expand braces var set = this.globSet = this.braceExpand() if (options.debug) this.debug = console.error this.debug(this.pattern, set) // step 3: now we have a set, so turn each one into a series of path-portion // matching patterns. // These will be regexps, except in the case of "**", which is // set to the GLOBSTAR object for globstar behavior, // and will not contain any / characters set = this.globParts = set.map(function (s) { return s.split(slashSplit) }) this.debug(this.pattern, set) // glob --> regexps set = set.map(function (s, si, set) { return s.map(this.parse, this) }, this) this.debug(this.pattern, set) // filter out everything that didn't compile properly. set = set.filter(function (s) { return s.indexOf(false) === -1 }) this.debug(this.pattern, set) this.set = set } Minimatch.prototype.parseNegate = parseNegate function parseNegate () { var pattern = this.pattern var negate = false var options = this.options var negateOffset = 0 if (options.nonegate) return for (var i = 0, l = pattern.length ; i < l && pattern.charAt(i) === '!' ; i++) { negate = !negate negateOffset++ } if (negateOffset) this.pattern = pattern.substr(negateOffset) this.negate = negate } // Brace expansion: // a{b,c}d -> abd acd // a{b,}c -> abc ac // a{0..3}d -> a0d a1d a2d a3d // a{b,c{d,e}f}g -> abg acdfg acefg // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg // // Invalid sets are not expanded. // a{2..}b -> a{2..}b // a{b}c -> a{b}c minimatch.braceExpand = function (pattern, options) { return braceExpand(pattern, options) } Minimatch.prototype.braceExpand = braceExpand function braceExpand (pattern, options) { if (!options) { if (this instanceof Minimatch) { options = this.options } else { options = {} } } pattern = typeof pattern === 'undefined' ? this.pattern : pattern if (typeof pattern === 'undefined') { throw new TypeError('undefined pattern') } if (options.nobrace || !pattern.match(/\{.*\}/)) { // shortcut. no need to expand. return [pattern] } return expand(pattern) } // parse a component of the expanded set. // At this point, no pattern may contain "/" in it // so we're going to return a 2d array, where each entry is the full // pattern, split on '/', and then turned into a regular expression. // A regexp is made at the end which joins each array with an // escaped /, and another full one which joins each regexp with |. // // Following the lead of Bash 4.1, note that "**" only has special meaning // when it is the *only* thing in a path portion. Otherwise, any series // of * is equivalent to a single *. Globstar behavior is enabled by // default, and can be disabled by setting options.noglobstar. Minimatch.prototype.parse = parse var SUBPARSE = {} function parse (pattern, isSub) { if (pattern.length > 1024 * 64) { throw new TypeError('pattern is too long') } var options = this.options // shortcuts if (!options.noglobstar && pattern === '**') return GLOBSTAR if (pattern === '') return '' var re = '' var hasMagic = !!options.nocase var escaping = false // ? => one single character var patternListStack = [] var negativeLists = [] var stateChar var inClass = false var reClassStart = -1 var classStart = -1 // . and .. never match anything that doesn't start with ., // even when options.dot is set. var patternStart = pattern.charAt(0) === '.' ? '' // anything // not (start or / followed by . or .. followed by / or end) : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' : '(?!\\.)' var self = this function clearStateChar () { if (stateChar) { // we had some state-tracking character // that wasn't consumed by this pass. switch (stateChar) { case '*': re += star hasMagic = true break case '?': re += qmark hasMagic = true break default: re += '\\' + stateChar break } self.debug('clearStateChar %j %j', stateChar, re) stateChar = false } } for (var i = 0, len = pattern.length, c ; (i < len) && (c = pattern.charAt(i)) ; i++) { this.debug('%s\t%s %s %j', pattern, i, re, c) // skip over any that are escaped. if (escaping && reSpecials[c]) { re += '\\' + c escaping = false continue } switch (c) { case '/': // completely not allowed, even escaped. // Should already be path-split by now. return false case '\\': clearStateChar() escaping = true continue // the various stateChar values // for the "extglob" stuff. case '?': case '*': case '+': case '@': case '!': this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) // all of those are literals inside a class, except that // the glob [!a] means [^a] in regexp if (inClass) { this.debug(' in class') if (c === '!' && i === classStart + 1) c = '^' re += c continue } // if we already have a stateChar, then it means // that there was something like ** or +? in there. // Handle the stateChar, then proceed with this one. self.debug('call clearStateChar %j', stateChar) clearStateChar() stateChar = c // if extglob is disabled, then +(asdf|foo) isn't a thing. // just clear the statechar *now*, rather than even diving into // the patternList stuff. if (options.noext) clearStateChar() continue case '(': if (inClass) { re += '(' continue } if (!stateChar) { re += '\\(' continue } patternListStack.push({ type: stateChar, start: i - 1, reStart: re.length, open: plTypes[stateChar].open, close: plTypes[stateChar].close }) // negation is (?:(?!js)[^/]*) re += stateChar === '!' ? '(?:(?!(?:' : '(?:' this.debug('plType %j %j', stateChar, re) stateChar = false continue case ')': if (inClass || !patternListStack.length) { re += '\\)' continue } clearStateChar() hasMagic = true var pl = patternListStack.pop() // negation is (?:(?!js)[^/]*) // The others are (?:) re += pl.close if (pl.type === '!') { negativeLists.push(pl) } pl.reEnd = re.length continue case '|': if (inClass || !patternListStack.length || escaping) { re += '\\|' escaping = false continue } clearStateChar() re += '|' continue // these are mostly the same in regexp and glob case '[': // swallow any state-tracking char before the [ clearStateChar() if (inClass) { re += '\\' + c continue } inClass = true classStart = i reClassStart = re.length re += c continue case ']': // a right bracket shall lose its special // meaning and represent itself in // a bracket expression if it occurs // first in the list. -- POSIX.2 2.8.3.2 if (i === classStart + 1 || !inClass) { re += '\\' + c escaping = false continue } // handle the case where we left a class open. // "[z-a]" is valid, equivalent to "\[z-a\]" if (inClass) { // split where the last [ was, make sure we don't have // an invalid re. if so, re-walk the contents of the // would-be class to re-translate any characters that // were passed through as-is // TODO: It would probably be faster to determine this // without a try/catch and a new RegExp, but it's tricky // to do safely. For now, this is safe and works. var cs = pattern.substring(classStart + 1, i) try { RegExp('[' + cs + ']') } catch (er) { // not a valid class! var sp = this.parse(cs, SUBPARSE) re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' hasMagic = hasMagic || sp[1] inClass = false continue } } // finish up the class. hasMagic = true inClass = false re += c continue default: // swallow any state char that wasn't consumed clearStateChar() if (escaping) { // no need escaping = false } else if (reSpecials[c] && !(c === '^' && inClass)) { re += '\\' } re += c } // switch } // for // handle the case where we left a class open. // "[abc" is valid, equivalent to "\[abc" if (inClass) { // split where the last [ was, and escape it // this is a huge pita. We now have to re-walk // the contents of the would-be class to re-translate // any characters that were passed through as-is cs = pattern.substr(classStart + 1) sp = this.parse(cs, SUBPARSE) re = re.substr(0, reClassStart) + '\\[' + sp[0] hasMagic = hasMagic || sp[1] } // handle the case where we had a +( thing at the *end* // of the pattern. // each pattern list stack adds 3 chars, and we need to go through // and escape any | chars that were passed through as-is for the regexp. // Go through and escape them, taking care not to double-escape any // | chars that were already escaped. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { var tail = re.slice(pl.reStart + pl.open.length) this.debug('setting tail', re, pl) // maybe some even number of \, then maybe 1 \, followed by a | tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { if (!$2) { // the | isn't already escaped, so escape it. $2 = '\\' } // need to escape all those slashes *again*, without escaping the // one that we need for escaping the | character. As it works out, // escaping an even number of slashes can be done by simply repeating // it exactly after itself. That's why this trick works. // // I am sorry that you have to see this. return $1 + $1 + $2 + '|' }) this.debug('tail=%j\n %s', tail, tail, pl, re) var t = pl.type === '*' ? star : pl.type === '?' ? qmark : '\\' + pl.type hasMagic = true re = re.slice(0, pl.reStart) + t + '\\(' + tail } // handle trailing things that only matter at the very end. clearStateChar() if (escaping) { // trailing \\ re += '\\\\' } // only need to apply the nodot start if the re starts with // something that could conceivably capture a dot var addPatternStart = false switch (re.charAt(0)) { case '.': case '[': case '(': addPatternStart = true } // Hack to work around lack of negative lookbehind in JS // A pattern like: *.!(x).!(y|z) needs to ensure that a name // like 'a.xyz.yz' doesn't match. So, the first negative // lookahead, has to look ALL the way ahead, to the end of // the pattern. for (var n = negativeLists.length - 1; n > -1; n--) { var nl = negativeLists[n] var nlBefore = re.slice(0, nl.reStart) var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) var nlAfter = re.slice(nl.reEnd) nlLast += nlAfter // Handle nested stuff like *(*.js|!(*.json)), where open parens // mean that we should *not* include the ) in the bit that is considered // "after" the negated section. var openParensBefore = nlBefore.split('(').length - 1 var cleanAfter = nlAfter for (i = 0; i < openParensBefore; i++) { cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') } nlAfter = cleanAfter var dollar = '' if (nlAfter === '' && isSub !== SUBPARSE) { dollar = '$' } var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast re = newRe } // if the re is not "" at this point, then we need to make sure // it doesn't match against an empty path part. // Otherwise a/* will match a/, which it should not. if (re !== '' && hasMagic) { re = '(?=.)' + re } if (addPatternStart) { re = patternStart + re } // parsing just a piece of a larger pattern. if (isSub === SUBPARSE) { return [re, hasMagic] } // skip the regexp for non-magical patterns // unescape anything in it, though, so that it'll be // an exact match against a file etc. if (!hasMagic) { return globUnescape(pattern) } var flags = options.nocase ? 'i' : '' try { var regExp = new RegExp('^' + re + '$', flags) } catch (er) { // If it was an invalid regular expression, then it can't match // anything. This trick looks for a character after the end of // the string, which is of course impossible, except in multi-line // mode, but it's not a /m regex. return new RegExp('$.') } regExp._glob = pattern regExp._src = re return regExp } minimatch.makeRe = function (pattern, options) { return new Minimatch(pattern, options || {}).makeRe() } Minimatch.prototype.makeRe = makeRe function makeRe () { if (this.regexp || this.regexp === false) return this.regexp // at this point, this.set is a 2d array of partial // pattern strings, or "**". // // It's better to use .match(). This function shouldn't // be used, really, but it's pretty convenient sometimes, // when you just want to work with a regex. var set = this.set if (!set.length) { this.regexp = false return this.regexp } var options = this.options var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot var flags = options.nocase ? 'i' : '' var re = set.map(function (pattern) { return pattern.map(function (p) { return (p === GLOBSTAR) ? twoStar : (typeof p === 'string') ? regExpEscape(p) : p._src }).join('\\\/') }).join('|') // must match entire pattern // ending in a * or ** will make it less strict. re = '^(?:' + re + ')$' // can match anything, as long as it's not this. if (this.negate) re = '^(?!' + re + ').*$' try { this.regexp = new RegExp(re, flags) } catch (ex) { this.regexp = false } return this.regexp } minimatch.match = function (list, pattern, options) { options = options || {} var mm = new Minimatch(pattern, options) list = list.filter(function (f) { return mm.match(f) }) if (mm.options.nonull && !list.length) { list.push(pattern) } return list } Minimatch.prototype.match = match function match (f, partial) { this.debug('match', f, this.pattern) // short-circuit in the case of busted things. // comments, etc. if (this.comment) return false if (this.empty) return f === '' if (f === '/' && partial) return true var options = this.options // windows: need to use /, not \ if (path.sep !== '/') { f = f.split(path.sep).join('/') } // treat the test path as a set of pathparts. f = f.split(slashSplit) this.debug(this.pattern, 'split', f) // just ONE of the pattern sets in this.set needs to match // in order for it to be valid. If negating, then just one // match means that we have failed. // Either way, return on the first hit. var set = this.set this.debug(this.pattern, 'set', set) // Find the basename of the path by looking for the last non-empty segment var filename var i for (i = f.length - 1; i >= 0; i--) { filename = f[i] if (filename) break } for (i = 0; i < set.length; i++) { var pattern = set[i] var file = f if (options.matchBase && pattern.length === 1) { file = [filename] } var hit = this.matchOne(file, pattern, partial) if (hit) { if (options.flipNegate) return true return !this.negate } } // didn't get any hits. this is success if it's a negative // pattern, failure otherwise. if (options.flipNegate) return false return this.negate } // set partial to true to test if, for example, // "/a/b" matches the start of "/*/b/*/d" // Partial means, if you run out of file before you run // out of pattern, then that's fine, as long as all // the parts match. Minimatch.prototype.matchOne = function (file, pattern, partial) { var options = this.options this.debug('matchOne', { 'this': this, file: file, pattern: pattern }) this.debug('matchOne', file.length, pattern.length) for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length ; (fi < fl) && (pi < pl) ; fi++, pi++) { this.debug('matchOne loop') var p = pattern[pi] var f = file[fi] this.debug(pattern, p, f) // should be impossible. // some invalid regexp stuff in the set. if (p === false) return false if (p === GLOBSTAR) { this.debug('GLOBSTAR', [pattern, p, f]) // "**" // a/**/b/**/c would match the following: // a/b/x/y/z/c // a/x/y/z/b/c // a/b/x/b/x/c // a/b/c // To do this, take the rest of the pattern after // the **, and see if it would match the file remainder. // If so, return success. // If not, the ** "swallows" a segment, and try again. // This is recursively awful. // // a/**/b/**/c matching a/b/x/y/z/c // - a matches a // - doublestar // - matchOne(b/x/y/z/c, b/**/c) // - b matches b // - doublestar // - matchOne(x/y/z/c, c) -> no // - matchOne(y/z/c, c) -> no // - matchOne(z/c, c) -> no // - matchOne(c, c) yes, hit var fr = fi var pr = pi + 1 if (pr === pl) { this.debug('** at the end') // a ** at the end will just swallow the rest. // We have found a match. // however, it will not swallow /.x, unless // options.dot is set. // . and .. are *never* matched by **, for explosively // exponential reasons. for (; fi < fl; fi++) { if (file[fi] === '.' || file[fi] === '..' || (!options.dot && file[fi].charAt(0) === '.')) return false } return true } // ok, let's see if we can swallow whatever we can. while (fr < fl) { var swallowee = file[fr] this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) // XXX remove this slice. Just pass the start index. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { this.debug('globstar found match!', fr, fl, swallowee) // found a match. return true } else { // can't swallow "." or ".." ever. // can only swallow ".foo" when explicitly asked. if (swallowee === '.' || swallowee === '..' || (!options.dot && swallowee.charAt(0) === '.')) { this.debug('dot detected!', file, fr, pattern, pr) break } // ** swallows a segment, and continue. this.debug('globstar swallow a segment, and continue') fr++ } } // no match was found. // However, in partial mode, we can't say this is necessarily over. // If there's more *pattern* left, then if (partial) { // ran out of file this.debug('\n>>> no match, partial?', file, fr, pattern, pr) if (fr === fl) return true } return false } // something other than ** // non-magic patterns just have to match exactly // patterns with magic have been turned into regexps. var hit if (typeof p === 'string') { if (options.nocase) { hit = f.toLowerCase() === p.toLowerCase() } else { hit = f === p } this.debug('string match', p, f, hit) } else { hit = f.match(p) this.debug('pattern match', p, f, hit) } if (!hit) return false } // Note: ending in / means that we'll get a final "" // at the end of the pattern. This can only match a // corresponding "" at the end of the file. // If the file ends in /, then it can only match a // a pattern that ends in /, unless the pattern just // doesn't have any more for it. But, a/b/ should *not* // match "a/b/*", even though "" matches against the // [^/]*? pattern, except in partial mode, where it might // simply not be reached yet. // However, a/b/ should still satisfy a/* // now either we fell off the end of the pattern, or we're done. if (fi === fl && pi === pl) { // ran out of pattern and filename at the same time. // an exact hit! return true } else if (fi === fl) { // ran out of file, but still had pattern left. // this is ok if we're doing the match as part of // a glob fs traversal. return partial } else if (pi === pl) { // ran out of pattern, still have file left. // this is only acceptable if we're on the very last // empty segment of a file with a trailing slash. // a/* should match a/b/ var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') return emptyFileEnd } // should be unreachable. throw new Error('wtf?') } // replace stuff like \* with * function globUnescape (s) { return s.replace(/\\(.)/g, '$1') } function regExpEscape (s) { return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') } /***/ }), /* 61 */ /***/ (function(module, exports, __nested_webpack_require_110873__) { var wrappy = __nested_webpack_require_110873__(123) module.exports = wrappy(once) module.exports.strict = wrappy(onceStrict) once.proto = once(function () { Object.defineProperty(Function.prototype, 'once', { value: function () { return once(this) }, configurable: true }) Object.defineProperty(Function.prototype, 'onceStrict', { value: function () { return onceStrict(this) }, configurable: true }) }) function once (fn) { var f = function () { if (f.called) return f.value f.called = true return f.value = fn.apply(this, arguments) } f.called = false return f } function onceStrict (fn) { var f = function () { if (f.called) throw new Error(f.onceError) f.called = true return f.value = fn.apply(this, arguments) } var name = fn.name || 'Function wrapped with `once`' f.onceError = name + " shouldn't be called more than once" f.called = false return f } /***/ }), /* 62 */, /* 63 */ /***/ (function(module, exports) { module.exports = __webpack_require__(14300); /***/ }), /* 64 */, /* 65 */, /* 66 */, /* 67 */ /***/ (function(module, exports) { // 7.2.1 RequireObjectCoercible(argument) module.exports = function (it) { if (it == undefined) throw TypeError("Can't call method on " + it); return it; }; /***/ }), /* 68 */ /***/ (function(module, exports, __nested_webpack_require_112244__) { var isObject = __nested_webpack_require_112244__(34); var document = __nested_webpack_require_112244__(11).document; // typeof document.createElement is 'object' in old IE var is = isObject(document) && isObject(document.createElement); module.exports = function (it) { return is ? document.createElement(it) : {}; }; /***/ }), /* 69 */ /***/ (function(module, exports) { module.exports = true; /***/ }), /* 70 */ /***/ (function(module, exports, __nested_webpack_require_112694__) { "use strict"; // 25.4.1.5 NewPromiseCapability(C) var aFunction = __nested_webpack_require_112694__(46); function PromiseCapability(C) { var resolve, reject; this.promise = new C(function ($$resolve, $$reject) { if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); resolve = $$resolve; reject = $$reject; }); this.resolve = aFunction(resolve); this.reject = aFunction(reject); } module.exports.f = function (C) { return new PromiseCapability(C); }; /***/ }), /* 71 */ /***/ (function(module, exports, __nested_webpack_require_113276__) { var def = __nested_webpack_require_113276__(50).f; var has = __nested_webpack_require_113276__(49); var TAG = __nested_webpack_require_113276__(13)('toStringTag'); module.exports = function (it, tag, stat) { if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); }; /***/ }), /* 72 */ /***/ (function(module, exports, __nested_webpack_require_113628__) { var shared = __nested_webpack_require_113628__(107)('keys'); var uid = __nested_webpack_require_113628__(111); module.exports = function (key) { return shared[key] || (shared[key] = uid(key)); }; /***/ }), /* 73 */ /***/ (function(module, exports) { // 7.1.4 ToInteger var ceil = Math.ceil; var floor = Math.floor; module.exports = function (it) { return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; /***/ }), /* 74 */ /***/ (function(module, exports, __nested_webpack_require_114094__) { // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = __nested_webpack_require_114094__(131); var defined = __nested_webpack_require_114094__(67); module.exports = function (it) { return IObject(defined(it)); }; /***/ }), /* 75 */ /***/ (function(module, exports, __nested_webpack_require_114394__) { // Approach: // // 1. Get the minimatch set // 2. For each pattern in the set, PROCESS(pattern, false) // 3. Store matches per-set, then uniq them // // PROCESS(pattern, inGlobStar) // Get the first [n] items from pattern that are all strings // Join these together. This is PREFIX. // If there is no more remaining, then stat(PREFIX) and // add to matches if it succeeds. END. // // If inGlobStar and PREFIX is symlink and points to dir // set ENTRIES = [] // else readdir(PREFIX) as ENTRIES // If fail, END // // with ENTRIES // If pattern[n] is GLOBSTAR // // handle the case where the globstar match is empty // // by pruning it out, and testing the resulting pattern // PROCESS(pattern[0..n] + pattern[n+1 .. $], false) // // handle other cases. // for ENTRY in ENTRIES (not dotfiles) // // attach globstar + tail onto the entry // // Mark that this entry is a globstar match // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) // // else // not globstar // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) // Test ENTRY against pattern[n] // If fails, continue // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) // // Caveat: // Cache all stats and readdirs results to minimize syscall. Since all // we ever care about is existence and directory-ness, we can just keep // `true` for files, and [children,...] for directories, or `false` for // things that don't exist. module.exports = glob var fs = __nested_webpack_require_114394__(3) var rp = __nested_webpack_require_114394__(114) var minimatch = __nested_webpack_require_114394__(60) var Minimatch = minimatch.Minimatch var inherits = __nested_webpack_require_114394__(42) var EE = __nested_webpack_require_114394__(54).EventEmitter var path = __nested_webpack_require_114394__(0) var assert = __nested_webpack_require_114394__(22) var isAbsolute = __nested_webpack_require_114394__(76) var globSync = __nested_webpack_require_114394__(218) var common = __nested_webpack_require_114394__(115) var alphasort = common.alphasort var alphasorti = common.alphasorti var setopts = common.setopts var ownProp = common.ownProp var inflight = __nested_webpack_require_114394__(223) var util = __nested_webpack_require_114394__(2) var childrenIgnored = common.childrenIgnored var isIgnored = common.isIgnored var once = __nested_webpack_require_114394__(61) function glob (pattern, options, cb) { if (typeof options === 'function') cb = options, options = {} if (!options) options = {} if (options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return globSync(pattern, options) } return new Glob(pattern, options, cb) } glob.sync = globSync var GlobSync = glob.GlobSync = globSync.GlobSync // old api surface glob.glob = glob function extend (origin, add) { if (add === null || typeof add !== 'object') { return origin } var keys = Object.keys(add) var i = keys.length while (i--) { origin[keys[i]] = add[keys[i]] } return origin } glob.hasMagic = function (pattern, options_) { var options = extend({}, options_) options.noprocess = true var g = new Glob(pattern, options) var set = g.minimatch.set if (!pattern) return false if (set.length > 1) return true for (var j = 0; j < set[0].length; j++) { if (typeof set[0][j] !== 'string') return true } return false } glob.Glob = Glob inherits(Glob, EE) function Glob (pattern, options, cb) { if (typeof options === 'function') { cb = options options = null } if (options && options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return new GlobSync(pattern, options) } if (!(this instanceof Glob)) return new Glob(pattern, options, cb) setopts(this, pattern, options) this._didRealPath = false // process each pattern in the minimatch set var n = this.minimatch.set.length // The matches are stored as {: true,...} so that // duplicates are automagically pruned. // Later, we do an Object.keys() on these. // Keep them as a list so we can fill in when nonull is set. this.matches = new Array(n) if (typeof cb === 'function') { cb = once(cb) this.on('error', cb) this.on('end', function (matches) { cb(null, matches) }) } var self = this this._processing = 0 this._emitQueue = [] this._processQueue = [] this.paused = false if (this.noprocess) return this if (n === 0) return done() var sync = true for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false, done) } sync = false function done () { --self._processing if (self._processing <= 0) { if (sync) { process.nextTick(function () { self._finish() }) } else { self._finish() } } } } Glob.prototype._finish = function () { assert(this instanceof Glob) if (this.aborted) return if (this.realpath && !this._didRealpath) return this._realpath() common.finish(this) this.emit('end', this.found) } Glob.prototype._realpath = function () { if (this._didRealpath) return this._didRealpath = true var n = this.matches.length if (n === 0) return this._finish() var self = this for (var i = 0; i < this.matches.length; i++) this._realpathSet(i, next) function next () { if (--n === 0) self._finish() } } Glob.prototype._realpathSet = function (index, cb) { var matchset = this.matches[index] if (!matchset) return cb() var found = Object.keys(matchset) var self = this var n = found.length if (n === 0) return cb() var set = this.matches[index] = Object.create(null) found.forEach(function (p, i) { // If there's a problem with the stat, then it means that // one or more of the links in the realpath couldn't be // resolved. just return the abs value in that case. p = self._makeAbs(p) rp.realpath(p, self.realpathCache, function (er, real) { if (!er) set[real] = true else if (er.syscall === 'stat') set[p] = true else self.emit('error', er) // srsly wtf right here if (--n === 0) { self.matches[index] = set cb() } }) }) } Glob.prototype._mark = function (p) { return common.mark(this, p) } Glob.prototype._makeAbs = function (f) { return common.makeAbs(this, f) } Glob.prototype.abort = function () { this.aborted = true this.emit('abort') } Glob.prototype.pause = function () { if (!this.paused) { this.paused = true this.emit('pause') } } Glob.prototype.resume = function () { if (this.paused) { this.emit('resume') this.paused = false if (this._emitQueue.length) { var eq = this._emitQueue.slice(0) this._emitQueue.length = 0 for (var i = 0; i < eq.length; i ++) { var e = eq[i] this._emitMatch(e[0], e[1]) } } if (this._processQueue.length) { var pq = this._processQueue.slice(0) this._processQueue.length = 0 for (var i = 0; i < pq.length; i ++) { var p = pq[i] this._processing-- this._process(p[0], p[1], p[2], p[3]) } } } } Glob.prototype._process = function (pattern, index, inGlobStar, cb) { assert(this instanceof Glob) assert(typeof cb === 'function') if (this.aborted) return this._processing++ if (this.paused) { this._processQueue.push([pattern, index, inGlobStar, cb]) return } //console.error('PROCESS %d', this._processing, pattern) // Get the first [n] parts of pattern that are all strings. var n = 0 while (typeof pattern[n] === 'string') { n ++ } // now n is the index of the first one that is *not* a string. // see if there's anything else var prefix switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index, cb) return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/') break } var remain = pattern.slice(n) // get the list of entries. var read if (prefix === null) read = '.' else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix } else read = prefix var abs = this._makeAbs(read) //if ignored, skip _processing if (childrenIgnored(this, read)) return cb() var isGlobStar = remain[0] === minimatch.GLOBSTAR if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) else this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) } Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this this._readdir(abs, inGlobStar, function (er, entries) { return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }) } Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { // if the abs isn't a dir, then nothing can match! if (!entries) return cb() // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0] var negate = !!this.minimatch.negate var rawGlob = pn._glob var dotOk = this.dot || rawGlob.charAt(0) === '.' var matchedEntries = [] for (var i = 0; i < entries.length; i++) { var e = entries[i] if (e.charAt(0) !== '.' || dotOk) { var m if (negate && !prefix) { m = !e.match(pn) } else { m = e.match(pn) } if (m) matchedEntries.push(e) } } //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) var len = matchedEntries.length // If there are no matched entries, then nothing matches. if (len === 0) return cb() // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null) for (var i = 0; i < len; i ++) { var e = matchedEntries[i] if (prefix) { if (prefix !== '/') e = prefix + '/' + e else e = prefix + e } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e) } this._emitMatch(index, e) } // This was the last one, and no stats were needed return cb() } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift() for (var i = 0; i < len; i ++) { var e = matchedEntries[i] var newPattern if (prefix) { if (prefix !== '/') e = prefix + '/' + e else e = prefix + e } this._process([e].concat(remain), index, inGlobStar, cb) } cb() } Glob.prototype._emitMatch = function (index, e) { if (this.aborted) return if (isIgnored(this, e)) return if (this.paused) { this._emitQueue.push([index, e]) return } var abs = isAbsolute(e) ? e : this._makeAbs(e) if (this.mark) e = this._mark(e) if (this.absolute) e = abs if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs] if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true var st = this.statCache[abs] if (st) this.emit('stat', e, st) this.emit('match', e) } Glob.prototype._readdirInGlobStar = function (abs, cb) { if (this.aborted) return // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false, cb) var lstatkey = 'lstat\0' + abs var self = this var lstatcb = inflight(lstatkey, lstatcb_) if (lstatcb) fs.lstat(abs, lstatcb) function lstatcb_ (er, lstat) { if (er && er.code === 'ENOENT') return cb() var isSym = lstat && lstat.isSymbolicLink() self.symlinks[abs] = isSym // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) { self.cache[abs] = 'FILE' cb() } else self._readdir(abs, false, cb) } } Glob.prototype._readdir = function (abs, inGlobStar, cb) { if (this.aborted) return cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) if (!cb) return //console.error('RD %j %j', +inGlobStar, abs) if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs, cb) if (ownProp(this.cache, abs)) { var c = this.cache[abs] if (!c || c === 'FILE') return cb() if (Array.isArray(c)) return cb(null, c) } var self = this fs.readdir(abs, readdirCb(this, abs, cb)) } function readdirCb (self, abs, cb) { return function (er, entries) { if (er) self._readdirError(abs, er, cb) else self._readdirEntries(abs, entries, cb) } } Glob.prototype._readdirEntries = function (abs, entries, cb) { if (this.aborted) return // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i] if (abs === '/') e = abs + e else e = abs + '/' + e this.cache[e] = true } } this.cache[abs] = entries return cb(null, entries) } Glob.prototype._readdirError = function (f, er, cb) { if (this.aborted) return // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f) this.cache[abs] = 'FILE' if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd) error.path = this.cwd error.code = er.code this.emit('error', error) this.abort() } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false if (this.strict) { this.emit('error', er) // If the error is handled, then we abort // if not, we threw out of here this.abort() } if (!this.silent) console.error('glob error', er) break } return cb() } Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this this._readdir(abs, inGlobStar, function (er, entries) { self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }) } Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { //console.error('pgs2', prefix, remain[0], entries) // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return cb() // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1) var gspref = prefix ? [ prefix ] : [] var noGlobStar = gspref.concat(remainWithoutGlobStar) // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false, cb) var isSym = this.symlinks[abs] var len = entries.length // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return cb() for (var i = 0; i < len; i++) { var e = entries[i] if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar) this._process(instead, index, true, cb) var below = gspref.concat(entries[i], remain) this._process(below, index, true, cb) } cb() } Glob.prototype._processSimple = function (prefix, index, cb) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var self = this this._stat(prefix, function (er, exists) { self._processSimple2(prefix, index, er, exists, cb) }) } Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { //console.error('ps2', prefix, exists) if (!this.matches[index]) this.matches[index] = Object.create(null) // If it doesn't exist, then just mark the lack of results if (!exists) return cb() if (prefix && isAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix) if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix) } else { prefix = path.resolve(this.root, prefix) if (trail) prefix += '/' } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/') // Mark this as a match this._emitMatch(index, prefix) cb() } // Returns either 'DIR', 'FILE', or false Glob.prototype._stat = function (f, cb) { var abs = this._makeAbs(f) var needDir = f.slice(-1) === '/' if (f.length > this.maxLength) return cb() if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs] if (Array.isArray(c)) c = 'DIR' // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return cb(null, c) if (needDir && c === 'FILE') return cb() // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var exists var stat = this.statCache[abs] if (stat !== undefined) { if (stat === false) return cb(null, stat) else { var type = stat.isDirectory() ? 'DIR' : 'FILE' if (needDir && type === 'FILE') return cb() else return cb(null, type, stat) } } var self = this var statcb = inflight('stat\0' + abs, lstatcb_) if (statcb) fs.lstat(abs, statcb) function lstatcb_ (er, lstat) { if (lstat && lstat.isSymbolicLink()) { // If it's a symlink, then treat it as the target, unless // the target does not exist, then treat it as a file. return fs.stat(abs, function (er, stat) { if (er) self._stat2(f, abs, null, lstat, cb) else self._stat2(f, abs, er, stat, cb) }) } else { self._stat2(f, abs, er, lstat, cb) } } } Glob.prototype._stat2 = function (f, abs, er, stat, cb) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false return cb() } var needDir = f.slice(-1) === '/' this.statCache[abs] = stat if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) return cb(null, false, stat) var c = true if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE' this.cache[abs] = this.cache[abs] || c if (needDir && c === 'FILE') return cb() return cb(null, c, stat) } /***/ }), /* 76 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function posix(path) { return path.charAt(0) === '/'; } function win32(path) { // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; var result = splitDeviceRe.exec(path); var device = result[1] || ''; var isUnc = Boolean(device && device.charAt(1) !== ':'); // UNC paths are always absolute return Boolean(result[2] || isUnc); } module.exports = process.platform === 'win32' ? win32 : posix; module.exports.posix = posix; module.exports.win32 = win32; /***/ }), /* 77 */, /* 78 */, /* 79 */ /***/ (function(module, exports) { module.exports = __webpack_require__(76224); /***/ }), /* 80 */, /* 81 */ /***/ (function(module, exports, __nested_webpack_require_134773__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (str, fileLoc = 'lockfile') { str = (0, (_stripBom || _load_stripBom()).default)(str); return hasMergeConflicts(str) ? parseWithConflict(str, fileLoc) : { type: 'success', object: parse(str, fileLoc) }; }; var _util; function _load_util() { return _util = _interopRequireDefault(__nested_webpack_require_134773__(2)); } var _invariant; function _load_invariant() { return _invariant = _interopRequireDefault(__nested_webpack_require_134773__(7)); } var _stripBom; function _load_stripBom() { return _stripBom = _interopRequireDefault(__nested_webpack_require_134773__(122)); } var _constants; function _load_constants() { return _constants = __nested_webpack_require_134773__(6); } var _errors; function _load_errors() { return _errors = __nested_webpack_require_134773__(4); } var _map; function _load_map() { return _map = _interopRequireDefault(__nested_webpack_require_134773__(20)); } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* eslint quotes: 0 */ const VERSION_REGEX = /^yarn lockfile v(\d+)$/; const TOKEN_TYPES = { boolean: 'BOOLEAN', string: 'STRING', identifier: 'IDENTIFIER', eof: 'EOF', colon: 'COLON', newline: 'NEWLINE', comment: 'COMMENT', indent: 'INDENT', invalid: 'INVALID', number: 'NUMBER', comma: 'COMMA' }; const VALID_PROP_VALUE_TOKENS = [TOKEN_TYPES.boolean, TOKEN_TYPES.string, TOKEN_TYPES.number]; function isValidPropValueToken(token) { return VALID_PROP_VALUE_TOKENS.indexOf(token.type) >= 0; } function* tokenise(input) { let lastNewline = false; let line = 1; let col = 0; function buildToken(type, value) { return { line, col, type, value }; } while (input.length) { let chop = 0; if (input[0] === '\n' || input[0] === '\r') { chop++; // If this is a \r\n line, ignore both chars but only add one new line if (input[1] === '\n') { chop++; } line++; col = 0; yield buildToken(TOKEN_TYPES.newline); } else if (input[0] === '#') { chop++; let val = ''; while (input[chop] !== '\n') { val += input[chop]; chop++; } yield buildToken(TOKEN_TYPES.comment, val); } else if (input[0] === ' ') { if (lastNewline) { let indent = ''; for (let i = 0; input[i] === ' '; i++) { indent += input[i]; } if (indent.length % 2) { throw new TypeError('Invalid number of spaces'); } else { chop = indent.length; yield buildToken(TOKEN_TYPES.indent, indent.length / 2); } } else { chop++; } } else if (input[0] === '"') { let val = ''; for (let i = 0;; i++) { const currentChar = input[i]; val += currentChar; if (i > 0 && currentChar === '"') { const isEscaped = input[i - 1] === '\\' && input[i - 2] !== '\\'; if (!isEscaped) { break; } } } chop = val.length; try { yield buildToken(TOKEN_TYPES.string, JSON.parse(val)); } catch (err) { if (err instanceof SyntaxError) { yield buildToken(TOKEN_TYPES.invalid); } else { throw err; } } } else if (/^[0-9]/.test(input)) { let val = ''; for (let i = 0; /^[0-9]$/.test(input[i]); i++) { val += input[i]; } chop = val.length; yield buildToken(TOKEN_TYPES.number, +val); } else if (/^true/.test(input)) { yield buildToken(TOKEN_TYPES.boolean, true); chop = 4; } else if (/^false/.test(input)) { yield buildToken(TOKEN_TYPES.boolean, false); chop = 5; } else if (input[0] === ':') { yield buildToken(TOKEN_TYPES.colon); chop++; } else if (input[0] === ',') { yield buildToken(TOKEN_TYPES.comma); chop++; } else if (/^[a-zA-Z\/-]/g.test(input)) { let name = ''; for (let i = 0; i < input.length; i++) { const char = input[i]; if (char === ':' || char === ' ' || char === '\n' || char === '\r' || char === ',') { break; } else { name += char; } } chop = name.length; yield buildToken(TOKEN_TYPES.string, name); } else { yield buildToken(TOKEN_TYPES.invalid); } if (!chop) { // will trigger infinite recursion yield buildToken(TOKEN_TYPES.invalid); } col += chop; lastNewline = input[0] === '\n' || input[0] === '\r' && input[1] === '\n'; input = input.slice(chop); } yield buildToken(TOKEN_TYPES.eof); } class Parser { constructor(input, fileLoc = 'lockfile') { this.comments = []; this.tokens = tokenise(input); this.fileLoc = fileLoc; } onComment(token) { const value = token.value; (0, (_invariant || _load_invariant()).default)(typeof value === 'string', 'expected token value to be a string'); const comment = value.trim(); const versionMatch = comment.match(VERSION_REGEX); if (versionMatch) { const version = +versionMatch[1]; if (version > (_constants || _load_constants()).LOCKFILE_VERSION) { throw new (_errors || _load_errors()).MessageError(`Can't install from a lockfile of version ${version} as you're on an old yarn version that only supports ` + `versions up to ${(_constants || _load_constants()).LOCKFILE_VERSION}. Run \`$ yarn self-update\` to upgrade to the latest version.`); } } this.comments.push(comment); } next() { const item = this.tokens.next(); (0, (_invariant || _load_invariant()).default)(item, 'expected a token'); const done = item.done, value = item.value; if (done || !value) { throw new Error('No more tokens'); } else if (value.type === TOKEN_TYPES.comment) { this.onComment(value); return this.next(); } else { return this.token = value; } } unexpected(msg = 'Unexpected token') { throw new SyntaxError(`${msg} ${this.token.line}:${this.token.col} in ${this.fileLoc}`); } expect(tokType) { if (this.token.type === tokType) { this.next(); } else { this.unexpected(); } } eat(tokType) { if (this.token.type === tokType) { this.next(); return true; } else { return false; } } parse(indent = 0) { const obj = (0, (_map || _load_map()).default)(); while (true) { const propToken = this.token; if (propToken.type === TOKEN_TYPES.newline) { const nextToken = this.next(); if (!indent) { // if we have 0 indentation then the next token doesn't matter continue; } if (nextToken.type !== TOKEN_TYPES.indent) { // if we have no indentation after a newline then we've gone down a level break; } if (nextToken.value === indent) { // all is good, the indent is on our level this.next(); } else { // the indentation is less than our level break; } } else if (propToken.type === TOKEN_TYPES.indent) { if (propToken.value === indent) { this.next(); } else { break; } } else if (propToken.type === TOKEN_TYPES.eof) { break; } else if (propToken.type === TOKEN_TYPES.string) { // property key const key = propToken.value; (0, (_invariant || _load_invariant()).default)(key, 'Expected a key'); const keys = [key]; this.next(); // support multiple keys while (this.token.type === TOKEN_TYPES.comma) { this.next(); // skip comma const keyToken = this.token; if (keyToken.type !== TOKEN_TYPES.string) { this.unexpected('Expected string'); } const key = keyToken.value; (0, (_invariant || _load_invariant()).default)(key, 'Expected a key'); keys.push(key); this.next(); } const valToken = this.token; if (valToken.type === TOKEN_TYPES.colon) { // object this.next(); // parse object const val = this.parse(indent + 1); for (var _iterator = keys, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } const key = _ref; obj[key] = val; } if (indent && this.token.type !== TOKEN_TYPES.indent) { break; } } else if (isValidPropValueToken(valToken)) { // plain value for (var _iterator2 = keys, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { var _ref2; if (_isArray2) { if (_i2 >= _iterator2.length) break; _ref2 = _iterator2[_i2++]; } else { _i2 = _iterator2.next(); if (_i2.done) break; _ref2 = _i2.value; } const key = _ref2; obj[key] = valToken.value; } this.next(); } else { this.unexpected('Invalid value type'); } } else { this.unexpected(`Unknown token: ${(_util || _load_util()).default.inspect(propToken)}`); } } return obj; } } const MERGE_CONFLICT_ANCESTOR = '|||||||'; const MERGE_CONFLICT_END = '>>>>>>>'; const MERGE_CONFLICT_SEP = '======='; const MERGE_CONFLICT_START = '<<<<<<<'; /** * Extract the two versions of the lockfile from a merge conflict. */ function extractConflictVariants(str) { const variants = [[], []]; const lines = str.split(/\r?\n/g); let skip = false; while (lines.length) { const line = lines.shift(); if (line.startsWith(MERGE_CONFLICT_START)) { // get the first variant while (lines.length) { const conflictLine = lines.shift(); if (conflictLine === MERGE_CONFLICT_SEP) { skip = false; break; } else if (skip || conflictLine.startsWith(MERGE_CONFLICT_ANCESTOR)) { skip = true; continue; } else { variants[0].push(conflictLine); } } // get the second variant while (lines.length) { const conflictLine = lines.shift(); if (conflictLine.startsWith(MERGE_CONFLICT_END)) { break; } else { variants[1].push(conflictLine); } } } else { variants[0].push(line); variants[1].push(line); } } return [variants[0].join('\n'), variants[1].join('\n')]; } /** * Check if a lockfile has merge conflicts. */ function hasMergeConflicts(str) { return str.includes(MERGE_CONFLICT_START) && str.includes(MERGE_CONFLICT_SEP) && str.includes(MERGE_CONFLICT_END); } /** * Parse the lockfile. */ function parse(str, fileLoc) { const parser = new Parser(str, fileLoc); parser.next(); return parser.parse(); } /** * Parse and merge the two variants in a conflicted lockfile. */ function parseWithConflict(str, fileLoc) { const variants = extractConflictVariants(str); try { return { type: 'merge', object: Object.assign({}, parse(variants[0], fileLoc), parse(variants[1], fileLoc)) }; } catch (err) { if (err instanceof SyntaxError) { return { type: 'conflict', object: {} }; } else { throw err; } } } /***/ }), /* 82 */, /* 83 */, /* 84 */ /***/ (function(module, exports, __nested_webpack_require_146655__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _map; function _load_map() { return _map = _interopRequireDefault(__nested_webpack_require_146655__(20)); } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = __nested_webpack_require_146655__(212)('yarn'); class BlockingQueue { constructor(alias, maxConcurrency = Infinity) { this.concurrencyQueue = []; this.maxConcurrency = maxConcurrency; this.runningCount = 0; this.warnedStuck = false; this.alias = alias; this.first = true; this.running = (0, (_map || _load_map()).default)(); this.queue = (0, (_map || _load_map()).default)(); this.stuckTick = this.stuckTick.bind(this); } stillActive() { if (this.stuckTimer) { clearTimeout(this.stuckTimer); } this.stuckTimer = setTimeout(this.stuckTick, 5000); // We need to check the existence of unref because of https://github.com/facebook/jest/issues/4559 // $FlowFixMe: Node's setInterval returns a Timeout, not a Number this.stuckTimer.unref && this.stuckTimer.unref(); } stuckTick() { if (this.runningCount === 1) { this.warnedStuck = true; debug(`The ${JSON.stringify(this.alias)} blocking queue may be stuck. 5 seconds ` + `without any activity with 1 worker: ${Object.keys(this.running)[0]}`); } } push(key, factory) { if (this.first) { this.first = false; } else { this.stillActive(); } return new Promise((resolve, reject) => { // we're already running so push ourselves to the queue const queue = this.queue[key] = this.queue[key] || []; queue.push({ factory, resolve, reject }); if (!this.running[key]) { this.shift(key); } }); } shift(key) { if (this.running[key]) { delete this.running[key]; this.runningCount--; if (this.stuckTimer) { clearTimeout(this.stuckTimer); this.stuckTimer = null; } if (this.warnedStuck) { this.warnedStuck = false; debug(`${JSON.stringify(this.alias)} blocking queue finally resolved. Nothing to worry about.`); } } const queue = this.queue[key]; if (!queue) { return; } var _queue$shift = queue.shift(); const resolve = _queue$shift.resolve, reject = _queue$shift.reject, factory = _queue$shift.factory; if (!queue.length) { delete this.queue[key]; } const next = () => { this.shift(key); this.shiftConcurrencyQueue(); }; const run = () => { this.running[key] = true; this.runningCount++; factory().then(function (val) { resolve(val); next(); return null; }).catch(function (err) { reject(err); next(); }); }; this.maybePushConcurrencyQueue(run); } maybePushConcurrencyQueue(run) { if (this.runningCount < this.maxConcurrency) { run(); } else { this.concurrencyQueue.push(run); } } shiftConcurrencyQueue() { if (this.runningCount < this.maxConcurrency) { const fn = this.concurrencyQueue.shift(); if (fn) { fn(); } } } } exports.default = BlockingQueue; /***/ }), /* 85 */ /***/ (function(module, exports) { module.exports = function (exec) { try { return !!exec(); } catch (e) { return true; } }; /***/ }), /* 86 */, /* 87 */, /* 88 */, /* 89 */, /* 90 */, /* 91 */, /* 92 */, /* 93 */, /* 94 */, /* 95 */, /* 96 */, /* 97 */, /* 98 */, /* 99 */, /* 100 */ /***/ (function(module, exports, __nested_webpack_require_150302__) { // getting tag from 19.1.3.6 Object.prototype.toString() var cof = __nested_webpack_require_150302__(47); var TAG = __nested_webpack_require_150302__(13)('toStringTag'); // ES3 wrong here var ARG = cof(function () { return arguments; }()) == 'Arguments'; // fallback for IE11 Script Access Denied error var tryGet = function (it, key) { try { return it[key]; } catch (e) { /* empty */ } }; module.exports = function (it) { var O, T, B; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T // builtinTag case : ARG ? cof(O) // ES3 arguments fallback : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; }; /***/ }), /* 101 */ /***/ (function(module, exports) { // IE 8- don't enum bug keys module.exports = ( 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' ).split(','); /***/ }), /* 102 */ /***/ (function(module, exports, __nested_webpack_require_151329__) { var document = __nested_webpack_require_151329__(11).document; module.exports = document && document.documentElement; /***/ }), /* 103 */ /***/ (function(module, exports, __nested_webpack_require_151512__) { "use strict"; var LIBRARY = __nested_webpack_require_151512__(69); var $export = __nested_webpack_require_151512__(41); var redefine = __nested_webpack_require_151512__(197); var hide = __nested_webpack_require_151512__(31); var Iterators = __nested_webpack_require_151512__(35); var $iterCreate = __nested_webpack_require_151512__(188); var setToStringTag = __nested_webpack_require_151512__(71); var getPrototypeOf = __nested_webpack_require_151512__(194); var ITERATOR = __nested_webpack_require_151512__(13)('iterator'); var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next` var FF_ITERATOR = '@@iterator'; var KEYS = 'keys'; var VALUES = 'values'; var returnThis = function () { return this; }; module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { $iterCreate(Constructor, NAME, next); var getMethod = function (kind) { if (!BUGGY && kind in proto) return proto[kind]; switch (kind) { case KEYS: return function keys() { return new Constructor(this, kind); }; case VALUES: return function values() { return new Constructor(this, kind); }; } return function entries() { return new Constructor(this, kind); }; }; var TAG = NAME + ' Iterator'; var DEF_VALUES = DEFAULT == VALUES; var VALUES_BUG = false; var proto = Base.prototype; var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]; var $default = $native || getMethod(DEFAULT); var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; var methods, key, IteratorPrototype; // Fix native if ($anyNative) { IteratorPrototype = getPrototypeOf($anyNative.call(new Base())); if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { // Set @@toStringTag to native iterators setToStringTag(IteratorPrototype, TAG, true); // fix for some old engines if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis); } } // fix Array#{values, @@iterator}.name in V8 / FF if (DEF_VALUES && $native && $native.name !== VALUES) { VALUES_BUG = true; $default = function values() { return $native.call(this); }; } // Define iterator if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) { hide(proto, ITERATOR, $default); } // Plug for library Iterators[NAME] = $default; Iterators[TAG] = returnThis; if (DEFAULT) { methods = { values: DEF_VALUES ? $default : getMethod(VALUES), keys: IS_SET ? $default : getMethod(KEYS), entries: $entries }; if (FORCED) for (key in methods) { if (!(key in proto)) redefine(proto, key, methods[key]); } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); } return methods; }; /***/ }), /* 104 */ /***/ (function(module, exports) { module.exports = function (exec) { try { return { e: false, v: exec() }; } catch (e) { return { e: true, v: e }; } }; /***/ }), /* 105 */ /***/ (function(module, exports, __nested_webpack_require_154570__) { var anObject = __nested_webpack_require_154570__(27); var isObject = __nested_webpack_require_154570__(34); var newPromiseCapability = __nested_webpack_require_154570__(70); module.exports = function (C, x) { anObject(C); if (isObject(x) && x.constructor === C) return x; var promiseCapability = newPromiseCapability.f(C); var resolve = promiseCapability.resolve; resolve(x); return promiseCapability.promise; }; /***/ }), /* 106 */ /***/ (function(module, exports) { module.exports = function (bitmap, value) { return { enumerable: !(bitmap & 1), configurable: !(bitmap & 2), writable: !(bitmap & 4), value: value }; }; /***/ }), /* 107 */ /***/ (function(module, exports, __nested_webpack_require_155264__) { var core = __nested_webpack_require_155264__(23); var global = __nested_webpack_require_155264__(11); var SHARED = '__core-js_shared__'; var store = global[SHARED] || (global[SHARED] = {}); (module.exports = function (key, value) { return store[key] || (store[key] = value !== undefined ? value : {}); })('versions', []).push({ version: core.version, mode: __nested_webpack_require_155264__(69) ? 'pure' : 'global', copyright: '© 2018 Denis Pushkarev (zloirock.ru)' }); /***/ }), /* 108 */ /***/ (function(module, exports, __nested_webpack_require_155780__) { // 7.3.20 SpeciesConstructor(O, defaultConstructor) var anObject = __nested_webpack_require_155780__(27); var aFunction = __nested_webpack_require_155780__(46); var SPECIES = __nested_webpack_require_155780__(13)('species'); module.exports = function (O, D) { var C = anObject(O).constructor; var S; return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); }; /***/ }), /* 109 */ /***/ (function(module, exports, __nested_webpack_require_156212__) { var ctx = __nested_webpack_require_156212__(48); var invoke = __nested_webpack_require_156212__(185); var html = __nested_webpack_require_156212__(102); var cel = __nested_webpack_require_156212__(68); var global = __nested_webpack_require_156212__(11); var process = global.process; var setTask = global.setImmediate; var clearTask = global.clearImmediate; var MessageChannel = global.MessageChannel; var Dispatch = global.Dispatch; var counter = 0; var queue = {}; var ONREADYSTATECHANGE = 'onreadystatechange'; var defer, channel, port; var run = function () { var id = +this; // eslint-disable-next-line no-prototype-builtins if (queue.hasOwnProperty(id)) { var fn = queue[id]; delete queue[id]; fn(); } }; var listener = function (event) { run.call(event.data); }; // Node.js 0.9+ & IE10+ has setImmediate, otherwise: if (!setTask || !clearTask) { setTask = function setImmediate(fn) { var args = []; var i = 1; while (arguments.length > i) args.push(arguments[i++]); queue[++counter] = function () { // eslint-disable-next-line no-new-func invoke(typeof fn == 'function' ? fn : Function(fn), args); }; defer(counter); return counter; }; clearTask = function clearImmediate(id) { delete queue[id]; }; // Node.js 0.8- if (__nested_webpack_require_156212__(47)(process) == 'process') { defer = function (id) { process.nextTick(ctx(run, id, 1)); }; // Sphere (JS game engine) Dispatch API } else if (Dispatch && Dispatch.now) { defer = function (id) { Dispatch.now(ctx(run, id, 1)); }; // Browsers with MessageChannel, includes WebWorkers } else if (MessageChannel) { channel = new MessageChannel(); port = channel.port2; channel.port1.onmessage = listener; defer = ctx(port.postMessage, port, 1); // Browsers with postMessage, skip WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) { defer = function (id) { global.postMessage(id + '', '*'); }; global.addEventListener('message', listener, false); // IE8- } else if (ONREADYSTATECHANGE in cel('script')) { defer = function (id) { html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () { html.removeChild(this); run.call(id); }; }; // Rest old browsers } else { defer = function (id) { setTimeout(ctx(run, id, 1), 0); }; } } module.exports = { set: setTask, clear: clearTask }; /***/ }), /* 110 */ /***/ (function(module, exports, __nested_webpack_require_158799__) { // 7.1.15 ToLength var toInteger = __nested_webpack_require_158799__(73); var min = Math.min; module.exports = function (it) { return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; /***/ }), /* 111 */ /***/ (function(module, exports) { var id = 0; var px = Math.random(); module.exports = function (key) { return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; /***/ }), /* 112 */ /***/ (function(module, exports, __nested_webpack_require_159312__) { /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; exports.humanize = __nested_webpack_require_159312__(229); /** * Active `debug` instances. */ exports.instances = []; /** * The currently active debug mode names, and names to skip. */ exports.names = []; exports.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ exports.formatters = {}; /** * Select a color. * @param {String} namespace * @return {Number} * @api private */ function selectColor(namespace) { var hash = 0, i; for (i in namespace) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return exports.colors[Math.abs(hash) % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { var prevTime; function debug() { // disabled? if (!debug.enabled) return; var self = debug; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // turn the `arguments` into a proper Array var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %O args.unshift('%O'); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // apply env-specific formatting (colors, etc.) exports.formatArgs.call(self, args); var logFn = debug.log || exports.log || console.log.bind(console); logFn.apply(self, args); } debug.namespace = namespace; debug.enabled = exports.enabled(namespace); debug.useColors = exports.useColors(); debug.color = selectColor(namespace); debug.destroy = destroy; // env-specific initialization logic for debug instances if ('function' === typeof exports.init) { exports.init(debug); } exports.instances.push(debug); return debug; } function destroy () { var index = exports.instances.indexOf(this); if (index !== -1) { exports.instances.splice(index, 1); return true; } else { return false; } } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { exports.save(namespaces); exports.names = []; exports.skips = []; var i; var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); var len = split.length; for (i = 0; i < len; i++) { if (!split[i]) continue; // ignore empty strings namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { exports.names.push(new RegExp('^' + namespaces + '$')); } } for (i = 0; i < exports.instances.length; i++) { var instance = exports.instances[i]; instance.enabled = exports.enabled(instance.namespace); } } /** * Disable debug output. * * @api public */ function disable() { exports.enable(''); } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { if (name[name.length - 1] === '*') { return true; } var i, len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; } } for (i = 0, len = exports.names.length; i < len; i++) { if (exports.names[i].test(name)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } /***/ }), /* 113 */, /* 114 */ /***/ (function(module, exports, __nested_webpack_require_164302__) { module.exports = realpath realpath.realpath = realpath realpath.sync = realpathSync realpath.realpathSync = realpathSync realpath.monkeypatch = monkeypatch realpath.unmonkeypatch = unmonkeypatch var fs = __nested_webpack_require_164302__(3) var origRealpath = fs.realpath var origRealpathSync = fs.realpathSync var version = process.version var ok = /^v[0-5]\./.test(version) var old = __nested_webpack_require_164302__(217) function newError (er) { return er && er.syscall === 'realpath' && ( er.code === 'ELOOP' || er.code === 'ENOMEM' || er.code === 'ENAMETOOLONG' ) } function realpath (p, cache, cb) { if (ok) { return origRealpath(p, cache, cb) } if (typeof cache === 'function') { cb = cache cache = null } origRealpath(p, cache, function (er, result) { if (newError(er)) { old.realpath(p, cache, cb) } else { cb(er, result) } }) } function realpathSync (p, cache) { if (ok) { return origRealpathSync(p, cache) } try { return origRealpathSync(p, cache) } catch (er) { if (newError(er)) { return old.realpathSync(p, cache) } else { throw er } } } function monkeypatch () { fs.realpath = realpath fs.realpathSync = realpathSync } function unmonkeypatch () { fs.realpath = origRealpath fs.realpathSync = origRealpathSync } /***/ }), /* 115 */ /***/ (function(module, exports, __nested_webpack_require_165703__) { exports.alphasort = alphasort exports.alphasorti = alphasorti exports.setopts = setopts exports.ownProp = ownProp exports.makeAbs = makeAbs exports.finish = finish exports.mark = mark exports.isIgnored = isIgnored exports.childrenIgnored = childrenIgnored function ownProp (obj, field) { return Object.prototype.hasOwnProperty.call(obj, field) } var path = __nested_webpack_require_165703__(0) var minimatch = __nested_webpack_require_165703__(60) var isAbsolute = __nested_webpack_require_165703__(76) var Minimatch = minimatch.Minimatch function alphasorti (a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()) } function alphasort (a, b) { return a.localeCompare(b) } function setupIgnores (self, options) { self.ignore = options.ignore || [] if (!Array.isArray(self.ignore)) self.ignore = [self.ignore] if (self.ignore.length) { self.ignore = self.ignore.map(ignoreMap) } } // ignore patterns are always in dot:true mode. function ignoreMap (pattern) { var gmatcher = null if (pattern.slice(-3) === '/**') { var gpattern = pattern.replace(/(\/\*\*)+$/, '') gmatcher = new Minimatch(gpattern, { dot: true }) } return { matcher: new Minimatch(pattern, { dot: true }), gmatcher: gmatcher } } function setopts (self, pattern, options) { if (!options) options = {} // base-matching: just use globstar for that. if (options.matchBase && -1 === pattern.indexOf("/")) { if (options.noglobstar) { throw new Error("base matching requires globstar") } pattern = "**/" + pattern } self.silent = !!options.silent self.pattern = pattern self.strict = options.strict !== false self.realpath = !!options.realpath self.realpathCache = options.realpathCache || Object.create(null) self.follow = !!options.follow self.dot = !!options.dot self.mark = !!options.mark self.nodir = !!options.nodir if (self.nodir) self.mark = true self.sync = !!options.sync self.nounique = !!options.nounique self.nonull = !!options.nonull self.nosort = !!options.nosort self.nocase = !!options.nocase self.stat = !!options.stat self.noprocess = !!options.noprocess self.absolute = !!options.absolute self.maxLength = options.maxLength || Infinity self.cache = options.cache || Object.create(null) self.statCache = options.statCache || Object.create(null) self.symlinks = options.symlinks || Object.create(null) setupIgnores(self, options) self.changedCwd = false var cwd = process.cwd() if (!ownProp(options, "cwd")) self.cwd = cwd else { self.cwd = path.resolve(options.cwd) self.changedCwd = self.cwd !== cwd } self.root = options.root || path.resolve(self.cwd, "/") self.root = path.resolve(self.root) if (process.platform === "win32") self.root = self.root.replace(/\\/g, "/") // TODO: is an absolute `cwd` supposed to be resolved against `root`? // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) if (process.platform === "win32") self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") self.nomount = !!options.nomount // disable comments and negation in Minimatch. // Note that they are not supported in Glob itself anyway. options.nonegate = true options.nocomment = true self.minimatch = new Minimatch(pattern, options) self.options = self.minimatch.options } function finish (self) { var nou = self.nounique var all = nou ? [] : Object.create(null) for (var i = 0, l = self.matches.length; i < l; i ++) { var matches = self.matches[i] if (!matches || Object.keys(matches).length === 0) { if (self.nonull) { // do like the shell, and spit out the literal glob var literal = self.minimatch.globSet[i] if (nou) all.push(literal) else all[literal] = true } } else { // had matches var m = Object.keys(matches) if (nou) all.push.apply(all, m) else m.forEach(function (m) { all[m] = true }) } } if (!nou) all = Object.keys(all) if (!self.nosort) all = all.sort(self.nocase ? alphasorti : alphasort) // at *some* point we statted all of these if (self.mark) { for (var i = 0; i < all.length; i++) { all[i] = self._mark(all[i]) } if (self.nodir) { all = all.filter(function (e) { var notDir = !(/\/$/.test(e)) var c = self.cache[e] || self.cache[makeAbs(self, e)] if (notDir && c) notDir = c !== 'DIR' && !Array.isArray(c) return notDir }) } } if (self.ignore.length) all = all.filter(function(m) { return !isIgnored(self, m) }) self.found = all } function mark (self, p) { var abs = makeAbs(self, p) var c = self.cache[abs] var m = p if (c) { var isDir = c === 'DIR' || Array.isArray(c) var slash = p.slice(-1) === '/' if (isDir && !slash) m += '/' else if (!isDir && slash) m = m.slice(0, -1) if (m !== p) { var mabs = makeAbs(self, m) self.statCache[mabs] = self.statCache[abs] self.cache[mabs] = self.cache[abs] } } return m } // lotta situps... function makeAbs (self, f) { var abs = f if (f.charAt(0) === '/') { abs = path.join(self.root, f) } else if (isAbsolute(f) || f === '') { abs = f } else if (self.changedCwd) { abs = path.resolve(self.cwd, f) } else { abs = path.resolve(f) } if (process.platform === 'win32') abs = abs.replace(/\\/g, '/') return abs } // Return true, if pattern ends with globstar '**', for the accompanying parent directory. // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents function isIgnored (self, path) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) }) } function childrenIgnored (self, path) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return !!(item.gmatcher && item.gmatcher.match(path)) }) } /***/ }), /* 116 */ /***/ (function(module, exports, __nested_webpack_require_171955__) { var path = __nested_webpack_require_171955__(0); var fs = __nested_webpack_require_171955__(3); var _0777 = parseInt('0777', 8); module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; function mkdirP (p, opts, f, made) { if (typeof opts === 'function') { f = opts; opts = {}; } else if (!opts || typeof opts !== 'object') { opts = { mode: opts }; } var mode = opts.mode; var xfs = opts.fs || fs; if (mode === undefined) { mode = _0777 & (~process.umask()); } if (!made) made = null; var cb = f || function () {}; p = path.resolve(p); xfs.mkdir(p, mode, function (er) { if (!er) { made = made || p; return cb(null, made); } switch (er.code) { case 'ENOENT': mkdirP(path.dirname(p), opts, function (er, made) { if (er) cb(er, made); else mkdirP(p, opts, cb, made); }); break; // In the case of any other error, just see if there's a dir // there already. If so, then hooray! If not, then something // is borked. default: xfs.stat(p, function (er2, stat) { // if the stat fails, then that's super weird. // let the original error be the failure reason. if (er2 || !stat.isDirectory()) cb(er, made) else cb(null, made); }); break; } }); } mkdirP.sync = function sync (p, opts, made) { if (!opts || typeof opts !== 'object') { opts = { mode: opts }; } var mode = opts.mode; var xfs = opts.fs || fs; if (mode === undefined) { mode = _0777 & (~process.umask()); } if (!made) made = null; p = path.resolve(p); try { xfs.mkdirSync(p, mode); made = made || p; } catch (err0) { switch (err0.code) { case 'ENOENT' : made = sync(path.dirname(p), opts, made); sync(p, opts, made); break; // In the case of any other error, just see if there's a dir // there already. If so, then hooray! If not, then something // is borked. default: var stat; try { stat = xfs.statSync(p); } catch (err1) { throw err0; } if (!stat.isDirectory()) throw err0; break; } } return made; }; /***/ }), /* 117 */, /* 118 */, /* 119 */, /* 120 */, /* 121 */, /* 122 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = x => { if (typeof x !== 'string') { throw new TypeError('Expected a string, got ' + typeof x); } // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string // conversion translates it to FEFF (UTF-16 BOM) if (x.charCodeAt(0) === 0xFEFF) { return x.slice(1); } return x; }; /***/ }), /* 123 */ /***/ (function(module, exports) { // Returns a wrapper function that returns a wrapped callback // The wrapper function should do some stuff, and return a // presumably different callback function. // This makes sure that own properties are retained, so that // decorations and such are not lost along the way. module.exports = wrappy function wrappy (fn, cb) { if (fn && cb) return wrappy(fn)(cb) if (typeof fn !== 'function') throw new TypeError('need wrapper function') Object.keys(fn).forEach(function (k) { wrapper[k] = fn[k] }) return wrapper function wrapper() { var args = new Array(arguments.length) for (var i = 0; i < args.length; i++) { args[i] = arguments[i] } var ret = fn.apply(this, args) var cb = args[args.length-1] if (typeof ret === 'function' && ret !== cb) { Object.keys(cb).forEach(function (k) { ret[k] = cb[k] }) } return ret } } /***/ }), /* 124 */, /* 125 */, /* 126 */, /* 127 */, /* 128 */, /* 129 */, /* 130 */, /* 131 */ /***/ (function(module, exports, __nested_webpack_require_176172__) { // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = __nested_webpack_require_176172__(47); // eslint-disable-next-line no-prototype-builtins module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { return cof(it) == 'String' ? it.split('') : Object(it); }; /***/ }), /* 132 */ /***/ (function(module, exports, __nested_webpack_require_176546__) { // 19.1.2.14 / 15.2.3.14 Object.keys(O) var $keys = __nested_webpack_require_176546__(195); var enumBugKeys = __nested_webpack_require_176546__(101); module.exports = Object.keys || function keys(O) { return $keys(O, enumBugKeys); }; /***/ }), /* 133 */ /***/ (function(module, exports, __nested_webpack_require_176834__) { // 7.1.13 ToObject(argument) var defined = __nested_webpack_require_176834__(67); module.exports = function (it) { return Object(defined(it)); }; /***/ }), /* 134 */, /* 135 */, /* 136 */, /* 137 */, /* 138 */, /* 139 */, /* 140 */, /* 141 */, /* 142 */, /* 143 */, /* 144 */, /* 145 */ /***/ (function(module, exports) { module.exports = {"name":"yarn","installationMethod":"unknown","version":"1.10.0-0","license":"BSD-2-Clause","preferGlobal":true,"description":"📦🐈 Fast, reliable, and secure dependency management.","dependencies":{"@zkochan/cmd-shim":"^2.2.4","babel-runtime":"^6.26.0","bytes":"^3.0.0","camelcase":"^4.0.0","chalk":"^2.1.0","commander":"^2.9.0","death":"^1.0.0","debug":"^3.0.0","deep-equal":"^1.0.1","detect-indent":"^5.0.0","dnscache":"^1.0.1","glob":"^7.1.1","gunzip-maybe":"^1.4.0","hash-for-dep":"^1.2.3","imports-loader":"^0.8.0","ini":"^1.3.4","inquirer":"^3.0.1","invariant":"^2.2.0","is-builtin-module":"^2.0.0","is-ci":"^1.0.10","is-webpack-bundle":"^1.0.0","leven":"^2.0.0","loud-rejection":"^1.2.0","micromatch":"^2.3.11","mkdirp":"^0.5.1","node-emoji":"^1.6.1","normalize-url":"^2.0.0","npm-logical-tree":"^1.2.1","object-path":"^0.11.2","proper-lockfile":"^2.0.0","puka":"^1.0.0","read":"^1.0.7","request":"^2.87.0","request-capture-har":"^1.2.2","rimraf":"^2.5.0","semver":"^5.1.0","ssri":"^5.3.0","strip-ansi":"^4.0.0","strip-bom":"^3.0.0","tar-fs":"^1.16.0","tar-stream":"^1.6.1","uuid":"^3.0.1","v8-compile-cache":"^2.0.0","validate-npm-package-license":"^3.0.3","yn":"^2.0.0"},"devDependencies":{"babel-core":"^6.26.0","babel-eslint":"^7.2.3","babel-loader":"^6.2.5","babel-plugin-array-includes":"^2.0.3","babel-plugin-transform-builtin-extend":"^1.1.2","babel-plugin-transform-inline-imports-commonjs":"^1.0.0","babel-plugin-transform-runtime":"^6.4.3","babel-preset-env":"^1.6.0","babel-preset-flow":"^6.23.0","babel-preset-stage-0":"^6.0.0","babylon":"^6.5.0","commitizen":"^2.9.6","cz-conventional-changelog":"^2.0.0","eslint":"^4.3.0","eslint-config-fb-strict":"^22.0.0","eslint-plugin-babel":"^5.0.0","eslint-plugin-flowtype":"^2.35.0","eslint-plugin-jasmine":"^2.6.2","eslint-plugin-jest":"^21.0.0","eslint-plugin-jsx-a11y":"^6.0.2","eslint-plugin-prefer-object-spread":"^1.2.1","eslint-plugin-prettier":"^2.1.2","eslint-plugin-react":"^7.1.0","eslint-plugin-relay":"^0.0.24","eslint-plugin-yarn-internal":"file:scripts/eslint-rules","execa":"^0.10.0","flow-bin":"^0.66.0","git-release-notes":"^3.0.0","gulp":"^3.9.0","gulp-babel":"^7.0.0","gulp-if":"^2.0.1","gulp-newer":"^1.0.0","gulp-plumber":"^1.0.1","gulp-sourcemaps":"^2.2.0","gulp-util":"^3.0.7","gulp-watch":"^5.0.0","jest":"^22.4.4","jsinspect":"^0.12.6","minimatch":"^3.0.4","mock-stdin":"^0.3.0","prettier":"^1.5.2","temp":"^0.8.3","webpack":"^2.1.0-beta.25","yargs":"^6.3.0"},"resolutions":{"sshpk":"^1.14.2"},"engines":{"node":">=4.0.0"},"repository":"yarnpkg/yarn","bin":{"yarn":"./bin/yarn.js","yarnpkg":"./bin/yarn.js"},"scripts":{"build":"gulp build","build-bundle":"node ./scripts/build-webpack.js","build-chocolatey":"powershell ./scripts/build-chocolatey.ps1","build-deb":"./scripts/build-deb.sh","build-dist":"bash ./scripts/build-dist.sh","build-win-installer":"scripts\\build-windows-installer.bat","changelog":"git-release-notes $(git describe --tags --abbrev=0 $(git describe --tags --abbrev=0)^)..$(git describe --tags --abbrev=0) scripts/changelog.md","dupe-check":"yarn jsinspect ./src","lint":"eslint . && flow check","pkg-tests":"yarn --cwd packages/pkg-tests jest yarn.test.js","prettier":"eslint src __tests__ --fix","release-branch":"./scripts/release-branch.sh","test":"yarn lint && yarn test-only","test-only":"node --max_old_space_size=4096 node_modules/jest/bin/jest.js --verbose","test-only-debug":"node --inspect-brk --max_old_space_size=4096 node_modules/jest/bin/jest.js --runInBand --verbose","test-coverage":"node --max_old_space_size=4096 node_modules/jest/bin/jest.js --coverage --verbose","watch":"gulp watch","commit":"git-cz"},"jest":{"collectCoverageFrom":["src/**/*.js"],"testEnvironment":"node","modulePathIgnorePatterns":["__tests__/fixtures/","packages/pkg-tests/pkg-tests-fixtures","dist/"],"testPathIgnorePatterns":["__tests__/(fixtures|__mocks__)/","updates/","_(temp|mock|install|init|helpers).js$","packages/pkg-tests"]},"config":{"commitizen":{"path":"./node_modules/cz-conventional-changelog"}}} /***/ }), /* 146 */, /* 147 */, /* 148 */, /* 149 */, /* 150 */ /***/ (function(module, exports, __nested_webpack_require_181304__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = stringify; var _misc; function _load_misc() { return _misc = __nested_webpack_require_181304__(12); } var _constants; function _load_constants() { return _constants = __nested_webpack_require_181304__(6); } var _package; function _load_package() { return _package = __nested_webpack_require_181304__(145); } const NODE_VERSION = process.version; function shouldWrapKey(str) { return str.indexOf('true') === 0 || str.indexOf('false') === 0 || /[:\s\n\\",\[\]]/g.test(str) || /^[0-9]/g.test(str) || !/^[a-zA-Z]/g.test(str); } function maybeWrap(str) { if (typeof str === 'boolean' || typeof str === 'number' || shouldWrapKey(str)) { return JSON.stringify(str); } else { return str; } } const priorities = { name: 1, version: 2, uid: 3, resolved: 4, integrity: 5, registry: 6, dependencies: 7 }; function priorityThenAlphaSort(a, b) { if (priorities[a] || priorities[b]) { return (priorities[a] || 100) > (priorities[b] || 100) ? 1 : -1; } else { return (0, (_misc || _load_misc()).sortAlpha)(a, b); } } function _stringify(obj, options) { if (typeof obj !== 'object') { throw new TypeError(); } const indent = options.indent; const lines = []; // Sorting order needs to be consistent between runs, we run native sort by name because there are no // problems with it being unstable because there are no to keys the same // However priorities can be duplicated and native sort can shuffle things from run to run const keys = Object.keys(obj).sort(priorityThenAlphaSort); let addedKeys = []; for (let i = 0; i < keys.length; i++) { const key = keys[i]; const val = obj[key]; if (val == null || addedKeys.indexOf(key) >= 0) { continue; } const valKeys = [key]; // get all keys that have the same value equality, we only want this for objects if (typeof val === 'object') { for (let j = i + 1; j < keys.length; j++) { const key = keys[j]; if (val === obj[key]) { valKeys.push(key); } } } const keyLine = valKeys.sort((_misc || _load_misc()).sortAlpha).map(maybeWrap).join(', '); if (typeof val === 'string' || typeof val === 'boolean' || typeof val === 'number') { lines.push(`${keyLine} ${maybeWrap(val)}`); } else if (typeof val === 'object') { lines.push(`${keyLine}:\n${_stringify(val, { indent: indent + ' ' })}` + (options.topLevel ? '\n' : '')); } else { throw new TypeError(); } addedKeys = addedKeys.concat(valKeys); } return indent + lines.join(`\n${indent}`); } function stringify(obj, noHeader, enableVersions) { const val = _stringify(obj, { indent: '', topLevel: true }); if (noHeader) { return val; } const lines = []; lines.push('# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.'); lines.push(`# yarn lockfile v${(_constants || _load_constants()).LOCKFILE_VERSION}`); if (enableVersions) { lines.push(`# yarn v${(_package || _load_package()).version}`); lines.push(`# node ${NODE_VERSION}`); } lines.push('\n'); lines.push(val); return lines.join('\n'); } /***/ }), /* 151 */, /* 152 */, /* 153 */, /* 154 */, /* 155 */, /* 156 */, /* 157 */, /* 158 */, /* 159 */, /* 160 */, /* 161 */, /* 162 */, /* 163 */, /* 164 */ /***/ (function(module, exports, __nested_webpack_require_184737__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.fileDatesEqual = exports.copyFile = exports.unlink = undefined; var _asyncToGenerator2; function _load_asyncToGenerator() { return _asyncToGenerator2 = _interopRequireDefault(__nested_webpack_require_184737__(1)); } // We want to preserve file timestamps when copying a file, since yarn uses them to decide if a file has // changed compared to the cache. // There are some OS specific cases here: // * On linux, fs.copyFile does not preserve timestamps, but does on OSX and Win. // * On windows, you must open a file with write permissions to call `fs.futimes`. // * On OSX you can open with read permissions and still call `fs.futimes`. let fixTimes = (() => { var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (fd, dest, data) { const doOpen = fd === undefined; let openfd = fd ? fd : -1; if (disableTimestampCorrection === undefined) { // if timestamps match already, no correction is needed. // the need to correct timestamps varies based on OS and node versions. const destStat = yield lstat(dest); disableTimestampCorrection = fileDatesEqual(destStat.mtime, data.mtime); } if (disableTimestampCorrection) { return; } if (doOpen) { try { openfd = yield open(dest, 'a', data.mode); } catch (er) { // file is likely read-only try { openfd = yield open(dest, 'r', data.mode); } catch (err) { // We can't even open this file for reading. return; } } } try { if (openfd) { yield futimes(openfd, data.atime, data.mtime); } } catch (er) { // If `futimes` throws an exception, we probably have a case of a read-only file on Windows. // In this case we can just return. The incorrect timestamp will just cause that file to be recopied // on subsequent installs, which will effect yarn performance but not break anything. } finally { if (doOpen && openfd) { yield close(openfd); } } }); return function fixTimes(_x7, _x8, _x9) { return _ref3.apply(this, arguments); }; })(); // Compare file timestamps. // Some versions of Node on windows zero the milliseconds when utime is used. var _fs; function _load_fs() { return _fs = _interopRequireDefault(__nested_webpack_require_184737__(3)); } var _promise; function _load_promise() { return _promise = __nested_webpack_require_184737__(40); } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // This module serves as a wrapper for file operations that are inconsistant across node and OS versions. let disableTimestampCorrection = undefined; // OS dependent. will be detected on first file copy. const readFileBuffer = (0, (_promise || _load_promise()).promisify)((_fs || _load_fs()).default.readFile); const close = (0, (_promise || _load_promise()).promisify)((_fs || _load_fs()).default.close); const lstat = (0, (_promise || _load_promise()).promisify)((_fs || _load_fs()).default.lstat); const open = (0, (_promise || _load_promise()).promisify)((_fs || _load_fs()).default.open); const futimes = (0, (_promise || _load_promise()).promisify)((_fs || _load_fs()).default.futimes); const write = (0, (_promise || _load_promise()).promisify)((_fs || _load_fs()).default.write); const unlink = exports.unlink = (0, (_promise || _load_promise()).promisify)(__nested_webpack_require_184737__(233)); /** * Unlinks the destination to force a recreation. This is needed on case-insensitive file systems * to force the correct naming when the filename has changed only in character-casing. (Jest -> jest). */ const copyFile = exports.copyFile = (() => { var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data, cleanup) { try { yield unlink(data.dest); yield copyFilePoly(data.src, data.dest, 0, data); } finally { if (cleanup) { cleanup(); } } }); return function copyFile(_x, _x2) { return _ref.apply(this, arguments); }; })(); // Node 8.5.0 introduced `fs.copyFile` which is much faster, so use that when available. // Otherwise we fall back to reading and writing files as buffers. const copyFilePoly = (src, dest, flags, data) => { if ((_fs || _load_fs()).default.copyFile) { return new Promise((resolve, reject) => (_fs || _load_fs()).default.copyFile(src, dest, flags, err => { if (err) { reject(err); } else { fixTimes(undefined, dest, data).then(() => resolve()).catch(ex => reject(ex)); } })); } else { return copyWithBuffer(src, dest, flags, data); } }; const copyWithBuffer = (() => { var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (src, dest, flags, data) { // Use open -> write -> futimes -> close sequence to avoid opening the file twice: // one with writeFile and one with utimes const fd = yield open(dest, 'w', data.mode); try { const buffer = yield readFileBuffer(src); yield write(fd, buffer, 0, buffer.length); yield fixTimes(fd, dest, data); } finally { yield close(fd); } }); return function copyWithBuffer(_x3, _x4, _x5, _x6) { return _ref2.apply(this, arguments); }; })();const fileDatesEqual = exports.fileDatesEqual = (a, b) => { const aTime = a.getTime(); const bTime = b.getTime(); if (process.platform !== 'win32') { return aTime === bTime; } // See https://github.com/nodejs/node/pull/12607 // Submillisecond times from stat and utimes are truncated on Windows, // causing a file with mtime 8.0079998 and 8.0081144 to become 8.007 and 8.008 // and making it impossible to update these files to their correct timestamps. if (Math.abs(aTime - bTime) <= 1) { return true; } const aTimeSec = Math.floor(aTime / 1000); const bTimeSec = Math.floor(bTime / 1000); // See https://github.com/nodejs/node/issues/2069 // Some versions of Node on windows zero the milliseconds when utime is used // So if any of the time has a milliseconds part of zero we suspect that the // bug is present and compare only seconds. if (aTime - aTimeSec * 1000 === 0 || bTime - bTimeSec * 1000 === 0) { return aTimeSec === bTimeSec; } return aTime === bTime; }; /***/ }), /* 165 */, /* 166 */, /* 167 */, /* 168 */, /* 169 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isFakeRoot = isFakeRoot; exports.isRootUser = isRootUser; function getUid() { if (process.platform !== 'win32' && process.getuid) { return process.getuid(); } return null; } exports.default = isRootUser(getUid()) && !isFakeRoot(); function isFakeRoot() { return Boolean(process.env.FAKEROOTKEY); } function isRootUser(uid) { return uid === 0; } /***/ }), /* 170 */, /* 171 */ /***/ (function(module, exports, __nested_webpack_require_191776__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getDataDir = getDataDir; exports.getCacheDir = getCacheDir; exports.getConfigDir = getConfigDir; const path = __nested_webpack_require_191776__(0); const userHome = __nested_webpack_require_191776__(45).default; const FALLBACK_CONFIG_DIR = path.join(userHome, '.config', 'yarn'); const FALLBACK_CACHE_DIR = path.join(userHome, '.cache', 'yarn'); function getDataDir() { if (process.platform === 'win32') { const WIN32_APPDATA_DIR = getLocalAppDataDir(); return WIN32_APPDATA_DIR == null ? FALLBACK_CONFIG_DIR : path.join(WIN32_APPDATA_DIR, 'Data'); } else if (process.env.XDG_DATA_HOME) { return path.join(process.env.XDG_DATA_HOME, 'yarn'); } else { // This could arguably be ~/Library/Application Support/Yarn on Macs, // but that feels unintuitive for a cli tool // Instead, use our prior fallback. Some day this could be // path.join(userHome, '.local', 'share', 'yarn') // or return path.join(WIN32_APPDATA_DIR, 'Data') on win32 return FALLBACK_CONFIG_DIR; } } function getCacheDir() { if (process.platform === 'win32') { // process.env.TEMP also exists, but most apps put caches here return path.join(getLocalAppDataDir() || path.join(userHome, 'AppData', 'Local', 'Yarn'), 'Cache'); } else if (process.env.XDG_CACHE_HOME) { return path.join(process.env.XDG_CACHE_HOME, 'yarn'); } else if (process.platform === 'darwin') { return path.join(userHome, 'Library', 'Caches', 'Yarn'); } else { return FALLBACK_CACHE_DIR; } } function getConfigDir() { if (process.platform === 'win32') { // Use our prior fallback. Some day this could be // return path.join(WIN32_APPDATA_DIR, 'Config') const WIN32_APPDATA_DIR = getLocalAppDataDir(); return WIN32_APPDATA_DIR == null ? FALLBACK_CONFIG_DIR : path.join(WIN32_APPDATA_DIR, 'Config'); } else if (process.env.XDG_CONFIG_HOME) { return path.join(process.env.XDG_CONFIG_HOME, 'yarn'); } else { return FALLBACK_CONFIG_DIR; } } function getLocalAppDataDir() { return process.env.LOCALAPPDATA ? path.join(process.env.LOCALAPPDATA, 'Yarn') : null; } /***/ }), /* 172 */, /* 173 */ /***/ (function(module, exports, __nested_webpack_require_194030__) { module.exports = { "default": __nested_webpack_require_194030__(179), __esModule: true }; /***/ }), /* 174 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = balanced; function balanced(a, b, str) { if (a instanceof RegExp) a = maybeMatch(a, str); if (b instanceof RegExp) b = maybeMatch(b, str); var r = range(a, b, str); return r && { start: r[0], end: r[1], pre: str.slice(0, r[0]), body: str.slice(r[0] + a.length, r[1]), post: str.slice(r[1] + b.length) }; } function maybeMatch(reg, str) { var m = str.match(reg); return m ? m[0] : null; } balanced.range = range; function range(a, b, str) { var begs, beg, left, right, result; var ai = str.indexOf(a); var bi = str.indexOf(b, ai + 1); var i = ai; if (ai >= 0 && bi > 0) { begs = []; left = str.length; while (i >= 0 && !result) { if (i == ai) { begs.push(i); ai = str.indexOf(a, i + 1); } else if (begs.length == 1) { result = [ begs.pop(), bi ]; } else { beg = begs.pop(); if (beg < left) { left = beg; right = bi; } bi = str.indexOf(b, i + 1); } i = ai < bi && ai >= 0 ? ai : bi; } if (begs.length) { result = [ left, right ]; } } return result; } /***/ }), /* 175 */ /***/ (function(module, exports, __nested_webpack_require_195438__) { var concatMap = __nested_webpack_require_195438__(178); var balanced = __nested_webpack_require_195438__(174); module.exports = expandTop; var escSlash = '\0SLASH'+Math.random()+'\0'; var escOpen = '\0OPEN'+Math.random()+'\0'; var escClose = '\0CLOSE'+Math.random()+'\0'; var escComma = '\0COMMA'+Math.random()+'\0'; var escPeriod = '\0PERIOD'+Math.random()+'\0'; function numeric(str) { return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); } function escapeBraces(str) { return str.split('\\\\').join(escSlash) .split('\\{').join(escOpen) .split('\\}').join(escClose) .split('\\,').join(escComma) .split('\\.').join(escPeriod); } function unescapeBraces(str) { return str.split(escSlash).join('\\') .split(escOpen).join('{') .split(escClose).join('}') .split(escComma).join(',') .split(escPeriod).join('.'); } // Basically just str.split(","), but handling cases // where we have nested braced sections, which should be // treated as individual members, like {a,{b,c},d} function parseCommaParts(str) { if (!str) return ['']; var parts = []; var m = balanced('{', '}', str); if (!m) return str.split(','); var pre = m.pre; var body = m.body; var post = m.post; var p = pre.split(','); p[p.length-1] += '{' + body + '}'; var postParts = parseCommaParts(post); if (post.length) { p[p.length-1] += postParts.shift(); p.push.apply(p, postParts); } parts.push.apply(parts, p); return parts; } function expandTop(str) { if (!str) return []; // I don't know why Bash 4.3 does this, but it does. // Anything starting with {} will have the first two bytes preserved // but *only* at the top level, so {},a}b will not expand to anything, // but a{},b}c will be expanded to [a}c,abc]. // One could argue that this is a bug in Bash, but since the goal of // this module is to match Bash's rules, we escape a leading {} if (str.substr(0, 2) === '{}') { str = '\\{\\}' + str.substr(2); } return expand(escapeBraces(str), true).map(unescapeBraces); } function identity(e) { return e; } function embrace(str) { return '{' + str + '}'; } function isPadded(el) { return /^-?0\d/.test(el); } function lte(i, y) { return i <= y; } function gte(i, y) { return i >= y; } function expand(str, isTop) { var expansions = []; var m = balanced('{', '}', str); if (!m || /\$$/.test(m.pre)) return [str]; var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(',') >= 0; if (!isSequence && !isOptions) { // {a},b} if (m.post.match(/,.*\}/)) { str = m.pre + '{' + m.body + escClose + m.post; return expand(str); } return [str]; } var n; if (isSequence) { n = m.body.split(/\.\./); } else { n = parseCommaParts(m.body); if (n.length === 1) { // x{{a,b}}y ==> x{a}y x{b}y n = expand(n[0], false).map(embrace); if (n.length === 1) { var post = m.post.length ? expand(m.post, false) : ['']; return post.map(function(p) { return m.pre + n[0] + p; }); } } } // at this point, n is the parts, and we know it's not a comma set // with a single entry. // no need to expand pre, since it is guaranteed to be free of brace-sets var pre = m.pre; var post = m.post.length ? expand(m.post, false) : ['']; var N; if (isSequence) { var x = numeric(n[0]); var y = numeric(n[1]); var width = Math.max(n[0].length, n[1].length) var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1; var test = lte; var reverse = y < x; if (reverse) { incr *= -1; test = gte; } var pad = n.some(isPadded); N = []; for (var i = x; test(i, y); i += incr) { var c; if (isAlphaSequence) { c = String.fromCharCode(i); if (c === '\\') c = ''; } else { c = String(i); if (pad) { var need = width - c.length; if (need > 0) { var z = new Array(need + 1).join('0'); if (i < 0) c = '-' + z + c.slice(1); else c = z + c; } } } N.push(c); } } else { N = concatMap(n, function(el) { return expand(el, false) }); } for (var j = 0; j < N.length; j++) { for (var k = 0; k < post.length; k++) { var expansion = pre + N[j] + post[k]; if (!isTop || isSequence || expansion) expansions.push(expansion); } } return expansions; } /***/ }), /* 176 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function preserveCamelCase(str) { let isLastCharLower = false; let isLastCharUpper = false; let isLastLastCharUpper = false; for (let i = 0; i < str.length; i++) { const c = str[i]; if (isLastCharLower && /[a-zA-Z]/.test(c) && c.toUpperCase() === c) { str = str.substr(0, i) + '-' + str.substr(i); isLastCharLower = false; isLastLastCharUpper = isLastCharUpper; isLastCharUpper = true; i++; } else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(c) && c.toLowerCase() === c) { str = str.substr(0, i - 1) + '-' + str.substr(i - 1); isLastLastCharUpper = isLastCharUpper; isLastCharUpper = false; isLastCharLower = true; } else { isLastCharLower = c.toLowerCase() === c; isLastLastCharUpper = isLastCharUpper; isLastCharUpper = c.toUpperCase() === c; } } return str; } module.exports = function (str) { if (arguments.length > 1) { str = Array.from(arguments) .map(x => x.trim()) .filter(x => x.length) .join('-'); } else { str = str.trim(); } if (str.length === 0) { return ''; } if (str.length === 1) { return str.toLowerCase(); } if (/^[a-z0-9]+$/.test(str)) { return str; } const hasUpperCase = str !== str.toLowerCase(); if (hasUpperCase) { str = preserveCamelCase(str); } return str .replace(/^[_.\- ]+/, '') .toLowerCase() .replace(/[_.\- ]+(\w|$)/g, (m, p1) => p1.toUpperCase()); }; /***/ }), /* 177 */, /* 178 */ /***/ (function(module, exports) { module.exports = function (xs, fn) { var res = []; for (var i = 0; i < xs.length; i++) { var x = fn(xs[i], i); if (isArray(x)) res.push.apply(res, x); else res.push(x); } return res; }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; /***/ }), /* 179 */ /***/ (function(module, exports, __nested_webpack_require_202224__) { __nested_webpack_require_202224__(205); __nested_webpack_require_202224__(207); __nested_webpack_require_202224__(210); __nested_webpack_require_202224__(206); __nested_webpack_require_202224__(208); __nested_webpack_require_202224__(209); module.exports = __nested_webpack_require_202224__(23).Promise; /***/ }), /* 180 */ /***/ (function(module, exports) { module.exports = function () { /* empty */ }; /***/ }), /* 181 */ /***/ (function(module, exports) { module.exports = function (it, Constructor, name, forbiddenField) { if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) { throw TypeError(name + ': incorrect invocation!'); } return it; }; /***/ }), /* 182 */ /***/ (function(module, exports, __nested_webpack_require_202908__) { // false -> Array#indexOf // true -> Array#includes var toIObject = __nested_webpack_require_202908__(74); var toLength = __nested_webpack_require_202908__(110); var toAbsoluteIndex = __nested_webpack_require_202908__(200); module.exports = function (IS_INCLUDES) { return function ($this, el, fromIndex) { var O = toIObject($this); var length = toLength(O.length); var index = toAbsoluteIndex(fromIndex, length); var value; // Array#includes uses SameValueZero equality algorithm // eslint-disable-next-line no-self-compare if (IS_INCLUDES && el != el) while (length > index) { value = O[index++]; // eslint-disable-next-line no-self-compare if (value != value) return true; // Array#indexOf ignores holes, Array#includes - not } else for (;length > index; index++) if (IS_INCLUDES || index in O) { if (O[index] === el) return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; /***/ }), /* 183 */ /***/ (function(module, exports, __nested_webpack_require_203904__) { var ctx = __nested_webpack_require_203904__(48); var call = __nested_webpack_require_203904__(187); var isArrayIter = __nested_webpack_require_203904__(186); var anObject = __nested_webpack_require_203904__(27); var toLength = __nested_webpack_require_203904__(110); var getIterFn = __nested_webpack_require_203904__(203); var BREAK = {}; var RETURN = {}; var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) { var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable); var f = ctx(fn, that, entries ? 2 : 1); var index = 0; var length, step, iterator, result; if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!'); // fast case for arrays with default iterator if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) { result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); if (result === BREAK || result === RETURN) return result; } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) { result = call(iterator, f, step.value, entries); if (result === BREAK || result === RETURN) return result; } }; exports.BREAK = BREAK; exports.RETURN = RETURN; /***/ }), /* 184 */ /***/ (function(module, exports, __nested_webpack_require_205151__) { module.exports = !__nested_webpack_require_205151__(33) && !__nested_webpack_require_205151__(85)(function () { return Object.defineProperty(__nested_webpack_require_205151__(68)('div'), 'a', { get: function () { return 7; } }).a != 7; }); /***/ }), /* 185 */ /***/ (function(module, exports) { // fast apply, http://jsperf.lnkit.com/fast-apply/5 module.exports = function (fn, args, that) { var un = that === undefined; switch (args.length) { case 0: return un ? fn() : fn.call(that); case 1: return un ? fn(args[0]) : fn.call(that, args[0]); case 2: return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]); case 3: return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]); case 4: return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]); } return fn.apply(that, args); }; /***/ }), /* 186 */ /***/ (function(module, exports, __nested_webpack_require_206189__) { // check on default Array iterator var Iterators = __nested_webpack_require_206189__(35); var ITERATOR = __nested_webpack_require_206189__(13)('iterator'); var ArrayProto = Array.prototype; module.exports = function (it) { return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); }; /***/ }), /* 187 */ /***/ (function(module, exports, __nested_webpack_require_206553__) { // call something on iterator step with safe closing on error var anObject = __nested_webpack_require_206553__(27); module.exports = function (iterator, fn, value, entries) { try { return entries ? fn(anObject(value)[0], value[1]) : fn(value); // 7.4.6 IteratorClose(iterator, completion) } catch (e) { var ret = iterator['return']; if (ret !== undefined) anObject(ret.call(iterator)); throw e; } }; /***/ }), /* 188 */ /***/ (function(module, exports, __nested_webpack_require_207042__) { "use strict"; var create = __nested_webpack_require_207042__(192); var descriptor = __nested_webpack_require_207042__(106); var setToStringTag = __nested_webpack_require_207042__(71); var IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() __nested_webpack_require_207042__(31)(IteratorPrototype, __nested_webpack_require_207042__(13)('iterator'), function () { return this; }); module.exports = function (Constructor, NAME, next) { Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) }); setToStringTag(Constructor, NAME + ' Iterator'); }; /***/ }), /* 189 */ /***/ (function(module, exports, __nested_webpack_require_207645__) { var ITERATOR = __nested_webpack_require_207645__(13)('iterator'); var SAFE_CLOSING = false; try { var riter = [7][ITERATOR](); riter['return'] = function () { SAFE_CLOSING = true; }; // eslint-disable-next-line no-throw-literal Array.from(riter, function () { throw 2; }); } catch (e) { /* empty */ } module.exports = function (exec, skipClosing) { if (!skipClosing && !SAFE_CLOSING) return false; var safe = false; try { var arr = [7]; var iter = arr[ITERATOR](); iter.next = function () { return { done: safe = true }; }; arr[ITERATOR] = function () { return iter; }; exec(arr); } catch (e) { /* empty */ } return safe; }; /***/ }), /* 190 */ /***/ (function(module, exports) { module.exports = function (done, value) { return { value: value, done: !!done }; }; /***/ }), /* 191 */ /***/ (function(module, exports, __nested_webpack_require_208519__) { var global = __nested_webpack_require_208519__(11); var macrotask = __nested_webpack_require_208519__(109).set; var Observer = global.MutationObserver || global.WebKitMutationObserver; var process = global.process; var Promise = global.Promise; var isNode = __nested_webpack_require_208519__(47)(process) == 'process'; module.exports = function () { var head, last, notify; var flush = function () { var parent, fn; if (isNode && (parent = process.domain)) parent.exit(); while (head) { fn = head.fn; head = head.next; try { fn(); } catch (e) { if (head) notify(); else last = undefined; throw e; } } last = undefined; if (parent) parent.enter(); }; // Node.js if (isNode) { notify = function () { process.nextTick(flush); }; // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339 } else if (Observer && !(global.navigator && global.navigator.standalone)) { var toggle = true; var node = document.createTextNode(''); new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new notify = function () { node.data = toggle = !toggle; }; // environments with maybe non-completely correct, but existent Promise } else if (Promise && Promise.resolve) { // Promise.resolve without an argument throws an error in LG WebOS 2 var promise = Promise.resolve(undefined); notify = function () { promise.then(flush); }; // for other environments - macrotask based on: // - setImmediate // - MessageChannel // - window.postMessag // - onreadystatechange // - setTimeout } else { notify = function () { // strange IE + webpack dev server bug - use .call(global) macrotask.call(global, flush); }; } return function (fn) { var task = { fn: fn, next: undefined }; if (last) last.next = task; if (!head) { head = task; notify(); } last = task; }; }; /***/ }), /* 192 */ /***/ (function(module, exports, __nested_webpack_require_210595__) { // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) var anObject = __nested_webpack_require_210595__(27); var dPs = __nested_webpack_require_210595__(193); var enumBugKeys = __nested_webpack_require_210595__(101); var IE_PROTO = __nested_webpack_require_210595__(72)('IE_PROTO'); var Empty = function () { /* empty */ }; var PROTOTYPE = 'prototype'; // Create object with fake `null` prototype: use iframe Object with cleared prototype var createDict = function () { // Thrash, waste and sodomy: IE GC bug var iframe = __nested_webpack_require_210595__(68)('iframe'); var i = enumBugKeys.length; var lt = '<'; var gt = '>'; var iframeDocument; iframe.style.display = 'none'; __nested_webpack_require_210595__(102).appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]]; return createDict(); }; module.exports = Object.create || function create(O, Properties) { var result; if (O !== null) { Empty[PROTOTYPE] = anObject(O); result = new Empty(); Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO] = O; } else result = createDict(); return Properties === undefined ? result : dPs(result, Properties); }; /***/ }), /* 193 */ /***/ (function(module, exports, __nested_webpack_require_212180__) { var dP = __nested_webpack_require_212180__(50); var anObject = __nested_webpack_require_212180__(27); var getKeys = __nested_webpack_require_212180__(132); module.exports = __nested_webpack_require_212180__(33) ? Object.defineProperties : function defineProperties(O, Properties) { anObject(O); var keys = getKeys(Properties); var length = keys.length; var i = 0; var P; while (length > i) dP.f(O, P = keys[i++], Properties[P]); return O; }; /***/ }), /* 194 */ /***/ (function(module, exports, __nested_webpack_require_212660__) { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) var has = __nested_webpack_require_212660__(49); var toObject = __nested_webpack_require_212660__(133); var IE_PROTO = __nested_webpack_require_212660__(72)('IE_PROTO'); var ObjectProto = Object.prototype; module.exports = Object.getPrototypeOf || function (O) { O = toObject(O); if (has(O, IE_PROTO)) return O[IE_PROTO]; if (typeof O.constructor == 'function' && O instanceof O.constructor) { return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }; /***/ }), /* 195 */ /***/ (function(module, exports, __nested_webpack_require_213238__) { var has = __nested_webpack_require_213238__(49); var toIObject = __nested_webpack_require_213238__(74); var arrayIndexOf = __nested_webpack_require_213238__(182)(false); var IE_PROTO = __nested_webpack_require_213238__(72)('IE_PROTO'); module.exports = function (object, names) { var O = toIObject(object); var i = 0; var result = []; var key; for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key); // Don't enum bug & hidden keys while (names.length > i) if (has(O, key = names[i++])) { ~arrayIndexOf(result, key) || result.push(key); } return result; }; /***/ }), /* 196 */ /***/ (function(module, exports, __nested_webpack_require_213854__) { var hide = __nested_webpack_require_213854__(31); module.exports = function (target, src, safe) { for (var key in src) { if (safe && target[key]) target[key] = src[key]; else hide(target, key, src[key]); } return target; }; /***/ }), /* 197 */ /***/ (function(module, exports, __nested_webpack_require_214155__) { module.exports = __nested_webpack_require_214155__(31); /***/ }), /* 198 */ /***/ (function(module, exports, __nested_webpack_require_214276__) { "use strict"; var global = __nested_webpack_require_214276__(11); var core = __nested_webpack_require_214276__(23); var dP = __nested_webpack_require_214276__(50); var DESCRIPTORS = __nested_webpack_require_214276__(33); var SPECIES = __nested_webpack_require_214276__(13)('species'); module.exports = function (KEY) { var C = typeof core[KEY] == 'function' ? core[KEY] : global[KEY]; if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, { configurable: true, get: function () { return this; } }); }; /***/ }), /* 199 */ /***/ (function(module, exports, __nested_webpack_require_214803__) { var toInteger = __nested_webpack_require_214803__(73); var defined = __nested_webpack_require_214803__(67); // true -> String#at // false -> String#codePointAt module.exports = function (TO_STRING) { return function (that, pos) { var s = String(defined(that)); var i = toInteger(pos); var l = s.length; var a, b; if (i < 0 || i >= l) return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; /***/ }), /* 200 */ /***/ (function(module, exports, __nested_webpack_require_215503__) { var toInteger = __nested_webpack_require_215503__(73); var max = Math.max; var min = Math.min; module.exports = function (index, length) { index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }; /***/ }), /* 201 */ /***/ (function(module, exports, __nested_webpack_require_215804__) { // 7.1.1 ToPrimitive(input [, PreferredType]) var isObject = __nested_webpack_require_215804__(34); // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string module.exports = function (it, S) { if (!isObject(it)) return it; var fn, val; if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val; if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; throw TypeError("Can't convert object to primitive value"); }; /***/ }), /* 202 */ /***/ (function(module, exports, __nested_webpack_require_216538__) { var global = __nested_webpack_require_216538__(11); var navigator = global.navigator; module.exports = navigator && navigator.userAgent || ''; /***/ }), /* 203 */ /***/ (function(module, exports, __nested_webpack_require_216747__) { var classof = __nested_webpack_require_216747__(100); var ITERATOR = __nested_webpack_require_216747__(13)('iterator'); var Iterators = __nested_webpack_require_216747__(35); module.exports = __nested_webpack_require_216747__(23).getIteratorMethod = function (it) { if (it != undefined) return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)]; }; /***/ }), /* 204 */ /***/ (function(module, exports, __nested_webpack_require_217137__) { "use strict"; var addToUnscopables = __nested_webpack_require_217137__(180); var step = __nested_webpack_require_217137__(190); var Iterators = __nested_webpack_require_217137__(35); var toIObject = __nested_webpack_require_217137__(74); // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() module.exports = __nested_webpack_require_217137__(103)(Array, 'Array', function (iterated, kind) { this._t = toIObject(iterated); // target this._i = 0; // next index this._k = kind; // kind // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function () { var O = this._t; var kind = this._k; var index = this._i++; if (!O || index >= O.length) { this._t = undefined; return step(1); } if (kind == 'keys') return step(0, index); if (kind == 'values') return step(0, O[index]); return step(0, [index, O[index]]); }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators.Arguments = Iterators.Array; addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); /***/ }), /* 205 */ /***/ (function(module, exports) { /***/ }), /* 206 */ /***/ (function(module, exports, __nested_webpack_require_218382__) { "use strict"; var LIBRARY = __nested_webpack_require_218382__(69); var global = __nested_webpack_require_218382__(11); var ctx = __nested_webpack_require_218382__(48); var classof = __nested_webpack_require_218382__(100); var $export = __nested_webpack_require_218382__(41); var isObject = __nested_webpack_require_218382__(34); var aFunction = __nested_webpack_require_218382__(46); var anInstance = __nested_webpack_require_218382__(181); var forOf = __nested_webpack_require_218382__(183); var speciesConstructor = __nested_webpack_require_218382__(108); var task = __nested_webpack_require_218382__(109).set; var microtask = __nested_webpack_require_218382__(191)(); var newPromiseCapabilityModule = __nested_webpack_require_218382__(70); var perform = __nested_webpack_require_218382__(104); var userAgent = __nested_webpack_require_218382__(202); var promiseResolve = __nested_webpack_require_218382__(105); var PROMISE = 'Promise'; var TypeError = global.TypeError; var process = global.process; var versions = process && process.versions; var v8 = versions && versions.v8 || ''; var $Promise = global[PROMISE]; var isNode = classof(process) == 'process'; var empty = function () { /* empty */ }; var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper; var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f; var USE_NATIVE = !!function () { try { // correct subclassing with @@species support var promise = $Promise.resolve(1); var FakePromise = (promise.constructor = {})[__nested_webpack_require_218382__(13)('species')] = function (exec) { exec(empty, empty); }; // unhandled rejections tracking support, NodeJS Promise without it fails @@species test return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise // v8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables // https://bugs.chromium.org/p/chromium/issues/detail?id=830565 // we can't detect it synchronously, so just check versions && v8.indexOf('6.6') !== 0 && userAgent.indexOf('Chrome/66') === -1; } catch (e) { /* empty */ } }(); // helpers var isThenable = function (it) { var then; return isObject(it) && typeof (then = it.then) == 'function' ? then : false; }; var notify = function (promise, isReject) { if (promise._n) return; promise._n = true; var chain = promise._c; microtask(function () { var value = promise._v; var ok = promise._s == 1; var i = 0; var run = function (reaction) { var handler = ok ? reaction.ok : reaction.fail; var resolve = reaction.resolve; var reject = reaction.reject; var domain = reaction.domain; var result, then, exited; try { if (handler) { if (!ok) { if (promise._h == 2) onHandleUnhandled(promise); promise._h = 1; } if (handler === true) result = value; else { if (domain) domain.enter(); result = handler(value); // may throw if (domain) { domain.exit(); exited = true; } } if (result === reaction.promise) { reject(TypeError('Promise-chain cycle')); } else if (then = isThenable(result)) { then.call(result, resolve, reject); } else resolve(result); } else reject(value); } catch (e) { if (domain && !exited) domain.exit(); reject(e); } }; while (chain.length > i) run(chain[i++]); // variable length - can't use forEach promise._c = []; promise._n = false; if (isReject && !promise._h) onUnhandled(promise); }); }; var onUnhandled = function (promise) { task.call(global, function () { var value = promise._v; var unhandled = isUnhandled(promise); var result, handler, console; if (unhandled) { result = perform(function () { if (isNode) { process.emit('unhandledRejection', value, promise); } else if (handler = global.onunhandledrejection) { handler({ promise: promise, reason: value }); } else if ((console = global.console) && console.error) { console.error('Unhandled promise rejection', value); } }); // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should promise._h = isNode || isUnhandled(promise) ? 2 : 1; } promise._a = undefined; if (unhandled && result.e) throw result.v; }); }; var isUnhandled = function (promise) { return promise._h !== 1 && (promise._a || promise._c).length === 0; }; var onHandleUnhandled = function (promise) { task.call(global, function () { var handler; if (isNode) { process.emit('rejectionHandled', promise); } else if (handler = global.onrejectionhandled) { handler({ promise: promise, reason: promise._v }); } }); }; var $reject = function (value) { var promise = this; if (promise._d) return; promise._d = true; promise = promise._w || promise; // unwrap promise._v = value; promise._s = 2; if (!promise._a) promise._a = promise._c.slice(); notify(promise, true); }; var $resolve = function (value) { var promise = this; var then; if (promise._d) return; promise._d = true; promise = promise._w || promise; // unwrap try { if (promise === value) throw TypeError("Promise can't be resolved itself"); if (then = isThenable(value)) { microtask(function () { var wrapper = { _w: promise, _d: false }; // wrap try { then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); } catch (e) { $reject.call(wrapper, e); } }); } else { promise._v = value; promise._s = 1; notify(promise, false); } } catch (e) { $reject.call({ _w: promise, _d: false }, e); // wrap } }; // constructor polyfill if (!USE_NATIVE) { // 25.4.3.1 Promise(executor) $Promise = function Promise(executor) { anInstance(this, $Promise, PROMISE, '_h'); aFunction(executor); Internal.call(this); try { executor(ctx($resolve, this, 1), ctx($reject, this, 1)); } catch (err) { $reject.call(this, err); } }; // eslint-disable-next-line no-unused-vars Internal = function Promise(executor) { this._c = []; // <- awaiting reactions this._a = undefined; // <- checked in isUnhandled reactions this._s = 0; // <- state this._d = false; // <- done this._v = undefined; // <- value this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled this._n = false; // <- notify }; Internal.prototype = __nested_webpack_require_218382__(196)($Promise.prototype, { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function then(onFulfilled, onRejected) { var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; reaction.fail = typeof onRejected == 'function' && onRejected; reaction.domain = isNode ? process.domain : undefined; this._c.push(reaction); if (this._a) this._a.push(reaction); if (this._s) notify(this, false); return reaction.promise; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function (onRejected) { return this.then(undefined, onRejected); } }); OwnPromiseCapability = function () { var promise = new Internal(); this.promise = promise; this.resolve = ctx($resolve, promise, 1); this.reject = ctx($reject, promise, 1); }; newPromiseCapabilityModule.f = newPromiseCapability = function (C) { return C === $Promise || C === Wrapper ? new OwnPromiseCapability(C) : newGenericPromiseCapability(C); }; } $export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise }); __nested_webpack_require_218382__(71)($Promise, PROMISE); __nested_webpack_require_218382__(198)(PROMISE); Wrapper = __nested_webpack_require_218382__(23)[PROMISE]; // statics $export($export.S + $export.F * !USE_NATIVE, PROMISE, { // 25.4.4.5 Promise.reject(r) reject: function reject(r) { var capability = newPromiseCapability(this); var $$reject = capability.reject; $$reject(r); return capability.promise; } }); $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { // 25.4.4.6 Promise.resolve(x) resolve: function resolve(x) { return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x); } }); $export($export.S + $export.F * !(USE_NATIVE && __nested_webpack_require_218382__(189)(function (iter) { $Promise.all(iter)['catch'](empty); })), PROMISE, { // 25.4.4.1 Promise.all(iterable) all: function all(iterable) { var C = this; var capability = newPromiseCapability(C); var resolve = capability.resolve; var reject = capability.reject; var result = perform(function () { var values = []; var index = 0; var remaining = 1; forOf(iterable, false, function (promise) { var $index = index++; var alreadyCalled = false; values.push(undefined); remaining++; C.resolve(promise).then(function (value) { if (alreadyCalled) return; alreadyCalled = true; values[$index] = value; --remaining || resolve(values); }, reject); }); --remaining || resolve(values); }); if (result.e) reject(result.v); return capability.promise; }, // 25.4.4.4 Promise.race(iterable) race: function race(iterable) { var C = this; var capability = newPromiseCapability(C); var reject = capability.reject; var result = perform(function () { forOf(iterable, false, function (promise) { C.resolve(promise).then(capability.resolve, reject); }); }); if (result.e) reject(result.v); return capability.promise; } }); /***/ }), /* 207 */ /***/ (function(module, exports, __nested_webpack_require_228275__) { "use strict"; var $at = __nested_webpack_require_228275__(199)(true); // 21.1.3.27 String.prototype[@@iterator]() __nested_webpack_require_228275__(103)(String, 'String', function (iterated) { this._t = String(iterated); // target this._i = 0; // next index // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function () { var O = this._t; var index = this._i; var point; if (index >= O.length) return { value: undefined, done: true }; point = $at(O, index); this._i += point.length; return { value: point, done: false }; }); /***/ }), /* 208 */ /***/ (function(module, exports, __nested_webpack_require_228886__) { "use strict"; // https://github.com/tc39/proposal-promise-finally var $export = __nested_webpack_require_228886__(41); var core = __nested_webpack_require_228886__(23); var global = __nested_webpack_require_228886__(11); var speciesConstructor = __nested_webpack_require_228886__(108); var promiseResolve = __nested_webpack_require_228886__(105); $export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) { var C = speciesConstructor(this, core.Promise || global.Promise); var isFunction = typeof onFinally == 'function'; return this.then( isFunction ? function (x) { return promiseResolve(C, onFinally()).then(function () { return x; }); } : onFinally, isFunction ? function (e) { return promiseResolve(C, onFinally()).then(function () { throw e; }); } : onFinally ); } }); /***/ }), /* 209 */ /***/ (function(module, exports, __nested_webpack_require_229726__) { "use strict"; // https://github.com/tc39/proposal-promise-try var $export = __nested_webpack_require_229726__(41); var newPromiseCapability = __nested_webpack_require_229726__(70); var perform = __nested_webpack_require_229726__(104); $export($export.S, 'Promise', { 'try': function (callbackfn) { var promiseCapability = newPromiseCapability.f(this); var result = perform(callbackfn); (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v); return promiseCapability.promise; } }); /***/ }), /* 210 */ /***/ (function(module, exports, __nested_webpack_require_230276__) { __nested_webpack_require_230276__(204); var global = __nested_webpack_require_230276__(11); var hide = __nested_webpack_require_230276__(31); var Iterators = __nested_webpack_require_230276__(35); var TO_STRING_TAG = __nested_webpack_require_230276__(13)('toStringTag'); var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' + 'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' + 'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' + 'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' + 'TextTrackList,TouchList').split(','); for (var i = 0; i < DOMIterables.length; i++) { var NAME = DOMIterables[i]; var Collection = global[NAME]; var proto = Collection && Collection.prototype; if (proto && !proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME); Iterators[NAME] = Iterators.Array; } /***/ }), /* 211 */ /***/ (function(module, exports, __nested_webpack_require_231331__) { /** * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = __nested_webpack_require_231331__(112); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage(); /** * Colors. */ exports.colors = [ '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { return true; } // Internet Explorer and Edge do not support colors. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } // is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || // double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ exports.formatters.j = function(v) { try { return JSON.stringify(v); } catch (err) { return '[UnexpectedJSONParseError]: ' + err.message; } }; /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!useColors) return; var c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit') // the final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into var index = 0; var lastC = 0; args[0].replace(/%[a-zA-Z%]/g, function(match) { if ('%%' === match) return; index++; if ('%c' === match) { // we only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.log()` when available. * No-op when `console.log` is not a "function". * * @api public */ function log() { // this hackery is required for IE8/9, where // the `console.log` function doesn't have 'apply' return 'object' === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (null == namespaces) { exports.storage.removeItem('debug'); } else { exports.storage.debug = namespaces; } } catch(e) {} } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { var r; try { r = exports.storage.debug; } catch(e) {} // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Enable namespaces listed in `localStorage.debug` initially. */ exports.enable(load()); /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { return window.localStorage; } catch (e) {} } /***/ }), /* 212 */ /***/ (function(module, exports, __nested_webpack_require_237123__) { /** * Detect Electron renderer process, which is node, but we should * treat as a browser. */ if (typeof process === 'undefined' || process.type === 'renderer') { module.exports = __nested_webpack_require_237123__(211); } else { module.exports = __nested_webpack_require_237123__(213); } /***/ }), /* 213 */ /***/ (function(module, exports, __nested_webpack_require_237470__) { /** * Module dependencies. */ var tty = __nested_webpack_require_237470__(79); var util = __nested_webpack_require_237470__(2); /** * This is the Node.js implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = __nested_webpack_require_237470__(112); exports.init = init; exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; /** * Colors. */ exports.colors = [ 6, 2, 3, 4, 5, 1 ]; try { var supportsColor = __nested_webpack_require_237470__(239); if (supportsColor && supportsColor.level >= 2) { exports.colors = [ 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221 ]; } } catch (err) { // swallow - we only care if `supports-color` is available; it doesn't have to be. } /** * Build up the default `inspectOpts` object from the environment variables. * * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ exports.inspectOpts = Object.keys(process.env).filter(function (key) { return /^debug_/i.test(key); }).reduce(function (obj, key) { // camel-case var prop = key .substring(6) .toLowerCase() .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); // coerce string value into JS value var val = process.env[key]; if (/^(yes|on|true|enabled)$/i.test(val)) val = true; else if (/^(no|off|false|disabled)$/i.test(val)) val = false; else if (val === 'null') val = null; else val = Number(val); obj[prop] = val; return obj; }, {}); /** * Is stdout a TTY? Colored output is enabled when `true`. */ function useColors() { return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); } /** * Map %o to `util.inspect()`, all on a single line. */ exports.formatters.o = function(v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts) .split('\n').map(function(str) { return str.trim() }).join(' '); }; /** * Map %o to `util.inspect()`, allowing multiple lines if needed. */ exports.formatters.O = function(v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts); }; /** * Adds ANSI color escape codes if enabled. * * @api public */ function formatArgs(args) { var name = this.namespace; var useColors = this.useColors; if (useColors) { var c = this.color; var colorCode = '\u001b[3' + (c < 8 ? c : '8;5;' + c); var prefix = ' ' + colorCode + ';1m' + name + ' ' + '\u001b[0m'; args[0] = prefix + args[0].split('\n').join('\n' + prefix); args.push(colorCode + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); } else { args[0] = getDate() + name + ' ' + args[0]; } } function getDate() { if (exports.inspectOpts.hideDate) { return ''; } else { return new Date().toISOString() + ' '; } } /** * Invokes `util.format()` with the specified arguments and writes to stderr. */ function log() { return process.stderr.write(util.format.apply(util, arguments) + '\n'); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { if (null == namespaces) { // If you set a process.env field to null or undefined, it gets cast to the // string 'null' or 'undefined'. Just delete instead. delete process.env.DEBUG; } else { process.env.DEBUG = namespaces; } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { return process.env.DEBUG; } /** * Init logic for `debug` instances. * * Create a new `inspectOpts` object in case `useColors` is set * differently for a particular `debug` instance. */ function init (debug) { debug.inspectOpts = {}; var keys = Object.keys(exports.inspectOpts); for (var i = 0; i < keys.length; i++) { debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; } } /** * Enable namespaces listed in `process.env.DEBUG` initially. */ exports.enable(load()); /***/ }), /* 214 */, /* 215 */, /* 216 */, /* 217 */ /***/ (function(module, exports, __nested_webpack_require_241942__) { // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var pathModule = __nested_webpack_require_241942__(0); var isWindows = process.platform === 'win32'; var fs = __nested_webpack_require_241942__(3); // JavaScript implementation of realpath, ported from node pre-v6 var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); function rethrow() { // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and // is fairly slow to generate. var callback; if (DEBUG) { var backtrace = new Error; callback = debugCallback; } else callback = missingCallback; return callback; function debugCallback(err) { if (err) { backtrace.message = err.message; err = backtrace; missingCallback(err); } } function missingCallback(err) { if (err) { if (process.throwDeprecation) throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs else if (!process.noDeprecation) { var msg = 'fs: missing callback ' + (err.stack || err.message); if (process.traceDeprecation) console.trace(msg); else console.error(msg); } } } } function maybeCallback(cb) { return typeof cb === 'function' ? cb : rethrow(); } var normalize = pathModule.normalize; // Regexp that finds the next partion of a (partial) path // result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] if (isWindows) { var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; } else { var nextPartRe = /(.*?)(?:[\/]+|$)/g; } // Regex to find the device root, including trailing slash. E.g. 'c:\\'. if (isWindows) { var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; } else { var splitRootRe = /^[\/]*/; } exports.realpathSync = function realpathSync(p, cache) { // make p is absolute p = pathModule.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return cache[p]; } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows && !knownHard[base]) { fs.lstatSync(base); knownHard[base] = true; } } // walk down the path, swapping out linked pathparts for their real // values // NB: p.length changes. while (pos < p.length) { // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { continue; } var resolvedLink; if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // some known symbolic link. no need to stat again. resolvedLink = cache[base]; } else { var stat = fs.lstatSync(base); if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; continue; } // read the link if it wasn't read before // dev/ino always return 0 on windows, so skip the check. var linkTarget = null; if (!isWindows) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { linkTarget = seenLinks[id]; } } if (linkTarget === null) { fs.statSync(base); linkTarget = fs.readlinkSync(base); } resolvedLink = pathModule.resolve(previous, linkTarget); // track this, if given a cache. if (cache) cache[base] = resolvedLink; if (!isWindows) seenLinks[id] = linkTarget; } // resolve the link, then start over p = pathModule.resolve(resolvedLink, p.slice(pos)); start(); } if (cache) cache[original] = p; return p; }; exports.realpath = function realpath(p, cache, cb) { if (typeof cb !== 'function') { cb = maybeCallback(cache); cache = null; } // make p is absolute p = pathModule.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return process.nextTick(cb.bind(null, null, cache[p])); } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows && !knownHard[base]) { fs.lstat(base, function(err) { if (err) return cb(err); knownHard[base] = true; LOOP(); }); } else { process.nextTick(LOOP); } } // walk down the path, swapping out linked pathparts for their real // values function LOOP() { // stop if scanned past end of path if (pos >= p.length) { if (cache) cache[original] = p; return cb(null, p); } // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { return process.nextTick(LOOP); } if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // known symbolic link. no need to stat again. return gotResolvedLink(cache[base]); } return fs.lstat(base, gotStat); } function gotStat(err, stat) { if (err) return cb(err); // if not a symlink, skip to the next path part if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; return process.nextTick(LOOP); } // stat & read the link if not read before // call gotTarget as soon as the link target is known // dev/ino always return 0 on windows, so skip the check. if (!isWindows) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { return gotTarget(null, seenLinks[id], base); } } fs.stat(base, function(err) { if (err) return cb(err); fs.readlink(base, function(err, target) { if (!isWindows) seenLinks[id] = target; gotTarget(err, target); }); }); } function gotTarget(err, target, base) { if (err) return cb(err); var resolvedLink = pathModule.resolve(previous, target); if (cache) cache[base] = resolvedLink; gotResolvedLink(resolvedLink); } function gotResolvedLink(resolvedLink) { // resolve the link, then start over p = pathModule.resolve(resolvedLink, p.slice(pos)); start(); } }; /***/ }), /* 218 */ /***/ (function(module, exports, __nested_webpack_require_250579__) { module.exports = globSync globSync.GlobSync = GlobSync var fs = __nested_webpack_require_250579__(3) var rp = __nested_webpack_require_250579__(114) var minimatch = __nested_webpack_require_250579__(60) var Minimatch = minimatch.Minimatch var Glob = __nested_webpack_require_250579__(75).Glob var util = __nested_webpack_require_250579__(2) var path = __nested_webpack_require_250579__(0) var assert = __nested_webpack_require_250579__(22) var isAbsolute = __nested_webpack_require_250579__(76) var common = __nested_webpack_require_250579__(115) var alphasort = common.alphasort var alphasorti = common.alphasorti var setopts = common.setopts var ownProp = common.ownProp var childrenIgnored = common.childrenIgnored var isIgnored = common.isIgnored function globSync (pattern, options) { if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') return new GlobSync(pattern, options).found } function GlobSync (pattern, options) { if (!pattern) throw new Error('must provide pattern') if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') if (!(this instanceof GlobSync)) return new GlobSync(pattern, options) setopts(this, pattern, options) if (this.noprocess) return this var n = this.minimatch.set.length this.matches = new Array(n) for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false) } this._finish() } GlobSync.prototype._finish = function () { assert(this instanceof GlobSync) if (this.realpath) { var self = this this.matches.forEach(function (matchset, index) { var set = self.matches[index] = Object.create(null) for (var p in matchset) { try { p = self._makeAbs(p) var real = rp.realpathSync(p, self.realpathCache) set[real] = true } catch (er) { if (er.syscall === 'stat') set[self._makeAbs(p)] = true else throw er } } }) } common.finish(this) } GlobSync.prototype._process = function (pattern, index, inGlobStar) { assert(this instanceof GlobSync) // Get the first [n] parts of pattern that are all strings. var n = 0 while (typeof pattern[n] === 'string') { n ++ } // now n is the index of the first one that is *not* a string. // See if there's anything else var prefix switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index) return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/') break } var remain = pattern.slice(n) // get the list of entries. var read if (prefix === null) read = '.' else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix } else read = prefix var abs = this._makeAbs(read) //if ignored, skip processing if (childrenIgnored(this, read)) return var isGlobStar = remain[0] === minimatch.GLOBSTAR if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) else this._processReaddir(prefix, read, abs, remain, index, inGlobStar) } GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar) // if the abs isn't a dir, then nothing can match! if (!entries) return // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0] var negate = !!this.minimatch.negate var rawGlob = pn._glob var dotOk = this.dot || rawGlob.charAt(0) === '.' var matchedEntries = [] for (var i = 0; i < entries.length; i++) { var e = entries[i] if (e.charAt(0) !== '.' || dotOk) { var m if (negate && !prefix) { m = !e.match(pn) } else { m = e.match(pn) } if (m) matchedEntries.push(e) } } var len = matchedEntries.length // If there are no matched entries, then nothing matches. if (len === 0) return // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null) for (var i = 0; i < len; i ++) { var e = matchedEntries[i] if (prefix) { if (prefix.slice(-1) !== '/') e = prefix + '/' + e else e = prefix + e } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e) } this._emitMatch(index, e) } // This was the last one, and no stats were needed return } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift() for (var i = 0; i < len; i ++) { var e = matchedEntries[i] var newPattern if (prefix) newPattern = [prefix, e] else newPattern = [e] this._process(newPattern.concat(remain), index, inGlobStar) } } GlobSync.prototype._emitMatch = function (index, e) { if (isIgnored(this, e)) return var abs = this._makeAbs(e) if (this.mark) e = this._mark(e) if (this.absolute) { e = abs } if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs] if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true if (this.stat) this._stat(e) } GlobSync.prototype._readdirInGlobStar = function (abs) { // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false) var entries var lstat var stat try { lstat = fs.lstatSync(abs) } catch (er) { if (er.code === 'ENOENT') { // lstat failed, doesn't exist return null } } var isSym = lstat && lstat.isSymbolicLink() this.symlinks[abs] = isSym // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) this.cache[abs] = 'FILE' else entries = this._readdir(abs, false) return entries } GlobSync.prototype._readdir = function (abs, inGlobStar) { var entries if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs) if (ownProp(this.cache, abs)) { var c = this.cache[abs] if (!c || c === 'FILE') return null if (Array.isArray(c)) return c } try { return this._readdirEntries(abs, fs.readdirSync(abs)) } catch (er) { this._readdirError(abs, er) return null } } GlobSync.prototype._readdirEntries = function (abs, entries) { // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i] if (abs === '/') e = abs + e else e = abs + '/' + e this.cache[e] = true } } this.cache[abs] = entries // mark and cache dir-ness return entries } GlobSync.prototype._readdirError = function (f, er) { // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f) this.cache[abs] = 'FILE' if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd) error.path = this.cwd error.code = er.code throw error } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false if (this.strict) throw er if (!this.silent) console.error('glob error', er) break } } GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar) // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1) var gspref = prefix ? [ prefix ] : [] var noGlobStar = gspref.concat(remainWithoutGlobStar) // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false) var len = entries.length var isSym = this.symlinks[abs] // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return for (var i = 0; i < len; i++) { var e = entries[i] if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar) this._process(instead, index, true) var below = gspref.concat(entries[i], remain) this._process(below, index, true) } } GlobSync.prototype._processSimple = function (prefix, index) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var exists = this._stat(prefix) if (!this.matches[index]) this.matches[index] = Object.create(null) // If it doesn't exist, then just mark the lack of results if (!exists) return if (prefix && isAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix) if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix) } else { prefix = path.resolve(this.root, prefix) if (trail) prefix += '/' } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/') // Mark this as a match this._emitMatch(index, prefix) } // Returns either 'DIR', 'FILE', or false GlobSync.prototype._stat = function (f) { var abs = this._makeAbs(f) var needDir = f.slice(-1) === '/' if (f.length > this.maxLength) return false if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs] if (Array.isArray(c)) c = 'DIR' // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return c if (needDir && c === 'FILE') return false // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var exists var stat = this.statCache[abs] if (!stat) { var lstat try { lstat = fs.lstatSync(abs) } catch (er) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false return false } } if (lstat && lstat.isSymbolicLink()) { try { stat = fs.statSync(abs) } catch (er) { stat = lstat } } else { stat = lstat } } this.statCache[abs] = stat var c = true if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE' this.cache[abs] = this.cache[abs] || c if (needDir && c === 'FILE') return false return c } GlobSync.prototype._mark = function (p) { return common.mark(this, p) } GlobSync.prototype._makeAbs = function (f) { return common.makeAbs(this, f) } /***/ }), /* 219 */, /* 220 */, /* 221 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function (flag, argv) { argv = argv || process.argv; var terminatorPos = argv.indexOf('--'); var prefix = /^--/.test(flag) ? '' : '--'; var pos = argv.indexOf(prefix + flag); return pos !== -1 && (terminatorPos !== -1 ? pos < terminatorPos : true); }; /***/ }), /* 222 */, /* 223 */ /***/ (function(module, exports, __nested_webpack_require_263098__) { var wrappy = __nested_webpack_require_263098__(123) var reqs = Object.create(null) var once = __nested_webpack_require_263098__(61) module.exports = wrappy(inflight) function inflight (key, cb) { if (reqs[key]) { reqs[key].push(cb) return null } else { reqs[key] = [cb] return makeres(key) } } function makeres (key) { return once(function RES () { var cbs = reqs[key] var len = cbs.length var args = slice(arguments) // XXX It's somewhat ambiguous whether a new callback added in this // pass should be queued for later execution if something in the // list of callbacks throws, or if it should just be discarded. // However, it's such an edge case that it hardly matters, and either // choice is likely as surprising as the other. // As it happens, we do go ahead and schedule it for later execution. try { for (var i = 0; i < len; i++) { cbs[i].apply(null, args) } } finally { if (cbs.length > len) { // added more in the interim. // de-zalgo, just in case, but don't call again. cbs.splice(0, len) process.nextTick(function () { RES.apply(null, args) }) } else { delete reqs[key] } } }) } function slice (args) { var length = args.length var array = [] for (var i = 0; i < length; i++) array[i] = args[i] return array } /***/ }), /* 224 */ /***/ (function(module, exports) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } /***/ }), /* 225 */, /* 226 */, /* 227 */ /***/ (function(module, exports, __nested_webpack_require_265309__) { // @flow /*:: declare var __webpack_require__: mixed; */ module.exports = typeof __nested_webpack_require_265309__ !== "undefined"; /***/ }), /* 228 */, /* 229 */ /***/ (function(module, exports) { /** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function(val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse(val); } else if (type === 'number' && isNaN(val) === false) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str); if (str.length > 100) { return; } var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { if (ms >= d) { return Math.round(ms / d) + 'd'; } if (ms >= h) { return Math.round(ms / h) + 'h'; } if (ms >= m) { return Math.round(ms / m) + 'm'; } if (ms >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, n, name) { if (ms < n) { return; } if (ms < n * 1.5) { return Math.floor(ms / n) + ' ' + name; } return Math.ceil(ms / n) + ' ' + name + 's'; } /***/ }), /* 230 */, /* 231 */, /* 232 */, /* 233 */ /***/ (function(module, exports, __nested_webpack_require_268374__) { module.exports = rimraf rimraf.sync = rimrafSync var assert = __nested_webpack_require_268374__(22) var path = __nested_webpack_require_268374__(0) var fs = __nested_webpack_require_268374__(3) var glob = __nested_webpack_require_268374__(75) var _0666 = parseInt('666', 8) var defaultGlobOpts = { nosort: true, silent: true } // for EMFILE handling var timeout = 0 var isWindows = (process.platform === "win32") function defaults (options) { var methods = [ 'unlink', 'chmod', 'stat', 'lstat', 'rmdir', 'readdir' ] methods.forEach(function(m) { options[m] = options[m] || fs[m] m = m + 'Sync' options[m] = options[m] || fs[m] }) options.maxBusyTries = options.maxBusyTries || 3 options.emfileWait = options.emfileWait || 1000 if (options.glob === false) { options.disableGlob = true } options.disableGlob = options.disableGlob || false options.glob = options.glob || defaultGlobOpts } function rimraf (p, options, cb) { if (typeof options === 'function') { cb = options options = {} } assert(p, 'rimraf: missing path') assert.equal(typeof p, 'string', 'rimraf: path should be a string') assert.equal(typeof cb, 'function', 'rimraf: callback function required') assert(options, 'rimraf: invalid options argument provided') assert.equal(typeof options, 'object', 'rimraf: options should be object') defaults(options) var busyTries = 0 var errState = null var n = 0 if (options.disableGlob || !glob.hasMagic(p)) return afterGlob(null, [p]) options.lstat(p, function (er, stat) { if (!er) return afterGlob(null, [p]) glob(p, options.glob, afterGlob) }) function next (er) { errState = errState || er if (--n === 0) cb(errState) } function afterGlob (er, results) { if (er) return cb(er) n = results.length if (n === 0) return cb() results.forEach(function (p) { rimraf_(p, options, function CB (er) { if (er) { if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && busyTries < options.maxBusyTries) { busyTries ++ var time = busyTries * 100 // try again, with the same exact callback as this one. return setTimeout(function () { rimraf_(p, options, CB) }, time) } // this one won't happen if graceful-fs is used. if (er.code === "EMFILE" && timeout < options.emfileWait) { return setTimeout(function () { rimraf_(p, options, CB) }, timeout ++) } // already gone if (er.code === "ENOENT") er = null } timeout = 0 next(er) }) }) } } // Two possible strategies. // 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR // 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR // // Both result in an extra syscall when you guess wrong. However, there // are likely far more normal files in the world than directories. This // is based on the assumption that a the average number of files per // directory is >= 1. // // If anyone ever complains about this, then I guess the strategy could // be made configurable somehow. But until then, YAGNI. function rimraf_ (p, options, cb) { assert(p) assert(options) assert(typeof cb === 'function') // sunos lets the root user unlink directories, which is... weird. // so we have to lstat here and make sure it's not a dir. options.lstat(p, function (er, st) { if (er && er.code === "ENOENT") return cb(null) // Windows can EPERM on stat. Life is suffering. if (er && er.code === "EPERM" && isWindows) fixWinEPERM(p, options, er, cb) if (st && st.isDirectory()) return rmdir(p, options, er, cb) options.unlink(p, function (er) { if (er) { if (er.code === "ENOENT") return cb(null) if (er.code === "EPERM") return (isWindows) ? fixWinEPERM(p, options, er, cb) : rmdir(p, options, er, cb) if (er.code === "EISDIR") return rmdir(p, options, er, cb) } return cb(er) }) }) } function fixWinEPERM (p, options, er, cb) { assert(p) assert(options) assert(typeof cb === 'function') if (er) assert(er instanceof Error) options.chmod(p, _0666, function (er2) { if (er2) cb(er2.code === "ENOENT" ? null : er) else options.stat(p, function(er3, stats) { if (er3) cb(er3.code === "ENOENT" ? null : er) else if (stats.isDirectory()) rmdir(p, options, er, cb) else options.unlink(p, cb) }) }) } function fixWinEPERMSync (p, options, er) { assert(p) assert(options) if (er) assert(er instanceof Error) try { options.chmodSync(p, _0666) } catch (er2) { if (er2.code === "ENOENT") return else throw er } try { var stats = options.statSync(p) } catch (er3) { if (er3.code === "ENOENT") return else throw er } if (stats.isDirectory()) rmdirSync(p, options, er) else options.unlinkSync(p) } function rmdir (p, options, originalEr, cb) { assert(p) assert(options) if (originalEr) assert(originalEr instanceof Error) assert(typeof cb === 'function') // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) // if we guessed wrong, and it's not a directory, then // raise the original error. options.rmdir(p, function (er) { if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) rmkids(p, options, cb) else if (er && er.code === "ENOTDIR") cb(originalEr) else cb(er) }) } function rmkids(p, options, cb) { assert(p) assert(options) assert(typeof cb === 'function') options.readdir(p, function (er, files) { if (er) return cb(er) var n = files.length if (n === 0) return options.rmdir(p, cb) var errState files.forEach(function (f) { rimraf(path.join(p, f), options, function (er) { if (errState) return if (er) return cb(errState = er) if (--n === 0) options.rmdir(p, cb) }) }) }) } // this looks simpler, and is strictly *faster*, but will // tie up the JavaScript thread and fail on excessively // deep directory trees. function rimrafSync (p, options) { options = options || {} defaults(options) assert(p, 'rimraf: missing path') assert.equal(typeof p, 'string', 'rimraf: path should be a string') assert(options, 'rimraf: missing options') assert.equal(typeof options, 'object', 'rimraf: options should be object') var results if (options.disableGlob || !glob.hasMagic(p)) { results = [p] } else { try { options.lstatSync(p) results = [p] } catch (er) { results = glob.sync(p, options.glob) } } if (!results.length) return for (var i = 0; i < results.length; i++) { var p = results[i] try { var st = options.lstatSync(p) } catch (er) { if (er.code === "ENOENT") return // Windows can EPERM on stat. Life is suffering. if (er.code === "EPERM" && isWindows) fixWinEPERMSync(p, options, er) } try { // sunos lets the root user unlink directories, which is... weird. if (st && st.isDirectory()) rmdirSync(p, options, null) else options.unlinkSync(p) } catch (er) { if (er.code === "ENOENT") return if (er.code === "EPERM") return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) if (er.code !== "EISDIR") throw er rmdirSync(p, options, er) } } } function rmdirSync (p, options, originalEr) { assert(p) assert(options) if (originalEr) assert(originalEr instanceof Error) try { options.rmdirSync(p) } catch (er) { if (er.code === "ENOENT") return if (er.code === "ENOTDIR") throw originalEr if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") rmkidsSync(p, options) } } function rmkidsSync (p, options) { assert(p) assert(options) options.readdirSync(p).forEach(function (f) { rimrafSync(path.join(p, f), options) }) // We only end up here once we got ENOTEMPTY at least once, and // at this point, we are guaranteed to have removed all the kids. // So, we know that it won't be ENOENT or ENOTDIR or anything else. // try really hard to delete stuff on windows, because it has a // PROFOUNDLY annoying habit of not closing handles promptly when // files are deleted, resulting in spurious ENOTEMPTY errors. var retries = isWindows ? 100 : 1 var i = 0 do { var threw = true try { var ret = options.rmdirSync(p, options) threw = false return ret } finally { if (++i < retries && threw) continue } } while (true) } /***/ }), /* 234 */, /* 235 */, /* 236 */, /* 237 */, /* 238 */, /* 239 */ /***/ (function(module, exports, __nested_webpack_require_277532__) { "use strict"; var hasFlag = __nested_webpack_require_277532__(221); var support = function (level) { if (level === 0) { return false; } return { level: level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; }; var supportLevel = (function () { if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { return 0; } if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { return 3; } if (hasFlag('color=256')) { return 2; } if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { return 1; } if (process.stdout && !process.stdout.isTTY) { return 0; } if (process.platform === 'win32') { return 1; } if ('CI' in process.env) { if ('TRAVIS' in process.env || process.env.CI === 'Travis') { return 1; } return 0; } if ('TEAMCITY_VERSION' in process.env) { return process.env.TEAMCITY_VERSION.match(/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/) === null ? 0 : 1; } if (/^(screen|xterm)-256(?:color)?/.test(process.env.TERM)) { return 2; } if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) { return 1; } if ('COLORTERM' in process.env) { return 1; } if (process.env.TERM === 'dumb') { return 0; } return 0; })(); if (supportLevel === 0 && 'FORCE_COLOR' in process.env) { supportLevel = 1; } module.exports = process && support(supportLevel); /***/ }) /******/ ]); /***/ }), /***/ 92460: /***/ ((module) => { "use strict"; /* * Generated by PEG.js 0.10.0. * * http://pegjs.org/ */ function peg$subclass(child, parent) { function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); } function peg$SyntaxError(message, expected, found, location) { this.message = message; this.expected = expected; this.found = found; this.location = location; this.name = "SyntaxError"; if (typeof Error.captureStackTrace === "function") { Error.captureStackTrace(this, peg$SyntaxError); } } peg$subclass(peg$SyntaxError, Error); peg$SyntaxError.buildMessage = function(expected, found) { var DESCRIBE_EXPECTATION_FNS = { literal: function(expectation) { return "\"" + literalEscape(expectation.text) + "\""; }, "class": function(expectation) { var escapedParts = "", i; for (i = 0; i < expectation.parts.length; i++) { escapedParts += expectation.parts[i] instanceof Array ? classEscape(expectation.parts[i][0]) + "-" + classEscape(expectation.parts[i][1]) : classEscape(expectation.parts[i]); } return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; }, any: function(expectation) { return "any character"; }, end: function(expectation) { return "end of input"; }, other: function(expectation) { return expectation.description; } }; function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); } function literalEscape(s) { return s .replace(/\\/g, '\\\\') .replace(/"/g, '\\"') .replace(/\0/g, '\\0') .replace(/\t/g, '\\t') .replace(/\n/g, '\\n') .replace(/\r/g, '\\r') .replace(/[\x00-\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x' + hex(ch); }); } function classEscape(s) { return s .replace(/\\/g, '\\\\') .replace(/\]/g, '\\]') .replace(/\^/g, '\\^') .replace(/-/g, '\\-') .replace(/\0/g, '\\0') .replace(/\t/g, '\\t') .replace(/\n/g, '\\n') .replace(/\r/g, '\\r') .replace(/[\x00-\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x' + hex(ch); }); } function describeExpectation(expectation) { return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation); } function describeExpected(expected) { var descriptions = new Array(expected.length), i, j; for (i = 0; i < expected.length; i++) { descriptions[i] = describeExpectation(expected[i]); } descriptions.sort(); if (descriptions.length > 0) { for (i = 1, j = 1; i < descriptions.length; i++) { if (descriptions[i - 1] !== descriptions[i]) { descriptions[j] = descriptions[i]; j++; } } descriptions.length = j; } switch (descriptions.length) { case 1: return descriptions[0]; case 2: return descriptions[0] + " or " + descriptions[1]; default: return descriptions.slice(0, -1).join(", ") + ", or " + descriptions[descriptions.length - 1]; } } function describeFound(found) { return found ? "\"" + literalEscape(found) + "\"" : "end of input"; } return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; }; function peg$parse(input, options) { options = options !== void 0 ? options : {}; var peg$FAILED = {}, peg$startRuleFunctions = { resolution: peg$parseresolution }, peg$startRuleFunction = peg$parseresolution, peg$c0 = "/", peg$c1 = peg$literalExpectation("/", false), peg$c2 = function(from, descriptor) { return { from, descriptor } }, peg$c3 = function(descriptor) { return { descriptor } }, peg$c4 = "@", peg$c5 = peg$literalExpectation("@", false), peg$c6 = function(fullName, description) { return { fullName, description } }, peg$c7 = function(fullName) { return { fullName } }, peg$c8 = function() { return text() }, peg$c9 = /^[^\/@]/, peg$c10 = peg$classExpectation(["/", "@"], true, false), peg$c11 = /^[^\/]/, peg$c12 = peg$classExpectation(["/"], true, false), peg$currPos = 0, peg$savedPos = 0, peg$posDetailsCache = [{ line: 1, column: 1 }], peg$maxFailPos = 0, peg$maxFailExpected = [], peg$silentFails = 0, peg$result; if ("startRule" in options) { if (!(options.startRule in peg$startRuleFunctions)) { throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); } peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; } function text() { return input.substring(peg$savedPos, peg$currPos); } function location() { return peg$computeLocation(peg$savedPos, peg$currPos); } function expected(description, location) { location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos) throw peg$buildStructuredError( [peg$otherExpectation(description)], input.substring(peg$savedPos, peg$currPos), location ); } function error(message, location) { location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos) throw peg$buildSimpleError(message, location); } function peg$literalExpectation(text, ignoreCase) { return { type: "literal", text: text, ignoreCase: ignoreCase }; } function peg$classExpectation(parts, inverted, ignoreCase) { return { type: "class", parts: parts, inverted: inverted, ignoreCase: ignoreCase }; } function peg$anyExpectation() { return { type: "any" }; } function peg$endExpectation() { return { type: "end" }; } function peg$otherExpectation(description) { return { type: "other", description: description }; } function peg$computePosDetails(pos) { var details = peg$posDetailsCache[pos], p; if (details) { return details; } else { p = pos - 1; while (!peg$posDetailsCache[p]) { p--; } details = peg$posDetailsCache[p]; details = { line: details.line, column: details.column }; while (p < pos) { if (input.charCodeAt(p) === 10) { details.line++; details.column = 1; } else { details.column++; } p++; } peg$posDetailsCache[pos] = details; return details; } } function peg$computeLocation(startPos, endPos) { var startPosDetails = peg$computePosDetails(startPos), endPosDetails = peg$computePosDetails(endPos); return { start: { offset: startPos, line: startPosDetails.line, column: startPosDetails.column }, end: { offset: endPos, line: endPosDetails.line, column: endPosDetails.column } }; } function peg$fail(expected) { if (peg$currPos < peg$maxFailPos) { return; } if (peg$currPos > peg$maxFailPos) { peg$maxFailPos = peg$currPos; peg$maxFailExpected = []; } peg$maxFailExpected.push(expected); } function peg$buildSimpleError(message, location) { return new peg$SyntaxError(message, null, null, location); } function peg$buildStructuredError(expected, found, location) { return new peg$SyntaxError( peg$SyntaxError.buildMessage(expected, found), expected, found, location ); } function peg$parseresolution() { var s0, s1, s2, s3; s0 = peg$currPos; s1 = peg$parsespecifier(); if (s1 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 47) { s2 = peg$c0; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c1); } } if (s2 !== peg$FAILED) { s3 = peg$parsespecifier(); if (s3 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c2(s1, s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parsespecifier(); if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c3(s1); } s0 = s1; } return s0; } function peg$parsespecifier() { var s0, s1, s2, s3; s0 = peg$currPos; s1 = peg$parsefullName(); if (s1 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 64) { s2 = peg$c4; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c5); } } if (s2 !== peg$FAILED) { s3 = peg$parsedescription(); if (s3 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c6(s1, s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parsefullName(); if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c7(s1); } s0 = s1; } return s0; } function peg$parsefullName() { var s0, s1, s2, s3, s4; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 64) { s1 = peg$c4; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c5); } } if (s1 !== peg$FAILED) { s2 = peg$parseident(); if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 47) { s3 = peg$c0; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c1); } } if (s3 !== peg$FAILED) { s4 = peg$parseident(); if (s4 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c8(); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parseident(); if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c8(); } s0 = s1; } return s0; } function peg$parseident() { var s0, s1, s2; s0 = peg$currPos; s1 = []; if (peg$c9.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c10); } } if (s2 !== peg$FAILED) { while (s2 !== peg$FAILED) { s1.push(s2); if (peg$c9.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c10); } } } } else { s1 = peg$FAILED; } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c8(); } s0 = s1; return s0; } function peg$parsedescription() { var s0, s1, s2; s0 = peg$currPos; s1 = []; if (peg$c11.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c12); } } if (s2 !== peg$FAILED) { while (s2 !== peg$FAILED) { s1.push(s2); if (peg$c11.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c12); } } } } else { s1 = peg$FAILED; } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c8(); } s0 = s1; return s0; } peg$result = peg$startRuleFunction(); if (peg$result !== peg$FAILED && peg$currPos === input.length) { return peg$result; } else { if (peg$result !== peg$FAILED && peg$currPos < input.length) { peg$fail(peg$endExpectation()); } throw peg$buildStructuredError( peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) : peg$computeLocation(peg$maxFailPos, peg$maxFailPos) ); } } module.exports = { SyntaxError: peg$SyntaxError, parse: peg$parse }; /***/ }), /***/ 64399: /***/ ((module) => { "use strict"; /* * Generated by PEG.js 0.10.0. * * http://pegjs.org/ */ function peg$subclass(child, parent) { function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); } function peg$SyntaxError(message, expected, found, location) { this.message = message; this.expected = expected; this.found = found; this.location = location; this.name = "SyntaxError"; if (typeof Error.captureStackTrace === "function") { Error.captureStackTrace(this, peg$SyntaxError); } } peg$subclass(peg$SyntaxError, Error); peg$SyntaxError.buildMessage = function(expected, found) { var DESCRIBE_EXPECTATION_FNS = { literal: function(expectation) { return "\"" + literalEscape(expectation.text) + "\""; }, "class": function(expectation) { var escapedParts = "", i; for (i = 0; i < expectation.parts.length; i++) { escapedParts += expectation.parts[i] instanceof Array ? classEscape(expectation.parts[i][0]) + "-" + classEscape(expectation.parts[i][1]) : classEscape(expectation.parts[i]); } return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; }, any: function(expectation) { return "any character"; }, end: function(expectation) { return "end of input"; }, other: function(expectation) { return expectation.description; } }; function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); } function literalEscape(s) { return s .replace(/\\/g, '\\\\') .replace(/"/g, '\\"') .replace(/\0/g, '\\0') .replace(/\t/g, '\\t') .replace(/\n/g, '\\n') .replace(/\r/g, '\\r') .replace(/[\x00-\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x' + hex(ch); }); } function classEscape(s) { return s .replace(/\\/g, '\\\\') .replace(/\]/g, '\\]') .replace(/\^/g, '\\^') .replace(/-/g, '\\-') .replace(/\0/g, '\\0') .replace(/\t/g, '\\t') .replace(/\n/g, '\\n') .replace(/\r/g, '\\r') .replace(/[\x00-\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x' + hex(ch); }); } function describeExpectation(expectation) { return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation); } function describeExpected(expected) { var descriptions = new Array(expected.length), i, j; for (i = 0; i < expected.length; i++) { descriptions[i] = describeExpectation(expected[i]); } descriptions.sort(); if (descriptions.length > 0) { for (i = 1, j = 1; i < descriptions.length; i++) { if (descriptions[i - 1] !== descriptions[i]) { descriptions[j] = descriptions[i]; j++; } } descriptions.length = j; } switch (descriptions.length) { case 1: return descriptions[0]; case 2: return descriptions[0] + " or " + descriptions[1]; default: return descriptions.slice(0, -1).join(", ") + ", or " + descriptions[descriptions.length - 1]; } } function describeFound(found) { return found ? "\"" + literalEscape(found) + "\"" : "end of input"; } return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; }; function peg$parse(input, options) { options = options !== void 0 ? options : {}; var peg$FAILED = {}, peg$startRuleFunctions = { Start: peg$parseStart }, peg$startRuleFunction = peg$parseStart, peg$c0 = function(line) { return line ? line : [] }, peg$c1 = function(command, type, then) { return [ { command, type } ].concat(then || []) }, peg$c2 = function(command, type) { return [ { command, type: type || ';' } ] }, peg$c3 = function(then) { return then }, peg$c4 = ";", peg$c5 = peg$literalExpectation(";", false), peg$c6 = "&", peg$c7 = peg$literalExpectation("&", false), peg$c8 = function(chain, then) { return then ? { chain, then } : { chain } }, peg$c9 = function(type, then) { return { type, line: then } }, peg$c10 = "&&", peg$c11 = peg$literalExpectation("&&", false), peg$c12 = "||", peg$c13 = peg$literalExpectation("||", false), peg$c14 = function(main, then) { return then ? { ...main, then } : main }, peg$c15 = function(type, then) { return { type, chain: then } }, peg$c16 = "|&", peg$c17 = peg$literalExpectation("|&", false), peg$c18 = "|", peg$c19 = peg$literalExpectation("|", false), peg$c20 = "=", peg$c21 = peg$literalExpectation("=", false), peg$c22 = function(name, arg) { return { name, args: [arg] } }, peg$c23 = function(name) { return { name, args: [] } }, peg$c24 = "(", peg$c25 = peg$literalExpectation("(", false), peg$c26 = ")", peg$c27 = peg$literalExpectation(")", false), peg$c28 = function(subshell, args) { return { type: `subshell`, subshell, args } }, peg$c29 = "{", peg$c30 = peg$literalExpectation("{", false), peg$c31 = "}", peg$c32 = peg$literalExpectation("}", false), peg$c33 = function(group, args) { return { type: `group`, group, args } }, peg$c34 = function(envs, args) { return { type: `command`, args, envs } }, peg$c35 = function(envs) { return { type: `envs`, envs } }, peg$c36 = function(args) { return args }, peg$c37 = function(arg) { return arg }, peg$c38 = /^[0-9]/, peg$c39 = peg$classExpectation([["0", "9"]], false, false), peg$c40 = function(fd, redirect, arg) { return { type: `redirection`, subtype: redirect, fd: fd !== null ? parseInt(fd) : null, args: [arg] } }, peg$c41 = ">>", peg$c42 = peg$literalExpectation(">>", false), peg$c43 = ">&", peg$c44 = peg$literalExpectation(">&", false), peg$c45 = ">", peg$c46 = peg$literalExpectation(">", false), peg$c47 = "<<<", peg$c48 = peg$literalExpectation("<<<", false), peg$c49 = "<&", peg$c50 = peg$literalExpectation("<&", false), peg$c51 = "<", peg$c52 = peg$literalExpectation("<", false), peg$c53 = function(segments) { return { type: `argument`, segments: [].concat(... segments) } }, peg$c54 = function(string) { return string }, peg$c55 = "'", peg$c56 = peg$literalExpectation("'", false), peg$c57 = function(text) { return [ { type: `text`, text } ] }, peg$c58 = "\"", peg$c59 = peg$literalExpectation("\"", false), peg$c60 = function(segments) { return segments }, peg$c61 = function(arithmetic) { return { type: `arithmetic`, arithmetic, quoted: true} }, peg$c62 = function(shell) { return { type: `shell`, shell, quoted: true } }, peg$c63 = function(variable) { return { type: `variable`, ...variable, quoted: true } }, peg$c64 = function(text) { return { type: `text`, text } }, peg$c65 = function(arithmetic) { return { type: `arithmetic`, arithmetic, quoted: false} }, peg$c66 = function(shell) { return { type: `shell`, shell, quoted: false } }, peg$c67 = function(variable) { return { type: `variable`, ...variable, quoted: false } }, peg$c68 = function(pattern) { return { type: `glob`, pattern } }, peg$c69 = "\\", peg$c70 = peg$literalExpectation("\\", false), peg$c71 = peg$anyExpectation(), peg$c72 = function(c) { return c }, peg$c73 = /^[^']/, peg$c74 = peg$classExpectation(["'"], true, false), peg$c75 = function(chars) { return chars.join(``) }, peg$c76 = /^[^$"]/, peg$c77 = peg$classExpectation(["$", "\""], true, false), peg$c78 = "-", peg$c79 = peg$literalExpectation("-", false), peg$c80 = "+", peg$c81 = peg$literalExpectation("+", false), peg$c82 = ".", peg$c83 = peg$literalExpectation(".", false), peg$c84 = function(sign, left, right) { return { type: `number`, value: (sign === '-' ? -1 : 1) * parseFloat(left.join(``) + `.` + right.join(``)) } }, peg$c85 = function(sign, value) { return { type: `number`, value: (sign === '-' ? -1 : 1) * parseInt(value.join(``)) } }, peg$c86 = function(variable) { return { type: `variable`, ...variable } }, peg$c87 = function(name) { return { type: `variable`, name } }, peg$c88 = function(value) { return value }, peg$c89 = "*", peg$c90 = peg$literalExpectation("*", false), peg$c91 = function(left, right) { return { type: `multiplication`, left, right } }, peg$c92 = "/", peg$c93 = peg$literalExpectation("/", false), peg$c94 = function(left, right) { return { type: `division`, left, right } }, peg$c95 = function(left, right) { return { type: `addition`, left, right } }, peg$c96 = function(left, right) { return { type: `subtraction`, left, right } }, peg$c97 = "$((", peg$c98 = peg$literalExpectation("$((", false), peg$c99 = "))", peg$c100 = peg$literalExpectation("))", false), peg$c101 = function(arithmetic) { return arithmetic }, peg$c102 = "$(", peg$c103 = peg$literalExpectation("$(", false), peg$c104 = function(command) { return command }, peg$c105 = "${", peg$c106 = peg$literalExpectation("${", false), peg$c107 = ":-", peg$c108 = peg$literalExpectation(":-", false), peg$c109 = function(name, arg) { return { name, defaultValue: arg } }, peg$c110 = ":-}", peg$c111 = peg$literalExpectation(":-}", false), peg$c112 = function(name) { return { name, defaultValue: [] } }, peg$c113 = function(name) { return { name } }, peg$c114 = "$", peg$c115 = peg$literalExpectation("$", false), peg$c116 = function(pattern) { return options.isGlobPattern(pattern) }, peg$c117 = function(pattern) { return pattern }, peg$c118 = /^[a-zA-Z0-9_]/, peg$c119 = peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "_"], false, false), peg$c120 = function() { return text() }, peg$c121 = /^[$@*?#a-zA-Z0-9_\-]/, peg$c122 = peg$classExpectation(["$", "@", "*", "?", "#", ["a", "z"], ["A", "Z"], ["0", "9"], "_", "-"], false, false), peg$c123 = /^[(){}<>$|&; \t"']/, peg$c124 = peg$classExpectation(["(", ")", "{", "}", "<", ">", "$", "|", "&", ";", " ", "\t", "\"", "'"], false, false), peg$c125 = /^[<>&; \t"']/, peg$c126 = peg$classExpectation(["<", ">", "&", ";", " ", "\t", "\"", "'"], false, false), peg$c127 = /^[ \t]/, peg$c128 = peg$classExpectation([" ", "\t"], false, false), peg$currPos = 0, peg$savedPos = 0, peg$posDetailsCache = [{ line: 1, column: 1 }], peg$maxFailPos = 0, peg$maxFailExpected = [], peg$silentFails = 0, peg$result; if ("startRule" in options) { if (!(options.startRule in peg$startRuleFunctions)) { throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); } peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; } function text() { return input.substring(peg$savedPos, peg$currPos); } function location() { return peg$computeLocation(peg$savedPos, peg$currPos); } function expected(description, location) { location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos) throw peg$buildStructuredError( [peg$otherExpectation(description)], input.substring(peg$savedPos, peg$currPos), location ); } function error(message, location) { location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos) throw peg$buildSimpleError(message, location); } function peg$literalExpectation(text, ignoreCase) { return { type: "literal", text: text, ignoreCase: ignoreCase }; } function peg$classExpectation(parts, inverted, ignoreCase) { return { type: "class", parts: parts, inverted: inverted, ignoreCase: ignoreCase }; } function peg$anyExpectation() { return { type: "any" }; } function peg$endExpectation() { return { type: "end" }; } function peg$otherExpectation(description) { return { type: "other", description: description }; } function peg$computePosDetails(pos) { var details = peg$posDetailsCache[pos], p; if (details) { return details; } else { p = pos - 1; while (!peg$posDetailsCache[p]) { p--; } details = peg$posDetailsCache[p]; details = { line: details.line, column: details.column }; while (p < pos) { if (input.charCodeAt(p) === 10) { details.line++; details.column = 1; } else { details.column++; } p++; } peg$posDetailsCache[pos] = details; return details; } } function peg$computeLocation(startPos, endPos) { var startPosDetails = peg$computePosDetails(startPos), endPosDetails = peg$computePosDetails(endPos); return { start: { offset: startPos, line: startPosDetails.line, column: startPosDetails.column }, end: { offset: endPos, line: endPosDetails.line, column: endPosDetails.column } }; } function peg$fail(expected) { if (peg$currPos < peg$maxFailPos) { return; } if (peg$currPos > peg$maxFailPos) { peg$maxFailPos = peg$currPos; peg$maxFailExpected = []; } peg$maxFailExpected.push(expected); } function peg$buildSimpleError(message, location) { return new peg$SyntaxError(message, null, null, location); } function peg$buildStructuredError(expected, found, location) { return new peg$SyntaxError( peg$SyntaxError.buildMessage(expected, found), expected, found, location ); } function peg$parseStart() { var s0, s1; s0 = peg$currPos; s1 = peg$parseShellLine(); if (s1 === peg$FAILED) { s1 = null; } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c0(s1); } s0 = s1; return s0; } function peg$parseShellLine() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = peg$parseCommandLine(); if (s1 !== peg$FAILED) { s2 = []; s3 = peg$parseS(); while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$parseS(); } if (s2 !== peg$FAILED) { s3 = peg$parseShellLineType(); if (s3 !== peg$FAILED) { s4 = peg$parseShellLineThen(); if (s4 === peg$FAILED) { s4 = null; } if (s4 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c1(s1, s3, s4); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parseCommandLine(); if (s1 !== peg$FAILED) { s2 = []; s3 = peg$parseS(); while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$parseS(); } if (s2 !== peg$FAILED) { s3 = peg$parseShellLineType(); if (s3 === peg$FAILED) { s3 = null; } if (s3 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c2(s1, s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } return s0; } function peg$parseShellLineThen() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = []; s2 = peg$parseS(); while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$parseS(); } if (s1 !== peg$FAILED) { s2 = peg$parseShellLine(); if (s2 !== peg$FAILED) { s3 = []; s4 = peg$parseS(); while (s4 !== peg$FAILED) { s3.push(s4); s4 = peg$parseS(); } if (s3 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c3(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } return s0; } function peg$parseShellLineType() { var s0; if (input.charCodeAt(peg$currPos) === 59) { s0 = peg$c4; peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c5); } } if (s0 === peg$FAILED) { if (input.charCodeAt(peg$currPos) === 38) { s0 = peg$c6; peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c7); } } } return s0; } function peg$parseCommandLine() { var s0, s1, s2; s0 = peg$currPos; s1 = peg$parseCommandChain(); if (s1 !== peg$FAILED) { s2 = peg$parseCommandLineThen(); if (s2 === peg$FAILED) { s2 = null; } if (s2 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c8(s1, s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } return s0; } function peg$parseCommandLineThen() { var s0, s1, s2, s3, s4, s5, s6; s0 = peg$currPos; s1 = []; s2 = peg$parseS(); while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$parseS(); } if (s1 !== peg$FAILED) { s2 = peg$parseCommandLineType(); if (s2 !== peg$FAILED) { s3 = []; s4 = peg$parseS(); while (s4 !== peg$FAILED) { s3.push(s4); s4 = peg$parseS(); } if (s3 !== peg$FAILED) { s4 = peg$parseCommandLine(); if (s4 !== peg$FAILED) { s5 = []; s6 = peg$parseS(); while (s6 !== peg$FAILED) { s5.push(s6); s6 = peg$parseS(); } if (s5 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c9(s2, s4); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } return s0; } function peg$parseCommandLineType() { var s0; if (input.substr(peg$currPos, 2) === peg$c10) { s0 = peg$c10; peg$currPos += 2; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c11); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 2) === peg$c12) { s0 = peg$c12; peg$currPos += 2; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c13); } } } return s0; } function peg$parseCommandChain() { var s0, s1, s2; s0 = peg$currPos; s1 = peg$parseCommand(); if (s1 !== peg$FAILED) { s2 = peg$parseCommandChainThen(); if (s2 === peg$FAILED) { s2 = null; } if (s2 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c14(s1, s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } return s0; } function peg$parseCommandChainThen() { var s0, s1, s2, s3, s4, s5, s6; s0 = peg$currPos; s1 = []; s2 = peg$parseS(); while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$parseS(); } if (s1 !== peg$FAILED) { s2 = peg$parseCommandChainType(); if (s2 !== peg$FAILED) { s3 = []; s4 = peg$parseS(); while (s4 !== peg$FAILED) { s3.push(s4); s4 = peg$parseS(); } if (s3 !== peg$FAILED) { s4 = peg$parseCommandChain(); if (s4 !== peg$FAILED) { s5 = []; s6 = peg$parseS(); while (s6 !== peg$FAILED) { s5.push(s6); s6 = peg$parseS(); } if (s5 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c15(s2, s4); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } return s0; } function peg$parseCommandChainType() { var s0; if (input.substr(peg$currPos, 2) === peg$c16) { s0 = peg$c16; peg$currPos += 2; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c17); } } if (s0 === peg$FAILED) { if (input.charCodeAt(peg$currPos) === 124) { s0 = peg$c18; peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c19); } } } return s0; } function peg$parseVariableAssignment() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; s1 = peg$parseEnvVariable(); if (s1 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 61) { s2 = peg$c20; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c21); } } if (s2 !== peg$FAILED) { s3 = peg$parseStrictValueArgument(); if (s3 !== peg$FAILED) { s4 = []; s5 = peg$parseS(); while (s5 !== peg$FAILED) { s4.push(s5); s5 = peg$parseS(); } if (s4 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c22(s1, s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parseEnvVariable(); if (s1 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 61) { s2 = peg$c20; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c21); } } if (s2 !== peg$FAILED) { s3 = []; s4 = peg$parseS(); while (s4 !== peg$FAILED) { s3.push(s4); s4 = peg$parseS(); } if (s3 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c23(s1); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } return s0; } function peg$parseCommand() { var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; s0 = peg$currPos; s1 = []; s2 = peg$parseS(); while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$parseS(); } if (s1 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 40) { s2 = peg$c24; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c25); } } if (s2 !== peg$FAILED) { s3 = []; s4 = peg$parseS(); while (s4 !== peg$FAILED) { s3.push(s4); s4 = peg$parseS(); } if (s3 !== peg$FAILED) { s4 = peg$parseShellLine(); if (s4 !== peg$FAILED) { s5 = []; s6 = peg$parseS(); while (s6 !== peg$FAILED) { s5.push(s6); s6 = peg$parseS(); } if (s5 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 41) { s6 = peg$c26; peg$currPos++; } else { s6 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c27); } } if (s6 !== peg$FAILED) { s7 = []; s8 = peg$parseS(); while (s8 !== peg$FAILED) { s7.push(s8); s8 = peg$parseS(); } if (s7 !== peg$FAILED) { s8 = []; s9 = peg$parseRedirectArgument(); while (s9 !== peg$FAILED) { s8.push(s9); s9 = peg$parseRedirectArgument(); } if (s8 !== peg$FAILED) { s9 = []; s10 = peg$parseS(); while (s10 !== peg$FAILED) { s9.push(s10); s10 = peg$parseS(); } if (s9 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c28(s4, s8); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = []; s2 = peg$parseS(); while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$parseS(); } if (s1 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 123) { s2 = peg$c29; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c30); } } if (s2 !== peg$FAILED) { s3 = []; s4 = peg$parseS(); while (s4 !== peg$FAILED) { s3.push(s4); s4 = peg$parseS(); } if (s3 !== peg$FAILED) { s4 = peg$parseShellLine(); if (s4 !== peg$FAILED) { s5 = []; s6 = peg$parseS(); while (s6 !== peg$FAILED) { s5.push(s6); s6 = peg$parseS(); } if (s5 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 125) { s6 = peg$c31; peg$currPos++; } else { s6 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c32); } } if (s6 !== peg$FAILED) { s7 = []; s8 = peg$parseS(); while (s8 !== peg$FAILED) { s7.push(s8); s8 = peg$parseS(); } if (s7 !== peg$FAILED) { s8 = []; s9 = peg$parseRedirectArgument(); while (s9 !== peg$FAILED) { s8.push(s9); s9 = peg$parseRedirectArgument(); } if (s8 !== peg$FAILED) { s9 = []; s10 = peg$parseS(); while (s10 !== peg$FAILED) { s9.push(s10); s10 = peg$parseS(); } if (s9 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c33(s4, s8); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = []; s2 = peg$parseS(); while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$parseS(); } if (s1 !== peg$FAILED) { s2 = []; s3 = peg$parseVariableAssignment(); while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$parseVariableAssignment(); } if (s2 !== peg$FAILED) { s3 = []; s4 = peg$parseS(); while (s4 !== peg$FAILED) { s3.push(s4); s4 = peg$parseS(); } if (s3 !== peg$FAILED) { s4 = []; s5 = peg$parseArgument(); if (s5 !== peg$FAILED) { while (s5 !== peg$FAILED) { s4.push(s5); s5 = peg$parseArgument(); } } else { s4 = peg$FAILED; } if (s4 !== peg$FAILED) { s5 = []; s6 = peg$parseS(); while (s6 !== peg$FAILED) { s5.push(s6); s6 = peg$parseS(); } if (s5 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c34(s2, s4); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = []; s2 = peg$parseS(); while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$parseS(); } if (s1 !== peg$FAILED) { s2 = []; s3 = peg$parseVariableAssignment(); if (s3 !== peg$FAILED) { while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$parseVariableAssignment(); } } else { s2 = peg$FAILED; } if (s2 !== peg$FAILED) { s3 = []; s4 = peg$parseS(); while (s4 !== peg$FAILED) { s3.push(s4); s4 = peg$parseS(); } if (s3 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c35(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } } } return s0; } function peg$parseCommandString() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = []; s2 = peg$parseS(); while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$parseS(); } if (s1 !== peg$FAILED) { s2 = []; s3 = peg$parseValueArgument(); if (s3 !== peg$FAILED) { while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$parseValueArgument(); } } else { s2 = peg$FAILED; } if (s2 !== peg$FAILED) { s3 = []; s4 = peg$parseS(); while (s4 !== peg$FAILED) { s3.push(s4); s4 = peg$parseS(); } if (s3 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c36(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } return s0; } function peg$parseArgument() { var s0, s1, s2; s0 = peg$currPos; s1 = []; s2 = peg$parseS(); while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$parseS(); } if (s1 !== peg$FAILED) { s2 = peg$parseRedirectArgument(); if (s2 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c37(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = []; s2 = peg$parseS(); while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$parseS(); } if (s1 !== peg$FAILED) { s2 = peg$parseValueArgument(); if (s2 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c37(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } return s0; } function peg$parseRedirectArgument() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = []; s2 = peg$parseS(); while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$parseS(); } if (s1 !== peg$FAILED) { if (peg$c38.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c39); } } if (s2 === peg$FAILED) { s2 = null; } if (s2 !== peg$FAILED) { s3 = peg$parseRedirectType(); if (s3 !== peg$FAILED) { s4 = peg$parseValueArgument(); if (s4 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c40(s2, s3, s4); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } return s0; } function peg$parseRedirectType() { var s0; if (input.substr(peg$currPos, 2) === peg$c41) { s0 = peg$c41; peg$currPos += 2; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c42); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 2) === peg$c43) { s0 = peg$c43; peg$currPos += 2; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c44); } } if (s0 === peg$FAILED) { if (input.charCodeAt(peg$currPos) === 62) { s0 = peg$c45; peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c46); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 3) === peg$c47) { s0 = peg$c47; peg$currPos += 3; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c48); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 2) === peg$c49) { s0 = peg$c49; peg$currPos += 2; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c50); } } if (s0 === peg$FAILED) { if (input.charCodeAt(peg$currPos) === 60) { s0 = peg$c51; peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c52); } } } } } } } return s0; } function peg$parseValueArgument() { var s0, s1, s2; s0 = peg$currPos; s1 = []; s2 = peg$parseS(); while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$parseS(); } if (s1 !== peg$FAILED) { s2 = peg$parseStrictValueArgument(); if (s2 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c37(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } return s0; } function peg$parseStrictValueArgument() { var s0, s1, s2; s0 = peg$currPos; s1 = []; s2 = peg$parseArgumentSegment(); if (s2 !== peg$FAILED) { while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$parseArgumentSegment(); } } else { s1 = peg$FAILED; } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c53(s1); } s0 = s1; return s0; } function peg$parseArgumentSegment() { var s0, s1; s0 = peg$currPos; s1 = peg$parseSglQuoteString(); if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c54(s1); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parseDblQuoteString(); if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c54(s1); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parsePlainString(); if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c54(s1); } s0 = s1; } } return s0; } function peg$parseSglQuoteString() { var s0, s1, s2, s3; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 39) { s1 = peg$c55; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c56); } } if (s1 !== peg$FAILED) { s2 = peg$parseSglQuoteStringText(); if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 39) { s3 = peg$c55; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c56); } } if (s3 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c57(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } return s0; } function peg$parseDblQuoteString() { var s0, s1, s2, s3; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 34) { s1 = peg$c58; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c59); } } if (s1 !== peg$FAILED) { s2 = []; s3 = peg$parseDblQuoteStringSegment(); while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$parseDblQuoteStringSegment(); } if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 34) { s3 = peg$c58; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c59); } } if (s3 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c60(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } return s0; } function peg$parsePlainString() { var s0, s1, s2; s0 = peg$currPos; s1 = []; s2 = peg$parsePlainStringSegment(); if (s2 !== peg$FAILED) { while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$parsePlainStringSegment(); } } else { s1 = peg$FAILED; } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c60(s1); } s0 = s1; return s0; } function peg$parseDblQuoteStringSegment() { var s0, s1; s0 = peg$currPos; s1 = peg$parseArithmetic(); if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c61(s1); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parseSubshell(); if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c62(s1); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parseVariable(); if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c63(s1); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parseDblQuoteStringText(); if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c64(s1); } s0 = s1; } } } return s0; } function peg$parsePlainStringSegment() { var s0, s1; s0 = peg$currPos; s1 = peg$parseArithmetic(); if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c65(s1); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parseSubshell(); if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c66(s1); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parseVariable(); if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c67(s1); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parseGlob(); if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c68(s1); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parsePlainStringText(); if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c64(s1); } s0 = s1; } } } } return s0; } function peg$parseSglQuoteStringText() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = []; s2 = peg$currPos; if (input.charCodeAt(peg$currPos) === 92) { s3 = peg$c69; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c70); } } if (s3 !== peg$FAILED) { if (input.length > peg$currPos) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c71); } } if (s4 !== peg$FAILED) { peg$savedPos = s2; s3 = peg$c72(s4); s2 = s3; } else { peg$currPos = s2; s2 = peg$FAILED; } } else { peg$currPos = s2; s2 = peg$FAILED; } if (s2 === peg$FAILED) { if (peg$c73.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c74); } } } while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$currPos; if (input.charCodeAt(peg$currPos) === 92) { s3 = peg$c69; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c70); } } if (s3 !== peg$FAILED) { if (input.length > peg$currPos) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c71); } } if (s4 !== peg$FAILED) { peg$savedPos = s2; s3 = peg$c72(s4); s2 = s3; } else { peg$currPos = s2; s2 = peg$FAILED; } } else { peg$currPos = s2; s2 = peg$FAILED; } if (s2 === peg$FAILED) { if (peg$c73.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c74); } } } } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c75(s1); } s0 = s1; return s0; } function peg$parseDblQuoteStringText() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = []; s2 = peg$currPos; if (input.charCodeAt(peg$currPos) === 92) { s3 = peg$c69; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c70); } } if (s3 !== peg$FAILED) { if (input.length > peg$currPos) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c71); } } if (s4 !== peg$FAILED) { peg$savedPos = s2; s3 = peg$c72(s4); s2 = s3; } else { peg$currPos = s2; s2 = peg$FAILED; } } else { peg$currPos = s2; s2 = peg$FAILED; } if (s2 === peg$FAILED) { if (peg$c76.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c77); } } } if (s2 !== peg$FAILED) { while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$currPos; if (input.charCodeAt(peg$currPos) === 92) { s3 = peg$c69; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c70); } } if (s3 !== peg$FAILED) { if (input.length > peg$currPos) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c71); } } if (s4 !== peg$FAILED) { peg$savedPos = s2; s3 = peg$c72(s4); s2 = s3; } else { peg$currPos = s2; s2 = peg$FAILED; } } else { peg$currPos = s2; s2 = peg$FAILED; } if (s2 === peg$FAILED) { if (peg$c76.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c77); } } } } } else { s1 = peg$FAILED; } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c75(s1); } s0 = s1; return s0; } function peg$parsePlainStringText() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = []; s2 = peg$currPos; if (input.charCodeAt(peg$currPos) === 92) { s3 = peg$c69; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c70); } } if (s3 !== peg$FAILED) { if (input.length > peg$currPos) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c71); } } if (s4 !== peg$FAILED) { peg$savedPos = s2; s3 = peg$c72(s4); s2 = s3; } else { peg$currPos = s2; s2 = peg$FAILED; } } else { peg$currPos = s2; s2 = peg$FAILED; } if (s2 === peg$FAILED) { s2 = peg$currPos; s3 = peg$currPos; peg$silentFails++; s4 = peg$parseSpecialShellChars(); peg$silentFails--; if (s4 === peg$FAILED) { s3 = void 0; } else { peg$currPos = s3; s3 = peg$FAILED; } if (s3 !== peg$FAILED) { if (input.length > peg$currPos) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c71); } } if (s4 !== peg$FAILED) { peg$savedPos = s2; s3 = peg$c72(s4); s2 = s3; } else { peg$currPos = s2; s2 = peg$FAILED; } } else { peg$currPos = s2; s2 = peg$FAILED; } } if (s2 !== peg$FAILED) { while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$currPos; if (input.charCodeAt(peg$currPos) === 92) { s3 = peg$c69; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c70); } } if (s3 !== peg$FAILED) { if (input.length > peg$currPos) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c71); } } if (s4 !== peg$FAILED) { peg$savedPos = s2; s3 = peg$c72(s4); s2 = s3; } else { peg$currPos = s2; s2 = peg$FAILED; } } else { peg$currPos = s2; s2 = peg$FAILED; } if (s2 === peg$FAILED) { s2 = peg$currPos; s3 = peg$currPos; peg$silentFails++; s4 = peg$parseSpecialShellChars(); peg$silentFails--; if (s4 === peg$FAILED) { s3 = void 0; } else { peg$currPos = s3; s3 = peg$FAILED; } if (s3 !== peg$FAILED) { if (input.length > peg$currPos) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c71); } } if (s4 !== peg$FAILED) { peg$savedPos = s2; s3 = peg$c72(s4); s2 = s3; } else { peg$currPos = s2; s2 = peg$FAILED; } } else { peg$currPos = s2; s2 = peg$FAILED; } } } } else { s1 = peg$FAILED; } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c75(s1); } s0 = s1; return s0; } function peg$parseArithmeticPrimary() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 45) { s1 = peg$c78; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c79); } } if (s1 === peg$FAILED) { if (input.charCodeAt(peg$currPos) === 43) { s1 = peg$c80; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c81); } } } if (s1 === peg$FAILED) { s1 = null; } if (s1 !== peg$FAILED) { s2 = []; if (peg$c38.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c39); } } if (s3 !== peg$FAILED) { while (s3 !== peg$FAILED) { s2.push(s3); if (peg$c38.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c39); } } } } else { s2 = peg$FAILED; } if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 46) { s3 = peg$c82; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c83); } } if (s3 !== peg$FAILED) { s4 = []; if (peg$c38.test(input.charAt(peg$currPos))) { s5 = input.charAt(peg$currPos); peg$currPos++; } else { s5 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c39); } } if (s5 !== peg$FAILED) { while (s5 !== peg$FAILED) { s4.push(s5); if (peg$c38.test(input.charAt(peg$currPos))) { s5 = input.charAt(peg$currPos); peg$currPos++; } else { s5 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c39); } } } } else { s4 = peg$FAILED; } if (s4 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c84(s1, s2, s4); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 45) { s1 = peg$c78; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c79); } } if (s1 === peg$FAILED) { if (input.charCodeAt(peg$currPos) === 43) { s1 = peg$c80; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c81); } } } if (s1 === peg$FAILED) { s1 = null; } if (s1 !== peg$FAILED) { s2 = []; if (peg$c38.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c39); } } if (s3 !== peg$FAILED) { while (s3 !== peg$FAILED) { s2.push(s3); if (peg$c38.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c39); } } } } else { s2 = peg$FAILED; } if (s2 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c85(s1, s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parseVariable(); if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c86(s1); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parseIdentifier(); if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c87(s1); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 40) { s1 = peg$c24; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c25); } } if (s1 !== peg$FAILED) { s2 = []; s3 = peg$parseS(); while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$parseS(); } if (s2 !== peg$FAILED) { s3 = peg$parseArithmeticExpression(); if (s3 !== peg$FAILED) { s4 = []; s5 = peg$parseS(); while (s5 !== peg$FAILED) { s4.push(s5); s5 = peg$parseS(); } if (s4 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 41) { s5 = peg$c26; peg$currPos++; } else { s5 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c27); } } if (s5 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c88(s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } } } } return s0; } function peg$parseArithmeticTimesExpression() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; s1 = peg$parseArithmeticPrimary(); if (s1 !== peg$FAILED) { s2 = []; s3 = peg$parseS(); while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$parseS(); } if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 42) { s3 = peg$c89; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c90); } } if (s3 !== peg$FAILED) { s4 = []; s5 = peg$parseS(); while (s5 !== peg$FAILED) { s4.push(s5); s5 = peg$parseS(); } if (s4 !== peg$FAILED) { s5 = peg$parseArithmeticTimesExpression(); if (s5 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c91(s1, s5); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parseArithmeticPrimary(); if (s1 !== peg$FAILED) { s2 = []; s3 = peg$parseS(); while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$parseS(); } if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 47) { s3 = peg$c92; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c93); } } if (s3 !== peg$FAILED) { s4 = []; s5 = peg$parseS(); while (s5 !== peg$FAILED) { s4.push(s5); s5 = peg$parseS(); } if (s4 !== peg$FAILED) { s5 = peg$parseArithmeticTimesExpression(); if (s5 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c94(s1, s5); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$parseArithmeticPrimary(); } } return s0; } function peg$parseArithmeticExpression() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; s1 = peg$parseArithmeticTimesExpression(); if (s1 !== peg$FAILED) { s2 = []; s3 = peg$parseS(); while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$parseS(); } if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 43) { s3 = peg$c80; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c81); } } if (s3 !== peg$FAILED) { s4 = []; s5 = peg$parseS(); while (s5 !== peg$FAILED) { s4.push(s5); s5 = peg$parseS(); } if (s4 !== peg$FAILED) { s5 = peg$parseArithmeticExpression(); if (s5 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c95(s1, s5); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parseArithmeticTimesExpression(); if (s1 !== peg$FAILED) { s2 = []; s3 = peg$parseS(); while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$parseS(); } if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 45) { s3 = peg$c78; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c79); } } if (s3 !== peg$FAILED) { s4 = []; s5 = peg$parseS(); while (s5 !== peg$FAILED) { s4.push(s5); s5 = peg$parseS(); } if (s4 !== peg$FAILED) { s5 = peg$parseArithmeticExpression(); if (s5 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c96(s1, s5); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$parseArithmeticTimesExpression(); } } return s0; } function peg$parseArithmetic() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; if (input.substr(peg$currPos, 3) === peg$c97) { s1 = peg$c97; peg$currPos += 3; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c98); } } if (s1 !== peg$FAILED) { s2 = []; s3 = peg$parseS(); while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$parseS(); } if (s2 !== peg$FAILED) { s3 = peg$parseArithmeticExpression(); if (s3 !== peg$FAILED) { s4 = []; s5 = peg$parseS(); while (s5 !== peg$FAILED) { s4.push(s5); s5 = peg$parseS(); } if (s4 !== peg$FAILED) { if (input.substr(peg$currPos, 2) === peg$c99) { s5 = peg$c99; peg$currPos += 2; } else { s5 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c100); } } if (s5 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c101(s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } return s0; } function peg$parseSubshell() { var s0, s1, s2, s3; s0 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c102) { s1 = peg$c102; peg$currPos += 2; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c103); } } if (s1 !== peg$FAILED) { s2 = peg$parseShellLine(); if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 41) { s3 = peg$c26; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c27); } } if (s3 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c104(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } return s0; } function peg$parseVariable() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c105) { s1 = peg$c105; peg$currPos += 2; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c106); } } if (s1 !== peg$FAILED) { s2 = peg$parseIdentifier(); if (s2 !== peg$FAILED) { if (input.substr(peg$currPos, 2) === peg$c107) { s3 = peg$c107; peg$currPos += 2; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c108); } } if (s3 !== peg$FAILED) { s4 = peg$parseCommandString(); if (s4 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 125) { s5 = peg$c31; peg$currPos++; } else { s5 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c32); } } if (s5 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c109(s2, s4); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c105) { s1 = peg$c105; peg$currPos += 2; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c106); } } if (s1 !== peg$FAILED) { s2 = peg$parseIdentifier(); if (s2 !== peg$FAILED) { if (input.substr(peg$currPos, 3) === peg$c110) { s3 = peg$c110; peg$currPos += 3; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c111); } } if (s3 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c112(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c105) { s1 = peg$c105; peg$currPos += 2; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c106); } } if (s1 !== peg$FAILED) { s2 = peg$parseIdentifier(); if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 125) { s3 = peg$c31; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c32); } } if (s3 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c113(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 36) { s1 = peg$c114; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c115); } } if (s1 !== peg$FAILED) { s2 = peg$parseIdentifier(); if (s2 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c113(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } } } return s0; } function peg$parseGlob() { var s0, s1, s2; s0 = peg$currPos; s1 = peg$parseGlobText(); if (s1 !== peg$FAILED) { peg$savedPos = peg$currPos; s2 = peg$c116(s1); if (s2) { s2 = void 0; } else { s2 = peg$FAILED; } if (s2 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c117(s1); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } return s0; } function peg$parseGlobText() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = []; s2 = peg$currPos; s3 = peg$currPos; peg$silentFails++; s4 = peg$parseGlobSpecialShellChars(); peg$silentFails--; if (s4 === peg$FAILED) { s3 = void 0; } else { peg$currPos = s3; s3 = peg$FAILED; } if (s3 !== peg$FAILED) { if (input.length > peg$currPos) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c71); } } if (s4 !== peg$FAILED) { peg$savedPos = s2; s3 = peg$c72(s4); s2 = s3; } else { peg$currPos = s2; s2 = peg$FAILED; } } else { peg$currPos = s2; s2 = peg$FAILED; } if (s2 !== peg$FAILED) { while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$currPos; s3 = peg$currPos; peg$silentFails++; s4 = peg$parseGlobSpecialShellChars(); peg$silentFails--; if (s4 === peg$FAILED) { s3 = void 0; } else { peg$currPos = s3; s3 = peg$FAILED; } if (s3 !== peg$FAILED) { if (input.length > peg$currPos) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c71); } } if (s4 !== peg$FAILED) { peg$savedPos = s2; s3 = peg$c72(s4); s2 = s3; } else { peg$currPos = s2; s2 = peg$FAILED; } } else { peg$currPos = s2; s2 = peg$FAILED; } } } else { s1 = peg$FAILED; } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c75(s1); } s0 = s1; return s0; } function peg$parseEnvVariable() { var s0, s1, s2; s0 = peg$currPos; s1 = []; if (peg$c118.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c119); } } if (s2 !== peg$FAILED) { while (s2 !== peg$FAILED) { s1.push(s2); if (peg$c118.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c119); } } } } else { s1 = peg$FAILED; } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c120(); } s0 = s1; return s0; } function peg$parseIdentifier() { var s0, s1, s2; s0 = peg$currPos; s1 = []; if (peg$c121.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c122); } } if (s2 !== peg$FAILED) { while (s2 !== peg$FAILED) { s1.push(s2); if (peg$c121.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c122); } } } } else { s1 = peg$FAILED; } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c120(); } s0 = s1; return s0; } function peg$parseSpecialShellChars() { var s0; if (peg$c123.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c124); } } return s0; } function peg$parseGlobSpecialShellChars() { var s0; if (peg$c125.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c126); } } return s0; } function peg$parseS() { var s0, s1; s0 = []; if (peg$c127.test(input.charAt(peg$currPos))) { s1 = input.charAt(peg$currPos); peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c128); } } if (s1 !== peg$FAILED) { while (s1 !== peg$FAILED) { s0.push(s1); if (peg$c127.test(input.charAt(peg$currPos))) { s1 = input.charAt(peg$currPos); peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c128); } } } } else { s0 = peg$FAILED; } return s0; } peg$result = peg$startRuleFunction(); if (peg$result !== peg$FAILED && peg$currPos === input.length) { return peg$result; } else { if (peg$result !== peg$FAILED && peg$currPos < input.length) { peg$fail(peg$endExpectation()); } throw peg$buildStructuredError( peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) : peg$computeLocation(peg$maxFailPos, peg$maxFailPos) ); } } module.exports = { SyntaxError: peg$SyntaxError, parse: peg$parse }; /***/ }), /***/ 59433: /***/ ((module) => { "use strict"; /* * Generated by PEG.js 0.10.0. * * http://pegjs.org/ */ function peg$subclass(child, parent) { function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); } function peg$SyntaxError(message, expected, found, location) { this.message = message; this.expected = expected; this.found = found; this.location = location; this.name = "SyntaxError"; if (typeof Error.captureStackTrace === "function") { Error.captureStackTrace(this, peg$SyntaxError); } } peg$subclass(peg$SyntaxError, Error); peg$SyntaxError.buildMessage = function(expected, found) { var DESCRIBE_EXPECTATION_FNS = { literal: function(expectation) { return "\"" + literalEscape(expectation.text) + "\""; }, "class": function(expectation) { var escapedParts = "", i; for (i = 0; i < expectation.parts.length; i++) { escapedParts += expectation.parts[i] instanceof Array ? classEscape(expectation.parts[i][0]) + "-" + classEscape(expectation.parts[i][1]) : classEscape(expectation.parts[i]); } return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; }, any: function(expectation) { return "any character"; }, end: function(expectation) { return "end of input"; }, other: function(expectation) { return expectation.description; } }; function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); } function literalEscape(s) { return s .replace(/\\/g, '\\\\') .replace(/"/g, '\\"') .replace(/\0/g, '\\0') .replace(/\t/g, '\\t') .replace(/\n/g, '\\n') .replace(/\r/g, '\\r') .replace(/[\x00-\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x' + hex(ch); }); } function classEscape(s) { return s .replace(/\\/g, '\\\\') .replace(/\]/g, '\\]') .replace(/\^/g, '\\^') .replace(/-/g, '\\-') .replace(/\0/g, '\\0') .replace(/\t/g, '\\t') .replace(/\n/g, '\\n') .replace(/\r/g, '\\r') .replace(/[\x00-\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x' + hex(ch); }); } function describeExpectation(expectation) { return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation); } function describeExpected(expected) { var descriptions = new Array(expected.length), i, j; for (i = 0; i < expected.length; i++) { descriptions[i] = describeExpectation(expected[i]); } descriptions.sort(); if (descriptions.length > 0) { for (i = 1, j = 1; i < descriptions.length; i++) { if (descriptions[i - 1] !== descriptions[i]) { descriptions[j] = descriptions[i]; j++; } } descriptions.length = j; } switch (descriptions.length) { case 1: return descriptions[0]; case 2: return descriptions[0] + " or " + descriptions[1]; default: return descriptions.slice(0, -1).join(", ") + ", or " + descriptions[descriptions.length - 1]; } } function describeFound(found) { return found ? "\"" + literalEscape(found) + "\"" : "end of input"; } return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; }; function peg$parse(input, options) { options = options !== void 0 ? options : {}; var peg$FAILED = {}, peg$startRuleFunctions = { Start: peg$parseStart }, peg$startRuleFunction = peg$parseStart, peg$c0 = function(statements) { return [].concat(... statements) }, peg$c1 = "-", peg$c2 = peg$literalExpectation("-", false), peg$c3 = function(value) { return value }, peg$c4 = function(statements) { return Object.assign({}, ... statements) }, peg$c5 = "#", peg$c6 = peg$literalExpectation("#", false), peg$c7 = peg$anyExpectation(), peg$c8 = function() { return {} }, peg$c9 = ":", peg$c10 = peg$literalExpectation(":", false), peg$c11 = function(property, value) { return {[property]: value} }, peg$c12 = ",", peg$c13 = peg$literalExpectation(",", false), peg$c14 = function(property, other) { return other }, peg$c15 = function(property, others, value) { return Object.assign({}, ... [property].concat(others).map(property => ({[property]: value}))) }, peg$c16 = function(statements) { return statements }, peg$c17 = function(expression) { return expression }, peg$c18 = peg$otherExpectation("correct indentation"), peg$c19 = " ", peg$c20 = peg$literalExpectation(" ", false), peg$c21 = function(spaces) { return spaces.length === indentLevel * INDENT_STEP }, peg$c22 = function(spaces) { return spaces.length === (indentLevel + 1) * INDENT_STEP }, peg$c23 = function() { indentLevel++; return true }, peg$c24 = function() { indentLevel--; return true }, peg$c25 = function() { return text() }, peg$c26 = peg$otherExpectation("pseudostring"), peg$c27 = /^[^\r\n\t ?:,\][{}#&*!|>'"%@`\-]/, peg$c28 = peg$classExpectation(["\r", "\n", "\t", " ", "?", ":", ",", "]", "[", "{", "}", "#", "&", "*", "!", "|", ">", "'", "\"", "%", "@", "`", "-"], true, false), peg$c29 = /^[^\r\n\t ,\][{}:#"']/, peg$c30 = peg$classExpectation(["\r", "\n", "\t", " ", ",", "]", "[", "{", "}", ":", "#", "\"", "'"], true, false), peg$c31 = function() { return text().replace(/^ *| *$/g, '') }, peg$c32 = "--", peg$c33 = peg$literalExpectation("--", false), peg$c34 = /^[a-zA-Z\/0-9]/, peg$c35 = peg$classExpectation([["a", "z"], ["A", "Z"], "/", ["0", "9"]], false, false), peg$c36 = /^[^\r\n\t :,]/, peg$c37 = peg$classExpectation(["\r", "\n", "\t", " ", ":", ","], true, false), peg$c38 = "null", peg$c39 = peg$literalExpectation("null", false), peg$c40 = function() { return null }, peg$c41 = "true", peg$c42 = peg$literalExpectation("true", false), peg$c43 = function() { return true }, peg$c44 = "false", peg$c45 = peg$literalExpectation("false", false), peg$c46 = function() { return false }, peg$c47 = peg$otherExpectation("string"), peg$c48 = "\"", peg$c49 = peg$literalExpectation("\"", false), peg$c50 = function() { return "" }, peg$c51 = function(chars) { return chars }, peg$c52 = function(chars) { return chars.join(``) }, peg$c53 = /^[^"\\\0-\x1F\x7F]/, peg$c54 = peg$classExpectation(["\"", "\\", ["\0", "\x1F"], "\x7F"], true, false), peg$c55 = "\\\"", peg$c56 = peg$literalExpectation("\\\"", false), peg$c57 = function() { return `"` }, peg$c58 = "\\\\", peg$c59 = peg$literalExpectation("\\\\", false), peg$c60 = function() { return `\\` }, peg$c61 = "\\/", peg$c62 = peg$literalExpectation("\\/", false), peg$c63 = function() { return `/` }, peg$c64 = "\\b", peg$c65 = peg$literalExpectation("\\b", false), peg$c66 = function() { return `\b` }, peg$c67 = "\\f", peg$c68 = peg$literalExpectation("\\f", false), peg$c69 = function() { return `\f` }, peg$c70 = "\\n", peg$c71 = peg$literalExpectation("\\n", false), peg$c72 = function() { return `\n` }, peg$c73 = "\\r", peg$c74 = peg$literalExpectation("\\r", false), peg$c75 = function() { return `\r` }, peg$c76 = "\\t", peg$c77 = peg$literalExpectation("\\t", false), peg$c78 = function() { return `\t` }, peg$c79 = "\\u", peg$c80 = peg$literalExpectation("\\u", false), peg$c81 = function(h1, h2, h3, h4) { return String.fromCharCode(parseInt(`0x${h1}${h2}${h3}${h4}`)); }, peg$c82 = /^[0-9a-fA-F]/, peg$c83 = peg$classExpectation([["0", "9"], ["a", "f"], ["A", "F"]], false, false), peg$c84 = peg$otherExpectation("blank space"), peg$c85 = /^[ \t]/, peg$c86 = peg$classExpectation([" ", "\t"], false, false), peg$c87 = peg$otherExpectation("white space"), peg$c88 = /^[ \t\n\r]/, peg$c89 = peg$classExpectation([" ", "\t", "\n", "\r"], false, false), peg$c90 = "\r\n", peg$c91 = peg$literalExpectation("\r\n", false), peg$c92 = "\n", peg$c93 = peg$literalExpectation("\n", false), peg$c94 = "\r", peg$c95 = peg$literalExpectation("\r", false), peg$currPos = 0, peg$savedPos = 0, peg$posDetailsCache = [{ line: 1, column: 1 }], peg$maxFailPos = 0, peg$maxFailExpected = [], peg$silentFails = 0, peg$result; if ("startRule" in options) { if (!(options.startRule in peg$startRuleFunctions)) { throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); } peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; } function text() { return input.substring(peg$savedPos, peg$currPos); } function location() { return peg$computeLocation(peg$savedPos, peg$currPos); } function expected(description, location) { location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos) throw peg$buildStructuredError( [peg$otherExpectation(description)], input.substring(peg$savedPos, peg$currPos), location ); } function error(message, location) { location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos) throw peg$buildSimpleError(message, location); } function peg$literalExpectation(text, ignoreCase) { return { type: "literal", text: text, ignoreCase: ignoreCase }; } function peg$classExpectation(parts, inverted, ignoreCase) { return { type: "class", parts: parts, inverted: inverted, ignoreCase: ignoreCase }; } function peg$anyExpectation() { return { type: "any" }; } function peg$endExpectation() { return { type: "end" }; } function peg$otherExpectation(description) { return { type: "other", description: description }; } function peg$computePosDetails(pos) { var details = peg$posDetailsCache[pos], p; if (details) { return details; } else { p = pos - 1; while (!peg$posDetailsCache[p]) { p--; } details = peg$posDetailsCache[p]; details = { line: details.line, column: details.column }; while (p < pos) { if (input.charCodeAt(p) === 10) { details.line++; details.column = 1; } else { details.column++; } p++; } peg$posDetailsCache[pos] = details; return details; } } function peg$computeLocation(startPos, endPos) { var startPosDetails = peg$computePosDetails(startPos), endPosDetails = peg$computePosDetails(endPos); return { start: { offset: startPos, line: startPosDetails.line, column: startPosDetails.column }, end: { offset: endPos, line: endPosDetails.line, column: endPosDetails.column } }; } function peg$fail(expected) { if (peg$currPos < peg$maxFailPos) { return; } if (peg$currPos > peg$maxFailPos) { peg$maxFailPos = peg$currPos; peg$maxFailExpected = []; } peg$maxFailExpected.push(expected); } function peg$buildSimpleError(message, location) { return new peg$SyntaxError(message, null, null, location); } function peg$buildStructuredError(expected, found, location) { return new peg$SyntaxError( peg$SyntaxError.buildMessage(expected, found), expected, found, location ); } function peg$parseStart() { var s0; s0 = peg$parsePropertyStatements(); return s0; } function peg$parseItemStatements() { var s0, s1, s2; s0 = peg$currPos; s1 = []; s2 = peg$parseItemStatement(); while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$parseItemStatement(); } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c0(s1); } s0 = s1; return s0; } function peg$parseItemStatement() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = peg$parseSamedent(); if (s1 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 45) { s2 = peg$c1; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c2); } } if (s2 !== peg$FAILED) { s3 = peg$parseB(); if (s3 !== peg$FAILED) { s4 = peg$parseExpression(); if (s4 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c3(s4); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } return s0; } function peg$parsePropertyStatements() { var s0, s1, s2; s0 = peg$currPos; s1 = []; s2 = peg$parsePropertyStatement(); while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$parsePropertyStatement(); } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c4(s1); } s0 = s1; return s0; } function peg$parsePropertyStatement() { var s0, s1, s2, s3, s4, s5, s6, s7, s8; s0 = peg$currPos; s1 = peg$parseB(); if (s1 === peg$FAILED) { s1 = null; } if (s1 !== peg$FAILED) { s2 = peg$currPos; if (input.charCodeAt(peg$currPos) === 35) { s3 = peg$c5; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c6); } } if (s3 !== peg$FAILED) { s4 = []; s5 = peg$currPos; s6 = peg$currPos; peg$silentFails++; s7 = peg$parseEOL(); peg$silentFails--; if (s7 === peg$FAILED) { s6 = void 0; } else { peg$currPos = s6; s6 = peg$FAILED; } if (s6 !== peg$FAILED) { if (input.length > peg$currPos) { s7 = input.charAt(peg$currPos); peg$currPos++; } else { s7 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c7); } } if (s7 !== peg$FAILED) { s6 = [s6, s7]; s5 = s6; } else { peg$currPos = s5; s5 = peg$FAILED; } } else { peg$currPos = s5; s5 = peg$FAILED; } if (s5 !== peg$FAILED) { while (s5 !== peg$FAILED) { s4.push(s5); s5 = peg$currPos; s6 = peg$currPos; peg$silentFails++; s7 = peg$parseEOL(); peg$silentFails--; if (s7 === peg$FAILED) { s6 = void 0; } else { peg$currPos = s6; s6 = peg$FAILED; } if (s6 !== peg$FAILED) { if (input.length > peg$currPos) { s7 = input.charAt(peg$currPos); peg$currPos++; } else { s7 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c7); } } if (s7 !== peg$FAILED) { s6 = [s6, s7]; s5 = s6; } else { peg$currPos = s5; s5 = peg$FAILED; } } else { peg$currPos = s5; s5 = peg$FAILED; } } } else { s4 = peg$FAILED; } if (s4 !== peg$FAILED) { s3 = [s3, s4]; s2 = s3; } else { peg$currPos = s2; s2 = peg$FAILED; } } else { peg$currPos = s2; s2 = peg$FAILED; } if (s2 === peg$FAILED) { s2 = null; } if (s2 !== peg$FAILED) { s3 = []; s4 = peg$parseEOL_ANY(); if (s4 !== peg$FAILED) { while (s4 !== peg$FAILED) { s3.push(s4); s4 = peg$parseEOL_ANY(); } } else { s3 = peg$FAILED; } if (s3 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c8(); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parseSamedent(); if (s1 !== peg$FAILED) { s2 = peg$parseName(); if (s2 !== peg$FAILED) { s3 = peg$parseB(); if (s3 === peg$FAILED) { s3 = null; } if (s3 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 58) { s4 = peg$c9; peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c10); } } if (s4 !== peg$FAILED) { s5 = peg$parseB(); if (s5 === peg$FAILED) { s5 = null; } if (s5 !== peg$FAILED) { s6 = peg$parseExpression(); if (s6 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c11(s2, s6); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parseSamedent(); if (s1 !== peg$FAILED) { s2 = peg$parseLegacyName(); if (s2 !== peg$FAILED) { s3 = peg$parseB(); if (s3 === peg$FAILED) { s3 = null; } if (s3 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 58) { s4 = peg$c9; peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c10); } } if (s4 !== peg$FAILED) { s5 = peg$parseB(); if (s5 === peg$FAILED) { s5 = null; } if (s5 !== peg$FAILED) { s6 = peg$parseExpression(); if (s6 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c11(s2, s6); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parseSamedent(); if (s1 !== peg$FAILED) { s2 = peg$parseLegacyName(); if (s2 !== peg$FAILED) { s3 = peg$parseB(); if (s3 !== peg$FAILED) { s4 = peg$parseLegacyLiteral(); if (s4 !== peg$FAILED) { s5 = []; s6 = peg$parseEOL_ANY(); if (s6 !== peg$FAILED) { while (s6 !== peg$FAILED) { s5.push(s6); s6 = peg$parseEOL_ANY(); } } else { s5 = peg$FAILED; } if (s5 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c11(s2, s4); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parseSamedent(); if (s1 !== peg$FAILED) { s2 = peg$parseLegacyName(); if (s2 !== peg$FAILED) { s3 = []; s4 = peg$currPos; s5 = peg$parseB(); if (s5 === peg$FAILED) { s5 = null; } if (s5 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 44) { s6 = peg$c12; peg$currPos++; } else { s6 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c13); } } if (s6 !== peg$FAILED) { s7 = peg$parseB(); if (s7 === peg$FAILED) { s7 = null; } if (s7 !== peg$FAILED) { s8 = peg$parseLegacyName(); if (s8 !== peg$FAILED) { peg$savedPos = s4; s5 = peg$c14(s2, s8); s4 = s5; } else { peg$currPos = s4; s4 = peg$FAILED; } } else { peg$currPos = s4; s4 = peg$FAILED; } } else { peg$currPos = s4; s4 = peg$FAILED; } } else { peg$currPos = s4; s4 = peg$FAILED; } if (s4 !== peg$FAILED) { while (s4 !== peg$FAILED) { s3.push(s4); s4 = peg$currPos; s5 = peg$parseB(); if (s5 === peg$FAILED) { s5 = null; } if (s5 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 44) { s6 = peg$c12; peg$currPos++; } else { s6 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c13); } } if (s6 !== peg$FAILED) { s7 = peg$parseB(); if (s7 === peg$FAILED) { s7 = null; } if (s7 !== peg$FAILED) { s8 = peg$parseLegacyName(); if (s8 !== peg$FAILED) { peg$savedPos = s4; s5 = peg$c14(s2, s8); s4 = s5; } else { peg$currPos = s4; s4 = peg$FAILED; } } else { peg$currPos = s4; s4 = peg$FAILED; } } else { peg$currPos = s4; s4 = peg$FAILED; } } else { peg$currPos = s4; s4 = peg$FAILED; } } } else { s3 = peg$FAILED; } if (s3 !== peg$FAILED) { s4 = peg$parseB(); if (s4 === peg$FAILED) { s4 = null; } if (s4 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 58) { s5 = peg$c9; peg$currPos++; } else { s5 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c10); } } if (s5 !== peg$FAILED) { s6 = peg$parseB(); if (s6 === peg$FAILED) { s6 = null; } if (s6 !== peg$FAILED) { s7 = peg$parseExpression(); if (s7 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c15(s2, s3, s7); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } } } } return s0; } function peg$parseExpression() { var s0, s1, s2, s3, s4, s5, s6; s0 = peg$currPos; s1 = peg$currPos; peg$silentFails++; s2 = peg$currPos; s3 = peg$parseEOL(); if (s3 !== peg$FAILED) { s4 = peg$parseExtradent(); if (s4 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 45) { s5 = peg$c1; peg$currPos++; } else { s5 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c2); } } if (s5 !== peg$FAILED) { s6 = peg$parseB(); if (s6 !== peg$FAILED) { s3 = [s3, s4, s5, s6]; s2 = s3; } else { peg$currPos = s2; s2 = peg$FAILED; } } else { peg$currPos = s2; s2 = peg$FAILED; } } else { peg$currPos = s2; s2 = peg$FAILED; } } else { peg$currPos = s2; s2 = peg$FAILED; } peg$silentFails--; if (s2 !== peg$FAILED) { peg$currPos = s1; s1 = void 0; } else { s1 = peg$FAILED; } if (s1 !== peg$FAILED) { s2 = peg$parseEOL_ANY(); if (s2 !== peg$FAILED) { s3 = peg$parseIndent(); if (s3 !== peg$FAILED) { s4 = peg$parseItemStatements(); if (s4 !== peg$FAILED) { s5 = peg$parseDedent(); if (s5 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c16(s4); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parseEOL(); if (s1 !== peg$FAILED) { s2 = peg$parseIndent(); if (s2 !== peg$FAILED) { s3 = peg$parsePropertyStatements(); if (s3 !== peg$FAILED) { s4 = peg$parseDedent(); if (s4 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c16(s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parseLiteral(); if (s1 !== peg$FAILED) { s2 = []; s3 = peg$parseEOL_ANY(); if (s3 !== peg$FAILED) { while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$parseEOL_ANY(); } } else { s2 = peg$FAILED; } if (s2 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c17(s1); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } } return s0; } function peg$parseSamedent() { var s0, s1, s2; peg$silentFails++; s0 = peg$currPos; s1 = []; if (input.charCodeAt(peg$currPos) === 32) { s2 = peg$c19; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c20); } } while (s2 !== peg$FAILED) { s1.push(s2); if (input.charCodeAt(peg$currPos) === 32) { s2 = peg$c19; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c20); } } } if (s1 !== peg$FAILED) { peg$savedPos = peg$currPos; s2 = peg$c21(s1); if (s2) { s2 = void 0; } else { s2 = peg$FAILED; } if (s2 !== peg$FAILED) { s1 = [s1, s2]; s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } peg$silentFails--; if (s0 === peg$FAILED) { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c18); } } return s0; } function peg$parseExtradent() { var s0, s1, s2; s0 = peg$currPos; s1 = []; if (input.charCodeAt(peg$currPos) === 32) { s2 = peg$c19; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c20); } } while (s2 !== peg$FAILED) { s1.push(s2); if (input.charCodeAt(peg$currPos) === 32) { s2 = peg$c19; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c20); } } } if (s1 !== peg$FAILED) { peg$savedPos = peg$currPos; s2 = peg$c22(s1); if (s2) { s2 = void 0; } else { s2 = peg$FAILED; } if (s2 !== peg$FAILED) { s1 = [s1, s2]; s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } return s0; } function peg$parseIndent() { var s0; peg$savedPos = peg$currPos; s0 = peg$c23(); if (s0) { s0 = void 0; } else { s0 = peg$FAILED; } return s0; } function peg$parseDedent() { var s0; peg$savedPos = peg$currPos; s0 = peg$c24(); if (s0) { s0 = void 0; } else { s0 = peg$FAILED; } return s0; } function peg$parseName() { var s0; s0 = peg$parsestring(); if (s0 === peg$FAILED) { s0 = peg$parsepseudostring(); } return s0; } function peg$parseLegacyName() { var s0, s1, s2; s0 = peg$parsestring(); if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = []; s2 = peg$parsepseudostringLegacy(); if (s2 !== peg$FAILED) { while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$parsepseudostringLegacy(); } } else { s1 = peg$FAILED; } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c25(); } s0 = s1; } return s0; } function peg$parseLiteral() { var s0; s0 = peg$parsenull(); if (s0 === peg$FAILED) { s0 = peg$parseboolean(); if (s0 === peg$FAILED) { s0 = peg$parsestring(); if (s0 === peg$FAILED) { s0 = peg$parsepseudostring(); } } } return s0; } function peg$parseLegacyLiteral() { var s0; s0 = peg$parsenull(); if (s0 === peg$FAILED) { s0 = peg$parsestring(); if (s0 === peg$FAILED) { s0 = peg$parsepseudostringLegacy(); } } return s0; } function peg$parsepseudostring() { var s0, s1, s2, s3, s4, s5; peg$silentFails++; s0 = peg$currPos; if (peg$c27.test(input.charAt(peg$currPos))) { s1 = input.charAt(peg$currPos); peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c28); } } if (s1 !== peg$FAILED) { s2 = []; s3 = peg$currPos; s4 = peg$parseB(); if (s4 === peg$FAILED) { s4 = null; } if (s4 !== peg$FAILED) { if (peg$c29.test(input.charAt(peg$currPos))) { s5 = input.charAt(peg$currPos); peg$currPos++; } else { s5 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c30); } } if (s5 !== peg$FAILED) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$currPos; s4 = peg$parseB(); if (s4 === peg$FAILED) { s4 = null; } if (s4 !== peg$FAILED) { if (peg$c29.test(input.charAt(peg$currPos))) { s5 = input.charAt(peg$currPos); peg$currPos++; } else { s5 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c30); } } if (s5 !== peg$FAILED) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } } if (s2 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c31(); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } peg$silentFails--; if (s0 === peg$FAILED) { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c26); } } return s0; } function peg$parsepseudostringLegacy() { var s0, s1, s2, s3, s4; s0 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c32) { s1 = peg$c32; peg$currPos += 2; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c33); } } if (s1 === peg$FAILED) { s1 = null; } if (s1 !== peg$FAILED) { if (peg$c34.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c35); } } if (s2 !== peg$FAILED) { s3 = []; if (peg$c36.test(input.charAt(peg$currPos))) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c37); } } while (s4 !== peg$FAILED) { s3.push(s4); if (peg$c36.test(input.charAt(peg$currPos))) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c37); } } } if (s3 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c31(); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } return s0; } function peg$parsenull() { var s0, s1; s0 = peg$currPos; if (input.substr(peg$currPos, 4) === peg$c38) { s1 = peg$c38; peg$currPos += 4; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c39); } } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c40(); } s0 = s1; return s0; } function peg$parseboolean() { var s0, s1; s0 = peg$currPos; if (input.substr(peg$currPos, 4) === peg$c41) { s1 = peg$c41; peg$currPos += 4; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c42); } } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c43(); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.substr(peg$currPos, 5) === peg$c44) { s1 = peg$c44; peg$currPos += 5; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c45); } } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c46(); } s0 = s1; } return s0; } function peg$parsestring() { var s0, s1, s2, s3; peg$silentFails++; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 34) { s1 = peg$c48; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c49); } } if (s1 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 34) { s2 = peg$c48; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c49); } } if (s2 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c50(); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 34) { s1 = peg$c48; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c49); } } if (s1 !== peg$FAILED) { s2 = peg$parsechars(); if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 34) { s3 = peg$c48; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c49); } } if (s3 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c51(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } peg$silentFails--; if (s0 === peg$FAILED) { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c47); } } return s0; } function peg$parsechars() { var s0, s1, s2; s0 = peg$currPos; s1 = []; s2 = peg$parsechar(); if (s2 !== peg$FAILED) { while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$parsechar(); } } else { s1 = peg$FAILED; } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c52(s1); } s0 = s1; return s0; } function peg$parsechar() { var s0, s1, s2, s3, s4, s5; if (peg$c53.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c54); } } if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c55) { s1 = peg$c55; peg$currPos += 2; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c56); } } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c57(); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c58) { s1 = peg$c58; peg$currPos += 2; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c59); } } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c60(); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c61) { s1 = peg$c61; peg$currPos += 2; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c62); } } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c63(); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c64) { s1 = peg$c64; peg$currPos += 2; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c65); } } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c66(); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c67) { s1 = peg$c67; peg$currPos += 2; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c68); } } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c69(); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c70) { s1 = peg$c70; peg$currPos += 2; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c71); } } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c72(); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c73) { s1 = peg$c73; peg$currPos += 2; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c74); } } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c75(); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c76) { s1 = peg$c76; peg$currPos += 2; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c77); } } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c78(); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c79) { s1 = peg$c79; peg$currPos += 2; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c80); } } if (s1 !== peg$FAILED) { s2 = peg$parsehexDigit(); if (s2 !== peg$FAILED) { s3 = peg$parsehexDigit(); if (s3 !== peg$FAILED) { s4 = peg$parsehexDigit(); if (s4 !== peg$FAILED) { s5 = peg$parsehexDigit(); if (s5 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c81(s2, s3, s4, s5); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } } } } } } } } } return s0; } function peg$parsehexDigit() { var s0; if (peg$c82.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c83); } } return s0; } function peg$parseB() { var s0, s1; peg$silentFails++; s0 = []; if (peg$c85.test(input.charAt(peg$currPos))) { s1 = input.charAt(peg$currPos); peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c86); } } if (s1 !== peg$FAILED) { while (s1 !== peg$FAILED) { s0.push(s1); if (peg$c85.test(input.charAt(peg$currPos))) { s1 = input.charAt(peg$currPos); peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c86); } } } } else { s0 = peg$FAILED; } peg$silentFails--; if (s0 === peg$FAILED) { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c84); } } return s0; } function peg$parseS() { var s0, s1; peg$silentFails++; s0 = []; if (peg$c88.test(input.charAt(peg$currPos))) { s1 = input.charAt(peg$currPos); peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c89); } } if (s1 !== peg$FAILED) { while (s1 !== peg$FAILED) { s0.push(s1); if (peg$c88.test(input.charAt(peg$currPos))) { s1 = input.charAt(peg$currPos); peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c89); } } } } else { s0 = peg$FAILED; } peg$silentFails--; if (s0 === peg$FAILED) { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c87); } } return s0; } function peg$parseEOL_ANY() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; s1 = peg$parseEOL(); if (s1 !== peg$FAILED) { s2 = []; s3 = peg$currPos; s4 = peg$parseB(); if (s4 === peg$FAILED) { s4 = null; } if (s4 !== peg$FAILED) { s5 = peg$parseEOL(); if (s5 !== peg$FAILED) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$currPos; s4 = peg$parseB(); if (s4 === peg$FAILED) { s4 = null; } if (s4 !== peg$FAILED) { s5 = peg$parseEOL(); if (s5 !== peg$FAILED) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } } if (s2 !== peg$FAILED) { s1 = [s1, s2]; s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } return s0; } function peg$parseEOL() { var s0; if (input.substr(peg$currPos, 2) === peg$c90) { s0 = peg$c90; peg$currPos += 2; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c91); } } if (s0 === peg$FAILED) { if (input.charCodeAt(peg$currPos) === 10) { s0 = peg$c92; peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c93); } } if (s0 === peg$FAILED) { if (input.charCodeAt(peg$currPos) === 13) { s0 = peg$c94; peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c95); } } } } return s0; } const INDENT_STEP = 2; let indentLevel = 0; peg$result = peg$startRuleFunction(); if (peg$result !== peg$FAILED && peg$currPos === input.length) { return peg$result; } else { if (peg$result !== peg$FAILED && peg$currPos < input.length) { peg$fail(peg$endExpectation()); } throw peg$buildStructuredError( peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) : peg$computeLocation(peg$maxFailPos, peg$maxFailPos) ); } } module.exports = { SyntaxError: peg$SyntaxError, parse: peg$parse }; /***/ }), /***/ 21717: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.stringifySyml = exports.parseSyml = exports.stringifyResolution = exports.parseResolution = exports.stringifyValueArgument = exports.stringifyShellLine = exports.stringifyRedirectArgument = exports.stringifyEnvSegment = exports.stringifyCommandLineThen = exports.stringifyCommandLine = exports.stringifyCommandChainThen = exports.stringifyCommandChain = exports.stringifyCommand = exports.stringifyArithmeticExpression = exports.stringifyArgumentSegment = exports.stringifyArgument = exports.stringifyShell = exports.parseShell = void 0; var shell_1 = __webpack_require__(86430); Object.defineProperty(exports, "parseShell", ({ enumerable: true, get: function () { return shell_1.parseShell; } })); Object.defineProperty(exports, "stringifyShell", ({ enumerable: true, get: function () { return shell_1.stringifyShell; } })); Object.defineProperty(exports, "stringifyArgument", ({ enumerable: true, get: function () { return shell_1.stringifyArgument; } })); Object.defineProperty(exports, "stringifyArgumentSegment", ({ enumerable: true, get: function () { return shell_1.stringifyArgumentSegment; } })); Object.defineProperty(exports, "stringifyArithmeticExpression", ({ enumerable: true, get: function () { return shell_1.stringifyArithmeticExpression; } })); Object.defineProperty(exports, "stringifyCommand", ({ enumerable: true, get: function () { return shell_1.stringifyCommand; } })); Object.defineProperty(exports, "stringifyCommandChain", ({ enumerable: true, get: function () { return shell_1.stringifyCommandChain; } })); Object.defineProperty(exports, "stringifyCommandChainThen", ({ enumerable: true, get: function () { return shell_1.stringifyCommandChainThen; } })); Object.defineProperty(exports, "stringifyCommandLine", ({ enumerable: true, get: function () { return shell_1.stringifyCommandLine; } })); Object.defineProperty(exports, "stringifyCommandLineThen", ({ enumerable: true, get: function () { return shell_1.stringifyCommandLineThen; } })); Object.defineProperty(exports, "stringifyEnvSegment", ({ enumerable: true, get: function () { return shell_1.stringifyEnvSegment; } })); Object.defineProperty(exports, "stringifyRedirectArgument", ({ enumerable: true, get: function () { return shell_1.stringifyRedirectArgument; } })); Object.defineProperty(exports, "stringifyShellLine", ({ enumerable: true, get: function () { return shell_1.stringifyShellLine; } })); Object.defineProperty(exports, "stringifyValueArgument", ({ enumerable: true, get: function () { return shell_1.stringifyValueArgument; } })); var resolution_1 = __webpack_require__(88761); Object.defineProperty(exports, "parseResolution", ({ enumerable: true, get: function () { return resolution_1.parseResolution; } })); Object.defineProperty(exports, "stringifyResolution", ({ enumerable: true, get: function () { return resolution_1.stringifyResolution; } })); var syml_1 = __webpack_require__(69098); Object.defineProperty(exports, "parseSyml", ({ enumerable: true, get: function () { return syml_1.parseSyml; } })); Object.defineProperty(exports, "stringifySyml", ({ enumerable: true, get: function () { return syml_1.stringifySyml; } })); /***/ }), /***/ 88761: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.stringifyResolution = exports.parseResolution = void 0; const resolution_1 = __webpack_require__(92460); function parseResolution(source) { const legacyResolution = source.match(/^\*{1,2}\/(.*)/); if (legacyResolution) throw new Error(`The override for '${source}' includes a glob pattern. Glob patterns have been removed since their behaviours don't match what you'd expect. Set the override to '${legacyResolution[1]}' instead.`); try { return resolution_1.parse(source); } catch (error) { if (error.location) error.message = error.message.replace(/(\.)?$/, ` (line ${error.location.start.line}, column ${error.location.start.column})$1`); throw error; } } exports.parseResolution = parseResolution; function stringifyResolution(resolution) { let str = ``; if (resolution.from) { str += resolution.from.fullName; if (resolution.from.description) str += `@${resolution.from.description}`; str += `/`; } str += resolution.descriptor.fullName; if (resolution.descriptor.description) str += `@${resolution.descriptor.description}`; return str; } exports.stringifyResolution = stringifyResolution; /***/ }), /***/ 86430: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.stringifyShell = exports.stringifyArithmeticExpression = exports.stringifyArgumentSegment = exports.stringifyValueArgument = exports.stringifyRedirectArgument = exports.stringifyArgument = exports.stringifyEnvSegment = exports.stringifyCommand = exports.stringifyCommandChainThen = exports.stringifyCommandChain = exports.stringifyCommandLineThen = exports.stringifyCommandLine = exports.stringifyShellLine = exports.parseShell = void 0; const shell_1 = __webpack_require__(64399); function parseShell(source, options = { isGlobPattern: () => false }) { try { return shell_1.parse(source, options); } catch (error) { if (error.location) error.message = error.message.replace(/(\.)?$/, ` (line ${error.location.start.line}, column ${error.location.start.column})$1`); throw error; } } exports.parseShell = parseShell; function stringifyShellLine(shellLine, { endSemicolon = false } = {}) { return shellLine .map(({ command, type }, index) => `${stringifyCommandLine(command)}${type === `;` ? (index !== shellLine.length - 1 || endSemicolon ? `;` : ``) : ` &`}`) .join(` `); } exports.stringifyShellLine = stringifyShellLine; exports.stringifyShell = stringifyShellLine; function stringifyCommandLine(commandLine) { return `${stringifyCommandChain(commandLine.chain)}${commandLine.then ? ` ${stringifyCommandLineThen(commandLine.then)}` : ``}`; } exports.stringifyCommandLine = stringifyCommandLine; function stringifyCommandLineThen(commandLineThen) { return `${commandLineThen.type} ${stringifyCommandLine(commandLineThen.line)}`; } exports.stringifyCommandLineThen = stringifyCommandLineThen; function stringifyCommandChain(commandChain) { return `${stringifyCommand(commandChain)}${commandChain.then ? ` ${stringifyCommandChainThen(commandChain.then)}` : ``}`; } exports.stringifyCommandChain = stringifyCommandChain; function stringifyCommandChainThen(commandChainThen) { return `${commandChainThen.type} ${stringifyCommandChain(commandChainThen.chain)}`; } exports.stringifyCommandChainThen = stringifyCommandChainThen; function stringifyCommand(command) { switch (command.type) { case `command`: return `${command.envs.length > 0 ? `${command.envs.map(env => stringifyEnvSegment(env)).join(` `)} ` : ``}${command.args.map(argument => stringifyArgument(argument)).join(` `)}`; case `subshell`: return `(${stringifyShellLine(command.subshell)})${command.args.length > 0 ? ` ${command.args.map(argument => stringifyRedirectArgument(argument)).join(` `)}` : ``}`; case `group`: return `{ ${stringifyShellLine(command.group, { /* Bash compat */ endSemicolon: true })} }${command.args.length > 0 ? ` ${command.args.map(argument => stringifyRedirectArgument(argument)).join(` `)}` : ``}`; case `envs`: return command.envs.map(env => stringifyEnvSegment(env)).join(` `); default: throw new Error(`Unsupported command type: "${command.type}"`); } } exports.stringifyCommand = stringifyCommand; function stringifyEnvSegment(envSegment) { return `${envSegment.name}=${envSegment.args[0] ? stringifyValueArgument(envSegment.args[0]) : ``}`; } exports.stringifyEnvSegment = stringifyEnvSegment; function stringifyArgument(argument) { switch (argument.type) { case `redirection`: return stringifyRedirectArgument(argument); case `argument`: return stringifyValueArgument(argument); default: throw new Error(`Unsupported argument type: "${argument.type}"`); } } exports.stringifyArgument = stringifyArgument; function stringifyRedirectArgument(argument) { return `${argument.subtype} ${argument.args.map(argument => stringifyValueArgument(argument)).join(` `)}`; } exports.stringifyRedirectArgument = stringifyRedirectArgument; function stringifyValueArgument(argument) { return argument.segments.map(segment => stringifyArgumentSegment(segment)).join(``); } exports.stringifyValueArgument = stringifyValueArgument; function stringifyArgumentSegment(argumentSegment) { const doubleQuoteIfRequested = (string, quote) => quote ? `"${string}"` : string; const quoteIfNeeded = (string) => { if (!string.match(/[(){}<>$|&; \t"']/)) return string; if (!string.match(/[$"]/)) return `"${string}"`; return `'${string.replace(/[']/g, `\\'`)}'`; }; switch (argumentSegment.type) { case `text`: return quoteIfNeeded(argumentSegment.text); case `glob`: return argumentSegment.pattern; case `shell`: return doubleQuoteIfRequested(`\${${stringifyShellLine(argumentSegment.shell)}}`, argumentSegment.quoted); case `variable`: return doubleQuoteIfRequested(typeof argumentSegment.defaultValue === `undefined` ? `\${${argumentSegment.name}}` : argumentSegment.defaultValue.length === 0 ? `\${${argumentSegment.name}:-}` : `\${${argumentSegment.name}:-${argumentSegment.defaultValue.map(argument => stringifyValueArgument(argument)).join(` `)}}`, argumentSegment.quoted); case `arithmetic`: return `$(( ${stringifyArithmeticExpression(argumentSegment.arithmetic)} ))`; default: throw new Error(`Unsupported argument segment type: "${argumentSegment.type}"`); } } exports.stringifyArgumentSegment = stringifyArgumentSegment; function stringifyArithmeticExpression(argument) { const getOperator = (type) => { switch (type) { case `addition`: return `+`; case `subtraction`: return `-`; case `multiplication`: return `*`; case `division`: return `/`; default: throw new Error(`Can't extract operator from arithmetic expression of type "${type}"`); } }; const parenthesizeIfRequested = (string, parenthesize) => parenthesize ? `( ${string} )` : string; const stringifyAndParenthesizeIfNeeded = (expression) => // Right now we parenthesize all arithmetic operator expressions because it's easier parenthesizeIfRequested(stringifyArithmeticExpression(expression), ![`number`, `variable`].includes(expression.type)); switch (argument.type) { case `number`: return String(argument.value); case `variable`: return argument.name; default: return `${stringifyAndParenthesizeIfNeeded(argument.left)} ${getOperator(argument.type)} ${stringifyAndParenthesizeIfNeeded(argument.right)}`; } } exports.stringifyArithmeticExpression = stringifyArithmeticExpression; /***/ }), /***/ 69098: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseSyml = exports.stringifySyml = exports.PreserveOrdering = void 0; const js_yaml_1 = __webpack_require__(93320); const syml_1 = __webpack_require__(59433); const simpleStringPattern = /^(?![-?:,\][{}#&*!|>'"%@` \t\r\n]).([ \t]*(?![,\][{}:# \t\r\n]).)*$/; // The following keys will always be stored at the top of the object, in the // specified order. It's not fair but life isn't fair either. const specialObjectKeys = [`__metadata`, `version`, `resolution`, `dependencies`, `peerDependencies`, `dependenciesMeta`, `peerDependenciesMeta`, `binaries`]; class PreserveOrdering { constructor(data) { this.data = data; } } exports.PreserveOrdering = PreserveOrdering; function stringifyString(value) { if (value.match(simpleStringPattern)) { return value; } else { return JSON.stringify(value); } } function isRemovableField(value) { if (typeof value === `undefined`) return true; if (typeof value === `object` && value !== null) return Object.keys(value).every(key => isRemovableField(value[key])); return false; } function stringifyValue(value, indentLevel, newLineIfObject) { if (value === null) return `null\n`; if (typeof value === `number` || typeof value === `boolean`) return `${value.toString()}\n`; if (typeof value === `string`) return `${stringifyString(value)}\n`; if (Array.isArray(value)) { if (value.length === 0) return `[]\n`; const indent = ` `.repeat(indentLevel); const serialized = value.map(sub => { return `${indent}- ${stringifyValue(sub, indentLevel + 1, false)}`; }).join(``); return `\n${serialized}`; } if (typeof value === `object` && value) { let data; let sort; if (value instanceof PreserveOrdering) { data = value.data; sort = false; } else { data = value; sort = true; } const indent = ` `.repeat(indentLevel); const keys = Object.keys(data); if (sort) { keys.sort((a, b) => { const aIndex = specialObjectKeys.indexOf(a); const bIndex = specialObjectKeys.indexOf(b); if (aIndex === -1 && bIndex === -1) return a < b ? -1 : a > b ? +1 : 0; if (aIndex !== -1 && bIndex === -1) return -1; if (aIndex === -1 && bIndex !== -1) return +1; return aIndex - bIndex; }); } const fields = keys.filter(key => { return !isRemovableField(data[key]); }).map((key, index) => { const value = data[key]; const stringifiedKey = stringifyString(key); const stringifiedValue = stringifyValue(value, indentLevel + 1, true); const recordIndentation = index > 0 || newLineIfObject ? indent : ``; if (stringifiedValue.startsWith(`\n`)) { return `${recordIndentation}${stringifiedKey}:${stringifiedValue}`; } else { return `${recordIndentation}${stringifiedKey}: ${stringifiedValue}`; } }).join(indentLevel === 0 ? `\n` : ``) || `\n`; if (!newLineIfObject) { return `${fields}`; } else { return `\n${fields}`; } } throw new Error(`Unsupported value type (${value})`); } function stringifySyml(value) { try { const stringified = stringifyValue(value, 0, false); return stringified !== `\n` ? stringified : ``; } catch (error) { if (error.location) error.message = error.message.replace(/(\.)?$/, ` (line ${error.location.start.line}, column ${error.location.start.column})$1`); throw error; } } exports.stringifySyml = stringifySyml; stringifySyml.PreserveOrdering = PreserveOrdering; function parseViaPeg(source) { if (!source.endsWith(`\n`)) source += `\n`; return syml_1.parse(source); } const LEGACY_REGEXP = /^(#.*(\r?\n))*?#\s+yarn\s+lockfile\s+v1\r?\n/i; function parseViaJsYaml(source) { if (LEGACY_REGEXP.test(source)) return parseViaPeg(source); const value = js_yaml_1.safeLoad(source, { schema: js_yaml_1.FAILSAFE_SCHEMA, json: true, }); // Empty files are parsed as `undefined` instead of an empty object // Empty files with 2 newlines or more are `null` instead if (value === undefined || value === null) return {}; if (typeof value !== `object`) throw new Error(`Expected an indexed object, got a ${typeof value} instead. Does your file follow Yaml's rules?`); if (Array.isArray(value)) throw new Error(`Expected an indexed object, got an array instead. Does your file follow Yaml's rules?`); return value; } function parseSyml(source) { return parseViaJsYaml(source); } exports.parseSyml = parseSyml; /***/ }), /***/ 9478: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ShellError = void 0; /** * A recoverable shell error. */ class ShellError extends Error { constructor(message) { super(message); this.name = `ShellError`; } } exports.ShellError = ShellError; /***/ }), /***/ 18236: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isBraceExpansion = exports.match = exports.isGlobPattern = exports.fastGlobOptions = exports.micromatchOptions = void 0; const tslib_1 = __webpack_require__(70655); const fslib_1 = __webpack_require__(91794); const fast_glob_1 = tslib_1.__importDefault(__webpack_require__(13294)); const fs_1 = tslib_1.__importDefault(__webpack_require__(57147)); const micromatch_1 = tslib_1.__importDefault(__webpack_require__(70850)); exports.micromatchOptions = { // This is required because we don't want ")/*" to be a valid shell glob pattern. strictBrackets: true, }; exports.fastGlobOptions = { onlyDirectories: false, onlyFiles: false, }; /** * Decides whether a string is a glob pattern, using micromatch. * * Required because `fastGlob.isDynamicPattern` doesn't have the `strictBrackets` option. */ function isGlobPattern(pattern) { // The scanner extracts globs from a pattern, but doesn't throw errors if (!micromatch_1.default.scan(pattern, exports.micromatchOptions).isGlob) return false; // The parser is the one that throws errors try { micromatch_1.default.parse(pattern, exports.micromatchOptions); } catch (_a) { return false; } return true; } exports.isGlobPattern = isGlobPattern; function match(pattern, { cwd, baseFs }) { return fast_glob_1.default(pattern, { ...exports.fastGlobOptions, cwd: fslib_1.npath.fromPortablePath(cwd), fs: fslib_1.extendFs(fs_1.default, new fslib_1.PosixFS(baseFs)), }); } exports.match = match; function isBraceExpansion(pattern) { return micromatch_1.default.scan(pattern, exports.micromatchOptions).isBrace; } exports.isBraceExpansion = isBraceExpansion; /***/ }), /***/ 56096: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.execute = exports.ShellError = exports.globUtils = void 0; const tslib_1 = __webpack_require__(70655); const fslib_1 = __webpack_require__(91794); const parsers_1 = __webpack_require__(21717); const os_1 = __webpack_require__(22037); const stream_1 = __webpack_require__(12781); const errors_1 = __webpack_require__(9478); Object.defineProperty(exports, "ShellError", ({ enumerable: true, get: function () { return errors_1.ShellError; } })); const globUtils = tslib_1.__importStar(__webpack_require__(18236)); exports.globUtils = globUtils; const pipe_1 = __webpack_require__(74253); const pipe_2 = __webpack_require__(74253); var StreamType; (function (StreamType) { StreamType[StreamType["Readable"] = 1] = "Readable"; StreamType[StreamType["Writable"] = 2] = "Writable"; })(StreamType || (StreamType = {})); function getFileDescriptorStream(fd, type, state) { const stream = new stream_1.PassThrough({ autoDestroy: true }); switch (fd) { case pipe_2.Pipe.STDIN: { if ((type & StreamType.Readable) === StreamType.Readable) state.stdin.pipe(stream, { end: false }); if ((type & StreamType.Writable) === StreamType.Writable && state.stdin instanceof stream_1.Writable) { stream.pipe(state.stdin, { end: false }); } } break; case pipe_2.Pipe.STDOUT: { if ((type & StreamType.Readable) === StreamType.Readable) state.stdout.pipe(stream, { end: false }); if ((type & StreamType.Writable) === StreamType.Writable) { stream.pipe(state.stdout, { end: false }); } } break; case pipe_2.Pipe.STDERR: { if ((type & StreamType.Readable) === StreamType.Readable) state.stderr.pipe(stream, { end: false }); if ((type & StreamType.Writable) === StreamType.Writable) { stream.pipe(state.stderr, { end: false }); } } break; default: { throw new errors_1.ShellError(`Bad file descriptor: "${fd}"`); } } return stream; } function cloneState(state, mergeWith = {}) { const newState = { ...state, ...mergeWith }; newState.environment = { ...state.environment, ...mergeWith.environment }; newState.variables = { ...state.variables, ...mergeWith.variables }; return newState; } const BUILTINS = new Map([ [`cd`, async ([target = os_1.homedir(), ...rest], opts, state) => { const resolvedTarget = fslib_1.ppath.resolve(state.cwd, fslib_1.npath.toPortablePath(target)); const stat = await opts.baseFs.statPromise(resolvedTarget); if (!stat.isDirectory()) { state.stderr.write(`cd: not a directory\n`); return 1; } else { state.cwd = resolvedTarget; return 0; } }], [`pwd`, async (args, opts, state) => { state.stdout.write(`${fslib_1.npath.fromPortablePath(state.cwd)}\n`); return 0; }], [`:`, async (args, opts, state) => { return 0; }], [`true`, async (args, opts, state) => { return 0; }], [`false`, async (args, opts, state) => { return 1; }], [`exit`, async ([code, ...rest], opts, state) => { return state.exitCode = parseInt(code !== null && code !== void 0 ? code : state.variables[`?`], 10); }], [`echo`, async (args, opts, state) => { state.stdout.write(`${args.join(` `)}\n`); return 0; }], [`__ysh_run_procedure`, async (args, opts, state) => { const procedure = state.procedures[args[0]]; const exitCode = await pipe_2.start(procedure, { stdin: new pipe_2.ProtectedStream(state.stdin), stdout: new pipe_2.ProtectedStream(state.stdout), stderr: new pipe_2.ProtectedStream(state.stderr), }).run(); return exitCode; }], [`__ysh_set_redirects`, async (args, opts, state) => { let stdin = state.stdin; let stdout = state.stdout; const stderr = state.stderr; const inputs = []; const outputs = []; let t = 0; while (args[t] !== `--`) { const type = args[t++]; const count = Number(args[t++]); const last = t + count; for (let u = t; u < last; ++t, ++u) { switch (type) { case `<`: { inputs.push(() => { return opts.baseFs.createReadStream(fslib_1.ppath.resolve(state.cwd, fslib_1.npath.toPortablePath(args[u]))); }); } break; case `<<<`: { inputs.push(() => { const input = new stream_1.PassThrough(); process.nextTick(() => { input.write(`${args[u]}\n`); input.end(); }); return input; }); } break; case `<&`: { inputs.push(() => getFileDescriptorStream(Number(args[u]), StreamType.Readable, state)); } break; case `>`: case `>>`: { const outputPath = fslib_1.ppath.resolve(state.cwd, fslib_1.npath.toPortablePath(args[u])); if (outputPath === `/dev/null`) { outputs.push(new stream_1.Writable({ autoDestroy: true, emitClose: true, write(chunk, encoding, callback) { setImmediate(callback); }, })); } else { outputs.push(opts.baseFs.createWriteStream(outputPath, type === `>>` ? { flags: `a` } : undefined)); } } break; case `>&`: { outputs.push(getFileDescriptorStream(Number(args[u]), StreamType.Writable, state)); } break; default: { throw new Error(`Assertion failed: Unsupported redirection type: "${type}"`); } } } } if (inputs.length > 0) { const pipe = new stream_1.PassThrough(); stdin = pipe; const bindInput = (n) => { if (n === inputs.length) { pipe.end(); } else { const input = inputs[n](); input.pipe(pipe, { end: false }); input.on(`end`, () => { bindInput(n + 1); }); } }; bindInput(0); } if (outputs.length > 0) { const pipe = new stream_1.PassThrough(); stdout = pipe; for (const output of outputs) { pipe.pipe(output); } } const exitCode = await pipe_2.start(makeCommandAction(args.slice(t + 1), opts, state), { stdin: new pipe_2.ProtectedStream(stdin), stdout: new pipe_2.ProtectedStream(stdout), stderr: new pipe_2.ProtectedStream(stderr), }).run(); // Close all the outputs (since the shell never closes the output stream) await Promise.all(outputs.map(output => { // Wait until the output got flushed to the disk return new Promise(resolve => { output.on(`close`, () => { resolve(); }); output.end(); }); })); return exitCode; }], ]); async function executeBufferedSubshell(ast, opts, state) { const chunks = []; const stdout = new stream_1.PassThrough(); stdout.on(`data`, chunk => chunks.push(chunk)); await executeShellLine(ast, opts, cloneState(state, { stdout })); return Buffer.concat(chunks).toString().replace(/[\r\n]+$/, ``); } async function applyEnvVariables(environmentSegments, opts, state) { const envPromises = environmentSegments.map(async (envSegment) => { const interpolatedArgs = await interpolateArguments(envSegment.args, opts, state); return { name: envSegment.name, value: interpolatedArgs.join(` `), }; }); const interpolatedEnvs = await Promise.all(envPromises); return interpolatedEnvs.reduce((envs, env) => { envs[env.name] = env.value; return envs; }, {}); } function split(raw) { return raw.match(/[^ \r\n\t]+/g) || []; } async function evaluateVariable(segment, opts, state, push, pushAndClose = push) { switch (segment.name) { case `$`: { push(String(process.pid)); } break; case `#`: { push(String(opts.args.length)); } break; case `@`: { if (segment.quoted) { for (const raw of opts.args) { pushAndClose(raw); } } else { for (const raw of opts.args) { const parts = split(raw); for (let t = 0; t < parts.length - 1; ++t) pushAndClose(parts[t]); push(parts[parts.length - 1]); } } } break; case `*`: { const raw = opts.args.join(` `); if (segment.quoted) { push(raw); } else { for (const part of split(raw)) { pushAndClose(part); } } } break; case `PPID`: { push(String(process.ppid)); } break; case `RANDOM`: { push(String(Math.floor(Math.random() * 32768))); } break; default: { const argIndex = parseInt(segment.name, 10); if (Number.isFinite(argIndex)) { if (argIndex >= 0 && argIndex < opts.args.length) { push(opts.args[argIndex]); } else if (segment.defaultValue) { push((await interpolateArguments(segment.defaultValue, opts, state)).join(` `)); } else { throw new errors_1.ShellError(`Unbound argument #${argIndex}`); } } else { if (Object.prototype.hasOwnProperty.call(state.variables, segment.name)) { push(state.variables[segment.name]); } else if (Object.prototype.hasOwnProperty.call(state.environment, segment.name)) { push(state.environment[segment.name]); } else if (segment.defaultValue) { push((await interpolateArguments(segment.defaultValue, opts, state)).join(` `)); } else { throw new errors_1.ShellError(`Unbound variable "${segment.name}"`); } } } break; } } const operators = { addition: (left, right) => left + right, subtraction: (left, right) => left - right, multiplication: (left, right) => left * right, division: (left, right) => Math.trunc(left / right), }; async function evaluateArithmetic(arithmetic, opts, state) { if (arithmetic.type === `number`) { if (!Number.isInteger(arithmetic.value)) { // ZSH allows non-integers, while bash throws at the parser level (unrecoverable) throw new Error(`Invalid number: "${arithmetic.value}", only integers are allowed`); } else { return arithmetic.value; } } else if (arithmetic.type === `variable`) { const parts = []; await evaluateVariable({ ...arithmetic, quoted: true }, opts, state, result => parts.push(result)); const number = Number(parts.join(` `)); if (Number.isNaN(number)) { return evaluateArithmetic({ type: `variable`, name: parts.join(` `) }, opts, state); } else { return evaluateArithmetic({ type: `number`, value: number }, opts, state); } } else { return operators[arithmetic.type](await evaluateArithmetic(arithmetic.left, opts, state), await evaluateArithmetic(arithmetic.right, opts, state)); } } async function interpolateArguments(commandArgs, opts, state) { const redirections = new Map(); const interpolated = []; let interpolatedSegments = []; const push = (segment) => { interpolatedSegments.push(segment); }; const close = () => { if (interpolatedSegments.length > 0) interpolated.push(interpolatedSegments.join(``)); interpolatedSegments = []; }; const pushAndClose = (segment) => { push(segment); close(); }; const redirect = (type, target) => { let targets = redirections.get(type); if (typeof targets === `undefined`) redirections.set(type, targets = []); targets.push(target); }; for (const commandArg of commandArgs) { let isGlob = false; switch (commandArg.type) { case `redirection`: { const interpolatedArgs = await interpolateArguments(commandArg.args, opts, state); for (const interpolatedArg of interpolatedArgs) { redirect(commandArg.subtype, interpolatedArg); } } break; case `argument`: { for (const segment of commandArg.segments) { switch (segment.type) { case `text`: { push(segment.text); } break; case `glob`: { push(segment.pattern); isGlob = true; } break; case `shell`: { const raw = await executeBufferedSubshell(segment.shell, opts, state); if (segment.quoted) { push(raw); } else { const parts = split(raw); for (let t = 0; t < parts.length - 1; ++t) pushAndClose(parts[t]); push(parts[parts.length - 1]); } } break; case `variable`: { await evaluateVariable(segment, opts, state, push, pushAndClose); } break; case `arithmetic`: { push(String(await evaluateArithmetic(segment.arithmetic, opts, state))); } break; } } } break; } close(); if (isGlob) { const pattern = interpolated.pop(); if (typeof pattern === `undefined`) throw new Error(`Assertion failed: Expected a glob pattern to have been set`); const matches = await opts.glob.match(pattern, { cwd: state.cwd, baseFs: opts.baseFs }); if (matches.length === 0) { const braceExpansionNotice = globUtils.isBraceExpansion(pattern) ? `. Note: Brace expansion of arbitrary strings isn't currently supported. For more details, please read this issue: https://github.com/yarnpkg/berry/issues/22` : ``; throw new errors_1.ShellError(`No matches found: "${pattern}"${braceExpansionNotice}`); } for (const match of matches.sort()) { pushAndClose(match); } } } if (redirections.size > 0) { const redirectionArgs = []; for (const [subtype, targets] of redirections.entries()) redirectionArgs.splice(redirectionArgs.length, 0, subtype, String(targets.length), ...targets); interpolated.splice(0, 0, `__ysh_set_redirects`, ...redirectionArgs, `--`); } return interpolated; } /** * Executes a command chain. A command chain is a list of commands linked * together thanks to the use of either of the `|` or `|&` operators: * * $ cat hello | grep world | grep -v foobar */ function makeCommandAction(args, opts, state) { if (!opts.builtins.has(args[0])) args = [`command`, ...args]; const nativeCwd = fslib_1.npath.fromPortablePath(state.cwd); let env = state.environment; if (typeof env.PWD !== `undefined`) env = { ...env, PWD: nativeCwd }; const [name, ...rest] = args; if (name === `command`) { return pipe_1.makeProcess(rest[0], rest.slice(1), opts, { cwd: nativeCwd, env, }); } const builtin = opts.builtins.get(name); if (typeof builtin === `undefined`) throw new Error(`Assertion failed: A builtin should exist for "${name}"`); return pipe_1.makeBuiltin(async ({ stdin, stdout, stderr }) => { state.stdin = stdin; state.stdout = stdout; state.stderr = stderr; return await builtin(rest, opts, state); }); } function makeSubshellAction(ast, opts, state) { return (stdio) => { const stdin = new stream_1.PassThrough(); const promise = executeShellLine(ast, opts, cloneState(state, { stdin })); return { stdin, promise }; }; } function makeGroupAction(ast, opts, state) { return (stdio) => { const stdin = new stream_1.PassThrough(); const promise = executeShellLine(ast, opts, state); return { stdin, promise }; }; } function makeActionFromProcedure(procedure, args, opts, activeState) { if (args.length === 0) { return procedure; } else { let key; do { key = String(Math.random()); } while (Object.prototype.hasOwnProperty.call(activeState.procedures, key)); activeState.procedures = { ...activeState.procedures }; activeState.procedures[key] = procedure; return makeCommandAction([...args, `__ysh_run_procedure`, key], opts, activeState); } } async function executeCommandChain(node, opts, state) { let current = node; let pipeType = null; let execution = null; while (current) { // Only the final segment is allowed to modify the shell state; all the // other ones are isolated const activeState = current.then ? { ...state } : state; let action; switch (current.type) { case `command`: { const args = await interpolateArguments(current.args, opts, state); const environment = await applyEnvVariables(current.envs, opts, state); action = current.envs.length ? makeCommandAction(args, opts, cloneState(activeState, { environment })) : makeCommandAction(args, opts, activeState); } break; case `subshell`: { const args = await interpolateArguments(current.args, opts, state); // We don't interpolate the subshell because it will be recursively // interpolated within its own context const procedure = makeSubshellAction(current.subshell, opts, activeState); action = makeActionFromProcedure(procedure, args, opts, activeState); } break; case `group`: { const args = await interpolateArguments(current.args, opts, state); const procedure = makeGroupAction(current.group, opts, activeState); action = makeActionFromProcedure(procedure, args, opts, activeState); } break; case `envs`: { const environment = await applyEnvVariables(current.envs, opts, state); activeState.environment = { ...activeState.environment, ...environment }; action = makeCommandAction([`true`], opts, activeState); } break; } if (typeof action === `undefined`) throw new Error(`Assertion failed: An action should have been generated`); if (pipeType === null) { // If we're processing the left-most segment of the command, we start a // new execution pipeline execution = pipe_2.start(action, { stdin: new pipe_2.ProtectedStream(activeState.stdin), stdout: new pipe_2.ProtectedStream(activeState.stdout), stderr: new pipe_2.ProtectedStream(activeState.stderr), }); } else { if (execution === null) throw new Error(`Assertion failed: The execution pipeline should have been setup`); // Otherwise, depending on the exaxct pipe type, we either pipe stdout // only or stdout and stderr switch (pipeType) { case `|`: { execution = execution.pipeTo(action, pipe_2.Pipe.STDOUT); } break; case `|&`: { execution = execution.pipeTo(action, pipe_2.Pipe.STDOUT | pipe_2.Pipe.STDERR); } break; } } if (current.then) { pipeType = current.then.type; current = current.then.chain; } else { current = null; } } if (execution === null) throw new Error(`Assertion failed: The execution pipeline should have been setup`); return await execution.run(); } /** * Execute a command line. A command line is a list of command shells linked * together thanks to the use of either of the `||` or `&&` operators. */ async function executeCommandLine(node, opts, state) { let code; const setCode = (newCode) => { code = newCode; // We must update $?, which always contains the exit code from // the right-most command state.variables[`?`] = String(newCode); }; const executeChain = async (chain) => { try { return await executeCommandChain(chain, opts, state); } catch (error) { if (!(error instanceof errors_1.ShellError)) throw error; state.stderr.write(`${error.message}\n`); return 1; } }; setCode(await executeChain(node.chain)); // We use a loop because we must make sure that we respect // the left associativity of lists, as per the bash spec. // (e.g. `inexistent && echo yes || echo no` must be // the same as `{inexistent && echo yes} || echo no`) while (node.then) { // If the execution aborted (usually through "exit"), we must bailout if (state.exitCode !== null) return state.exitCode; switch (node.then.type) { case `&&`: { if (code === 0) { setCode(await executeChain(node.then.line.chain)); } } break; case `||`: { if (code !== 0) { setCode(await executeChain(node.then.line.chain)); } } break; default: { throw new Error(`Assertion failed: Unsupported command type: "${node.then.type}"`); } break; } node = node.then.line; } return code; } async function executeShellLine(node, opts, state) { let rightMostExitCode = 0; for (const command of node) { rightMostExitCode = await executeCommandLine(command, opts, state); // If the execution aborted (usually through "exit"), we must bailout if (state.exitCode !== null) return state.exitCode; // We must update $?, which always contains the exit code from // the right-most command state.variables[`?`] = String(rightMostExitCode); } return rightMostExitCode; } function locateArgsVariableInSegment(segment) { switch (segment.type) { case `variable`: { return segment.name === `@` || segment.name === `#` || segment.name === `*` || Number.isFinite(parseInt(segment.name, 10)) || (`defaultValue` in segment && !!segment.defaultValue && segment.defaultValue.some(arg => locateArgsVariableInArgument(arg))); } break; case `arithmetic`: { return locateArgsVariableInArithmetic(segment.arithmetic); } break; case `shell`: { return locateArgsVariable(segment.shell); } break; default: { return false; } break; } } function locateArgsVariableInArgument(arg) { switch (arg.type) { case `redirection`: { return arg.args.some(arg => locateArgsVariableInArgument(arg)); } break; case `argument`: { return arg.segments.some(segment => locateArgsVariableInSegment(segment)); } break; default: throw new Error(`Assertion failed: Unsupported argument type: "${arg.type}"`); } } function locateArgsVariableInArithmetic(arg) { switch (arg.type) { case `variable`: { return locateArgsVariableInSegment(arg); } break; case `number`: { return false; } break; default: return locateArgsVariableInArithmetic(arg.left) || locateArgsVariableInArithmetic(arg.right); } } function locateArgsVariable(node) { return node.some(command => { while (command) { let chain = command.chain; while (chain) { let hasArgs; switch (chain.type) { case `subshell`: { hasArgs = locateArgsVariable(chain.subshell); } break; case `command`: { hasArgs = chain.envs.some(env => env.args.some(arg => { return locateArgsVariableInArgument(arg); })) || chain.args.some(arg => { return locateArgsVariableInArgument(arg); }); } break; } if (hasArgs) return true; if (!chain.then) break; chain = chain.then.chain; } if (!command.then) break; command = command.then.line; } return false; }); } async function execute(command, args = [], { baseFs = new fslib_1.NodeFS(), builtins = {}, cwd = fslib_1.npath.toPortablePath(process.cwd()), env = process.env, stdin = process.stdin, stdout = process.stdout, stderr = process.stderr, variables = {}, glob = globUtils, } = {}) { const normalizedEnv = {}; for (const [key, value] of Object.entries(env)) if (typeof value !== `undefined`) normalizedEnv[key] = value; const normalizedBuiltins = new Map(BUILTINS); for (const [key, builtin] of Object.entries(builtins)) normalizedBuiltins.set(key, builtin); // This is meant to be the equivalent of /dev/null if (stdin === null) { stdin = new stream_1.PassThrough(); stdin.end(); } const ast = parsers_1.parseShell(command, glob); // If the shell line doesn't use the args, inject it at the end of the // right-most command if (!locateArgsVariable(ast) && ast.length > 0 && args.length > 0) { let command = ast[ast.length - 1]; while (command.then) command = command.then.line; let chain = command.chain; while (chain.then) chain = chain.then.chain; if (chain.type === `command`) { chain.args = chain.args.concat(args.map(arg => { return { type: `argument`, segments: [{ type: `text`, text: arg, }], }; })); } } return await executeShellLine(ast, { args, baseFs, builtins: normalizedBuiltins, initialStdin: stdin, initialStdout: stdout, initialStderr: stderr, glob, }, { cwd, environment: normalizedEnv, exitCode: null, procedures: {}, stdin, stdout, stderr, variables: Object.assign({}, variables, { [`?`]: 0, }), }); } exports.execute = execute; /***/ }), /***/ 74253: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.start = exports.Handle = exports.ProtectedStream = exports.makeBuiltin = exports.makeProcess = exports.Pipe = void 0; const tslib_1 = __webpack_require__(70655); const cross_spawn_1 = tslib_1.__importDefault(__webpack_require__(13238)); const stream_1 = __webpack_require__(12781); var Pipe; (function (Pipe) { Pipe[Pipe["STDIN"] = 0] = "STDIN"; Pipe[Pipe["STDOUT"] = 1] = "STDOUT"; Pipe[Pipe["STDERR"] = 2] = "STDERR"; })(Pipe = exports.Pipe || (exports.Pipe = {})); function sigintHandler() { // We don't want SIGINT to kill our process; we want it to kill the // innermost process, whose end will cause our own to exit. } // Rather than attaching one SIGINT handler for each process, we // attach a single one and use a refcount to detect once it's no // longer needed. let sigintRefCount = 0; function makeProcess(name, args, opts, spawnOpts) { return (stdio) => { const stdin = stdio[0] instanceof stream_1.Transform ? `pipe` : stdio[0]; const stdout = stdio[1] instanceof stream_1.Transform ? `pipe` : stdio[1]; const stderr = stdio[2] instanceof stream_1.Transform ? `pipe` : stdio[2]; const child = cross_spawn_1.default(name, args, { ...spawnOpts, stdio: [ stdin, stdout, stderr, ] }); if (sigintRefCount++ === 0) process.on(`SIGINT`, sigintHandler); if (stdio[0] instanceof stream_1.Transform) stdio[0].pipe(child.stdin); if (stdio[1] instanceof stream_1.Transform) child.stdout.pipe(stdio[1], { end: false }); if (stdio[2] instanceof stream_1.Transform) child.stderr.pipe(stdio[2], { end: false }); return { stdin: child.stdin, promise: new Promise(resolve => { child.on(`error`, error => { if (--sigintRefCount === 0) process.off(`SIGINT`, sigintHandler); // @ts-expect-error switch (error.code) { case `ENOENT`: { stdio[2].write(`command not found: ${name}\n`); resolve(127); } break; case `EACCES`: { stdio[2].write(`permission denied: ${name}\n`); resolve(128); } break; default: { stdio[2].write(`uncaught error: ${error.message}\n`); resolve(1); } break; } }); child.on(`exit`, code => { if (--sigintRefCount === 0) process.off(`SIGINT`, sigintHandler); if (code !== null) { resolve(code); } else { resolve(129); } }); }), }; }; } exports.makeProcess = makeProcess; function makeBuiltin(builtin) { return (stdio) => { const stdin = stdio[0] === `pipe` ? new stream_1.PassThrough() : stdio[0]; return { stdin, promise: Promise.resolve().then(() => builtin({ stdin, stdout: stdio[1], stderr: stdio[2], })), }; }; } exports.makeBuiltin = makeBuiltin; class ProtectedStream { constructor(stream) { this.stream = stream; } close() { // Ignore close request } get() { return this.stream; } } exports.ProtectedStream = ProtectedStream; class PipeStream { constructor() { this.stream = null; } close() { if (this.stream === null) { throw new Error(`Assertion failed: No stream attached`); } else { this.stream.end(); } } attach(stream) { this.stream = stream; } get() { if (this.stream === null) { throw new Error(`Assertion failed: No stream attached`); } else { return this.stream; } } } class Handle { constructor(ancestor, implementation) { this.stdin = null; this.stdout = null; this.stderr = null; this.pipe = null; this.ancestor = ancestor; this.implementation = implementation; } static start(implementation, { stdin, stdout, stderr }) { const chain = new Handle(null, implementation); chain.stdin = stdin; chain.stdout = stdout; chain.stderr = stderr; return chain; } pipeTo(implementation, source = Pipe.STDOUT) { const next = new Handle(this, implementation); const pipe = new PipeStream(); next.pipe = pipe; next.stdout = this.stdout; next.stderr = this.stderr; if ((source & Pipe.STDOUT) === Pipe.STDOUT) this.stdout = pipe; else if (this.ancestor !== null) this.stderr = this.ancestor.stdout; if ((source & Pipe.STDERR) === Pipe.STDERR) this.stderr = pipe; else if (this.ancestor !== null) this.stderr = this.ancestor.stderr; return next; } async exec() { const stdio = [ `ignore`, `ignore`, `ignore`, ]; if (this.pipe) { stdio[0] = `pipe`; } else { if (this.stdin === null) { throw new Error(`Assertion failed: No input stream registered`); } else { stdio[0] = this.stdin.get(); } } let stdoutLock; if (this.stdout === null) { throw new Error(`Assertion failed: No output stream registered`); } else { stdoutLock = this.stdout; stdio[1] = stdoutLock.get(); } let stderrLock; if (this.stderr === null) { throw new Error(`Assertion failed: No error stream registered`); } else { stderrLock = this.stderr; stdio[2] = stderrLock.get(); } const child = this.implementation(stdio); if (this.pipe) this.pipe.attach(child.stdin); return await child.promise.then(code => { stdoutLock.close(); stderrLock.close(); return code; }); } async run() { const promises = []; for (let handle = this; handle; handle = handle.ancestor) promises.push(handle.exec()); const exitCodes = await Promise.all(promises); return exitCodes[0]; } } exports.Handle = Handle; function start(p, opts) { return Handle.start(p, opts); } exports.start = start; /***/ }), /***/ 13238: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const cp = __webpack_require__(32081); const parse = __webpack_require__(63458); const enoent = __webpack_require__(79546); function spawn(command, args, options) { // Parse the arguments const parsed = parse(command, args, options); // Spawn the child process const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); // Hook into child process "exit" event to emit an error if the command // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 enoent.hookChildProcess(spawned, parsed); return spawned; } function spawnSync(command, args, options) { // Parse the arguments const parsed = parse(command, args, options); // Spawn the child process const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); return result; } module.exports = spawn; module.exports.spawn = spawn; module.exports.sync = spawnSync; module.exports._parse = parse; module.exports._enoent = enoent; /***/ }), /***/ 79546: /***/ ((module) => { "use strict"; const isWin = process.platform === 'win32'; function notFoundError(original, syscall) { return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { code: 'ENOENT', errno: 'ENOENT', syscall: `${syscall} ${original.command}`, path: original.command, spawnargs: original.args, }); } function hookChildProcess(cp, parsed) { if (!isWin) { return; } const originalEmit = cp.emit; cp.emit = function (name, arg1) { // If emitting "exit" event and exit code is 1, we need to check if // the command exists and emit an "error" instead // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 if (name === 'exit') { const err = verifyENOENT(arg1, parsed); if (err) { return originalEmit.call(cp, 'error', err); } } return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params }; } function verifyENOENT(status, parsed) { if (isWin && status === 1 && !parsed.file) { return notFoundError(parsed.original, 'spawn'); } return null; } function verifyENOENTSync(status, parsed) { if (isWin && status === 1 && !parsed.file) { return notFoundError(parsed.original, 'spawnSync'); } return null; } module.exports = { hookChildProcess, verifyENOENT, verifyENOENTSync, notFoundError, }; /***/ }), /***/ 63458: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const path = __webpack_require__(71017); const resolveCommand = __webpack_require__(56323); const escape = __webpack_require__(12791); const readShebang = __webpack_require__(93366); const isWin = process.platform === 'win32'; const isExecutableRegExp = /\.(?:com|exe)$/i; const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; function detectShebang(parsed) { parsed.file = resolveCommand(parsed); const shebang = parsed.file && readShebang(parsed.file); if (shebang) { parsed.args.unshift(parsed.file); parsed.command = shebang; return resolveCommand(parsed); } return parsed.file; } function parseNonShell(parsed) { if (!isWin) { return parsed; } // Detect & add support for shebangs const commandFile = detectShebang(parsed); // We don't need a shell if the command filename is an executable const needsShell = !isExecutableRegExp.test(commandFile); // If a shell is required, use cmd.exe and take care of escaping everything correctly // Note that `forceShell` is an hidden option used only in tests if (parsed.options.forceShell || needsShell) { // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, // we need to double escape them const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) // This is necessary otherwise it will always fail with ENOENT in those cases parsed.command = path.normalize(parsed.command); // Escape command & arguments parsed.command = escape.command(parsed.command); parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars)); const shellCommand = [parsed.command].concat(parsed.args).join(' '); parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; parsed.command = process.env.comspec || 'cmd.exe'; parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped } return parsed; } function parse(command, args, options) { // Normalize arguments, similar to nodejs if (args && !Array.isArray(args)) { options = args; args = null; } args = args ? args.slice(0) : []; // Clone array to avoid changing the original options = Object.assign({}, options); // Clone object to avoid changing the original // Build our parsed object const parsed = { command, args, options, file: undefined, original: { command, args, }, }; // Delegate further parsing to shell or non-shell return options.shell ? parsed : parseNonShell(parsed); } module.exports = parse; /***/ }), /***/ 12791: /***/ ((module) => { "use strict"; // See http://www.robvanderwoude.com/escapechars.php const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; function escapeCommand(arg) { // Escape meta chars arg = arg.replace(metaCharsRegExp, '^$1'); return arg; } function escapeArgument(arg, doubleEscapeMetaChars) { // Convert to string arg = `${arg}`; // Algorithm below is based on https://qntm.org/cmd // It's slightly altered to disable JS backtracking to avoid hanging on specially crafted input // Please see https://github.com/moxystudio/node-cross-spawn/pull/160 for more information // Sequence of backslashes followed by a double quote: // double up all the backslashes and escape the double quote arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"'); // Sequence of backslashes followed by the end of the string // (which will become a double quote later): // double up all the backslashes arg = arg.replace(/(?=(\\+?)?)\1$/, '$1$1'); // All other backslashes occur literally // Quote the whole thing: arg = `"${arg}"`; // Escape meta chars arg = arg.replace(metaCharsRegExp, '^$1'); // Double escape meta chars if necessary if (doubleEscapeMetaChars) { arg = arg.replace(metaCharsRegExp, '^$1'); } return arg; } module.exports.command = escapeCommand; module.exports.argument = escapeArgument; /***/ }), /***/ 93366: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const fs = __webpack_require__(57147); const shebangCommand = __webpack_require__(81674); function readShebang(command) { // Read the first 150 bytes from the file const size = 150; const buffer = Buffer.alloc(size); let fd; try { fd = fs.openSync(command, 'r'); fs.readSync(fd, buffer, 0, size, 0); fs.closeSync(fd); } catch (e) { /* Empty */ } // Attempt to extract shebang (null is returned if not a shebang) return shebangCommand(buffer.toString()); } module.exports = readShebang; /***/ }), /***/ 56323: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const path = __webpack_require__(71017); const which = __webpack_require__(36702); const getPathKey = __webpack_require__(15867); function resolveCommandAttempt(parsed, withoutPathExt) { const env = parsed.options.env || process.env; const cwd = process.cwd(); const hasCustomCwd = parsed.options.cwd != null; // Worker threads do not have process.chdir() const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled; // If a custom `cwd` was specified, we need to change the process cwd // because `which` will do stat calls but does not support a custom cwd if (shouldSwitchCwd) { try { process.chdir(parsed.options.cwd); } catch (err) { /* Empty */ } } let resolved; try { resolved = which.sync(parsed.command, { path: env[getPathKey({ env })], pathExt: withoutPathExt ? path.delimiter : undefined, }); } catch (e) { /* Empty */ } finally { if (shouldSwitchCwd) { process.chdir(cwd); } } // If we successfully resolved, ensure that an absolute path is returned // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it if (resolved) { resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); } return resolved; } function resolveCommand(parsed) { return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); } module.exports = resolveCommand; /***/ }), /***/ 15867: /***/ ((module) => { "use strict"; const pathKey = (options = {}) => { const environment = options.env || process.env; const platform = options.platform || process.platform; if (platform !== 'win32') { return 'PATH'; } return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; }; module.exports = pathKey; // TODO: Remove this for the next major release module.exports["default"] = pathKey; /***/ }), /***/ 81674: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const shebangRegex = __webpack_require__(98645); module.exports = (string = '') => { const match = string.match(shebangRegex); if (!match) { return null; } const [path, argument] = match[0].replace(/#! ?/, '').split(' '); const binary = path.split('/').pop(); if (binary === 'env') { return argument; } return argument ? `${binary} ${argument}` : binary; }; /***/ }), /***/ 98645: /***/ ((module) => { "use strict"; module.exports = /^#!(.*)/; /***/ }), /***/ 36702: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const isWindows = process.platform === 'win32' || process.env.OSTYPE === 'cygwin' || process.env.OSTYPE === 'msys' const path = __webpack_require__(71017) const COLON = isWindows ? ';' : ':' const isexe = __webpack_require__(31959) const getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }) const getPathInfo = (cmd, opt) => { const colon = opt.colon || COLON // If it has a slash, then we don't bother searching the pathenv. // just check the file itself, and that's it. const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] : ( [ // windows always checks the cwd first ...(isWindows ? [process.cwd()] : []), ...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */ '').split(colon), ] ) const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' : '' const pathExt = isWindows ? pathExtExe.split(colon) : [''] if (isWindows) { if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') pathExt.unshift('') } return { pathEnv, pathExt, pathExtExe, } } const which = (cmd, opt, cb) => { if (typeof opt === 'function') { cb = opt opt = {} } if (!opt) opt = {} const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) const found = [] const step = i => new Promise((resolve, reject) => { if (i === pathEnv.length) return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd)) const ppRaw = pathEnv[i] const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw const pCmd = path.join(pathPart, cmd) const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd resolve(subStep(p, i, 0)) }) const subStep = (p, i, ii) => new Promise((resolve, reject) => { if (ii === pathExt.length) return resolve(step(i + 1)) const ext = pathExt[ii] isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { if (!er && is) { if (opt.all) found.push(p + ext) else return resolve(p + ext) } return resolve(subStep(p, i, ii + 1)) }) }) return cb ? step(0).then(res => cb(null, res), cb) : step(0) } const whichSync = (cmd, opt) => { opt = opt || {} const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) const found = [] for (let i = 0; i < pathEnv.length; i ++) { const ppRaw = pathEnv[i] const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw const pCmd = path.join(pathPart, cmd) const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd for (let j = 0; j < pathExt.length; j ++) { const cur = p + pathExt[j] try { const is = isexe.sync(cur, { pathExt: pathExtExe }) if (is) { if (opt.all) found.push(cur) else return cur } } catch (ex) {} } } if (opt.all && found.length) return found if (opt.nothrow) return null throw getNotFoundError(cmd) } module.exports = which which.sync = whichSync /***/ }), /***/ 56455: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const indentString = __webpack_require__(95602); const cleanStack = __webpack_require__(75281); const cleanInternalStack = stack => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, ''); class AggregateError extends Error { constructor(errors) { if (!Array.isArray(errors)) { throw new TypeError(`Expected input to be an Array, got ${typeof errors}`); } errors = [...errors].map(error => { if (error instanceof Error) { return error; } if (error !== null && typeof error === 'object') { // Handle plain error objects with message property and/or possibly other metadata return Object.assign(new Error(error.message), error); } return new Error(error); }); let message = errors .map(error => { // The `stack` property is not standardized, so we can't assume it exists return typeof error.stack === 'string' ? cleanInternalStack(cleanStack(error.stack)) : String(error); }) .join('\n'); message = '\n' + indentString(message, 4); super(message); this.name = 'AggregateError'; Object.defineProperty(this, '_errors', {value: errors}); } * [Symbol.iterator]() { for (const error of this._errors) { yield error; } } } module.exports = AggregateError; /***/ }), /***/ 48811: /***/ ((module) => { "use strict"; // ColorCodes explained: http://www.termsys.demon.co.uk/vtansi.htm var colorNums = { white : 37 , black : 30 , blue : 34 , cyan : 36 , green : 32 , magenta : 35 , red : 31 , yellow : 33 , brightBlack : 90 , brightRed : 91 , brightGreen : 92 , brightYellow : 93 , brightBlue : 94 , brightMagenta : 95 , brightCyan : 96 , brightWhite : 97 } , backgroundColorNums = { bgBlack : 40 , bgRed : 41 , bgGreen : 42 , bgYellow : 43 , bgBlue : 44 , bgMagenta : 45 , bgCyan : 46 , bgWhite : 47 , bgBrightBlack : 100 , bgBrightRed : 101 , bgBrightGreen : 102 , bgBrightYellow : 103 , bgBrightBlue : 104 , bgBrightMagenta : 105 , bgBrightCyan : 106 , bgBrightWhite : 107 } , open = {} , close = {} , colors = {} ; Object.keys(colorNums).forEach(function (k) { var o = open[k] = '\u001b[' + colorNums[k] + 'm'; var c = close[k] = '\u001b[39m'; colors[k] = function (s) { return o + s + c; }; }); Object.keys(backgroundColorNums).forEach(function (k) { var o = open[k] = '\u001b[' + backgroundColorNums[k] + 'm'; var c = close[k] = '\u001b[49m'; colors[k] = function (s) { return o + s + c; }; }); module.exports = colors; colors.open = open; colors.close = close; /***/ }), /***/ 40261: /***/ ((module) => { "use strict"; const arrayDiffer = (array, ...values) => { const rest = new Set([].concat(...values)); return array.filter(element => !rest.has(element)); }; module.exports = arrayDiffer; /***/ }), /***/ 93755: /***/ ((module) => { "use strict"; module.exports = (...arguments_) => { return [...new Set([].concat(...arguments_))]; }; /***/ }), /***/ 50579: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var rawAsap = __webpack_require__(89134); var freeTasks = []; /** * Calls a task as soon as possible after returning, in its own event, with * priority over IO events. An exception thrown in a task can be handled by * `process.on("uncaughtException") or `domain.on("error")`, but will otherwise * crash the process. If the error is handled, all subsequent tasks will * resume. * * @param {{call}} task A callable object, typically a function that takes no * arguments. */ module.exports = asap; function asap(task) { var rawTask; if (freeTasks.length) { rawTask = freeTasks.pop(); } else { rawTask = new RawTask(); } rawTask.task = task; rawTask.domain = process.domain; rawAsap(rawTask); } function RawTask() { this.task = null; this.domain = null; } RawTask.prototype.call = function () { if (this.domain) { this.domain.enter(); } var threw = true; try { this.task.call(); threw = false; // If the task throws an exception (presumably) Node.js restores the // domain stack for the next event. if (this.domain) { this.domain.exit(); } } finally { // We use try/finally and a threw flag to avoid messing up stack traces // when we catch and release errors. if (threw) { // In Node.js, uncaught exceptions are considered fatal errors. // Re-throw them to interrupt flushing! // Ensure that flushing continues if an uncaught exception is // suppressed listening process.on("uncaughtException") or // domain.on("error"). rawAsap.requestFlush(); } // If the task threw an error, we do not want to exit the domain here. // Exiting the domain would prevent the domain from catching the error. this.task = null; this.domain = null; freeTasks.push(this); } }; /***/ }), /***/ 89134: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var domain; // The domain module is executed on demand var hasSetImmediate = typeof setImmediate === "function"; // Use the fastest means possible to execute a task in its own turn, with // priority over other events including network IO events in Node.js. // // An exception thrown by a task will permanently interrupt the processing of // subsequent tasks. The higher level `asap` function ensures that if an // exception is thrown by a task, that the task queue will continue flushing as // soon as possible, but if you use `rawAsap` directly, you are responsible to // either ensure that no exceptions are thrown from your task, or to manually // call `rawAsap.requestFlush` if an exception is thrown. module.exports = rawAsap; function rawAsap(task) { if (!queue.length) { requestFlush(); flushing = true; } // Avoids a function call queue[queue.length] = task; } var queue = []; // Once a flush has been requested, no further calls to `requestFlush` are // necessary until the next `flush` completes. var flushing = false; // The position of the next task to execute in the task queue. This is // preserved between calls to `flush` so that it can be resumed if // a task throws an exception. var index = 0; // If a task schedules additional tasks recursively, the task queue can grow // unbounded. To prevent memory excaustion, the task queue will periodically // truncate already-completed tasks. var capacity = 1024; // The flush function processes all tasks that have been scheduled with // `rawAsap` unless and until one of those tasks throws an exception. // If a task throws an exception, `flush` ensures that its state will remain // consistent and will resume where it left off when called again. // However, `flush` does not make any arrangements to be called again if an // exception is thrown. function flush() { while (index < queue.length) { var currentIndex = index; // Advance the index before calling the task. This ensures that we will // begin flushing on the next task the task throws an error. index = index + 1; queue[currentIndex].call(); // Prevent leaking memory for long chains of recursive calls to `asap`. // If we call `asap` within tasks scheduled by `asap`, the queue will // grow, but to avoid an O(n) walk for every task we execute, we don't // shift tasks off the queue after they have been executed. // Instead, we periodically shift 1024 tasks off the queue. if (index > capacity) { // Manually shift all values starting at the index back to the // beginning of the queue. for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) { queue[scan] = queue[scan + index]; } queue.length -= index; index = 0; } } queue.length = 0; index = 0; flushing = false; } rawAsap.requestFlush = requestFlush; function requestFlush() { // Ensure flushing is not bound to any domain. // It is not sufficient to exit the domain, because domains exist on a stack. // To execute code outside of any domain, the following dance is necessary. var parentDomain = process.domain; if (parentDomain) { if (!domain) { // Lazy execute the domain module. // Only employed if the user elects to use domains. domain = __webpack_require__(13639); } domain.active = process.domain = null; } // `setImmediate` is slower that `process.nextTick`, but `process.nextTick` // cannot handle recursion. // `requestFlush` will only be called recursively from `asap.js`, to resume // flushing after an error is thrown into a domain. // Conveniently, `setImmediate` was introduced in the same version // `process.nextTick` started throwing recursion errors. if (flushing && hasSetImmediate) { setImmediate(flush); } else { process.nextTick(flush); } if (parentDomain) { domain.active = process.domain = parentDomain; } } /***/ }), /***/ 83407: /***/ ((module) => { // Copyright 2011 Mark Cavage All rights reserved. module.exports = { newInvalidAsn1Error: function (msg) { var e = new Error(); e.name = 'InvalidAsn1Error'; e.message = msg || ''; return e; } }; /***/ }), /***/ 20279: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Copyright 2011 Mark Cavage All rights reserved. var errors = __webpack_require__(83407); var types = __webpack_require__(34478); var Reader = __webpack_require__(24578); var Writer = __webpack_require__(3609); // --- Exports module.exports = { Reader: Reader, Writer: Writer }; for (var t in types) { if (types.hasOwnProperty(t)) module.exports[t] = types[t]; } for (var e in errors) { if (errors.hasOwnProperty(e)) module.exports[e] = errors[e]; } /***/ }), /***/ 24578: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Copyright 2011 Mark Cavage All rights reserved. var assert = __webpack_require__(39491); var Buffer = __webpack_require__(2399).Buffer; var ASN1 = __webpack_require__(34478); var errors = __webpack_require__(83407); // --- Globals var newInvalidAsn1Error = errors.newInvalidAsn1Error; // --- API function Reader(data) { if (!data || !Buffer.isBuffer(data)) throw new TypeError('data must be a node Buffer'); this._buf = data; this._size = data.length; // These hold the "current" state this._len = 0; this._offset = 0; } Object.defineProperty(Reader.prototype, 'length', { enumerable: true, get: function () { return (this._len); } }); Object.defineProperty(Reader.prototype, 'offset', { enumerable: true, get: function () { return (this._offset); } }); Object.defineProperty(Reader.prototype, 'remain', { get: function () { return (this._size - this._offset); } }); Object.defineProperty(Reader.prototype, 'buffer', { get: function () { return (this._buf.slice(this._offset)); } }); /** * Reads a single byte and advances offset; you can pass in `true` to make this * a "peek" operation (i.e., get the byte, but don't advance the offset). * * @param {Boolean} peek true means don't move offset. * @return {Number} the next byte, null if not enough data. */ Reader.prototype.readByte = function (peek) { if (this._size - this._offset < 1) return null; var b = this._buf[this._offset] & 0xff; if (!peek) this._offset += 1; return b; }; Reader.prototype.peek = function () { return this.readByte(true); }; /** * Reads a (potentially) variable length off the BER buffer. This call is * not really meant to be called directly, as callers have to manipulate * the internal buffer afterwards. * * As a result of this call, you can call `Reader.length`, until the * next thing called that does a readLength. * * @return {Number} the amount of offset to advance the buffer. * @throws {InvalidAsn1Error} on bad ASN.1 */ Reader.prototype.readLength = function (offset) { if (offset === undefined) offset = this._offset; if (offset >= this._size) return null; var lenB = this._buf[offset++] & 0xff; if (lenB === null) return null; if ((lenB & 0x80) === 0x80) { lenB &= 0x7f; if (lenB === 0) throw newInvalidAsn1Error('Indefinite length not supported'); if (lenB > 4) throw newInvalidAsn1Error('encoding too long'); if (this._size - offset < lenB) return null; this._len = 0; for (var i = 0; i < lenB; i++) this._len = (this._len << 8) + (this._buf[offset++] & 0xff); } else { // Wasn't a variable length this._len = lenB; } return offset; }; /** * Parses the next sequence in this BER buffer. * * To get the length of the sequence, call `Reader.length`. * * @return {Number} the sequence's tag. */ Reader.prototype.readSequence = function (tag) { var seq = this.peek(); if (seq === null) return null; if (tag !== undefined && tag !== seq) throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + ': got 0x' + seq.toString(16)); var o = this.readLength(this._offset + 1); // stored in `length` if (o === null) return null; this._offset = o; return seq; }; Reader.prototype.readInt = function () { return this._readTag(ASN1.Integer); }; Reader.prototype.readBoolean = function () { return (this._readTag(ASN1.Boolean) === 0 ? false : true); }; Reader.prototype.readEnumeration = function () { return this._readTag(ASN1.Enumeration); }; Reader.prototype.readString = function (tag, retbuf) { if (!tag) tag = ASN1.OctetString; var b = this.peek(); if (b === null) return null; if (b !== tag) throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + ': got 0x' + b.toString(16)); var o = this.readLength(this._offset + 1); // stored in `length` if (o === null) return null; if (this.length > this._size - o) return null; this._offset = o; if (this.length === 0) return retbuf ? Buffer.alloc(0) : ''; var str = this._buf.slice(this._offset, this._offset + this.length); this._offset += this.length; return retbuf ? str : str.toString('utf8'); }; Reader.prototype.readOID = function (tag) { if (!tag) tag = ASN1.OID; var b = this.readString(tag, true); if (b === null) return null; var values = []; var value = 0; for (var i = 0; i < b.length; i++) { var byte = b[i] & 0xff; value <<= 7; value += byte & 0x7f; if ((byte & 0x80) === 0) { values.push(value); value = 0; } } value = values.shift(); values.unshift(value % 40); values.unshift((value / 40) >> 0); return values.join('.'); }; Reader.prototype._readTag = function (tag) { assert.ok(tag !== undefined); var b = this.peek(); if (b === null) return null; if (b !== tag) throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + ': got 0x' + b.toString(16)); var o = this.readLength(this._offset + 1); // stored in `length` if (o === null) return null; if (this.length > 4) throw newInvalidAsn1Error('Integer too long: ' + this.length); if (this.length > this._size - o) return null; this._offset = o; var fb = this._buf[this._offset]; var value = 0; for (var i = 0; i < this.length; i++) { value <<= 8; value |= (this._buf[this._offset++] & 0xff); } if ((fb & 0x80) === 0x80 && i !== 4) value -= (1 << (i * 8)); return value >> 0; }; // --- Exported API module.exports = Reader; /***/ }), /***/ 34478: /***/ ((module) => { // Copyright 2011 Mark Cavage All rights reserved. module.exports = { EOC: 0, Boolean: 1, Integer: 2, BitString: 3, OctetString: 4, Null: 5, OID: 6, ObjectDescriptor: 7, External: 8, Real: 9, // float Enumeration: 10, PDV: 11, Utf8String: 12, RelativeOID: 13, Sequence: 16, Set: 17, NumericString: 18, PrintableString: 19, T61String: 20, VideotexString: 21, IA5String: 22, UTCTime: 23, GeneralizedTime: 24, GraphicString: 25, VisibleString: 26, GeneralString: 28, UniversalString: 29, CharacterString: 30, BMPString: 31, Constructor: 32, Context: 128 }; /***/ }), /***/ 3609: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Copyright 2011 Mark Cavage All rights reserved. var assert = __webpack_require__(39491); var Buffer = __webpack_require__(2399).Buffer; var ASN1 = __webpack_require__(34478); var errors = __webpack_require__(83407); // --- Globals var newInvalidAsn1Error = errors.newInvalidAsn1Error; var DEFAULT_OPTS = { size: 1024, growthFactor: 8 }; // --- Helpers function merge(from, to) { assert.ok(from); assert.equal(typeof (from), 'object'); assert.ok(to); assert.equal(typeof (to), 'object'); var keys = Object.getOwnPropertyNames(from); keys.forEach(function (key) { if (to[key]) return; var value = Object.getOwnPropertyDescriptor(from, key); Object.defineProperty(to, key, value); }); return to; } // --- API function Writer(options) { options = merge(DEFAULT_OPTS, options || {}); this._buf = Buffer.alloc(options.size || 1024); this._size = this._buf.length; this._offset = 0; this._options = options; // A list of offsets in the buffer where we need to insert // sequence tag/len pairs. this._seq = []; } Object.defineProperty(Writer.prototype, 'buffer', { get: function () { if (this._seq.length) throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)'); return (this._buf.slice(0, this._offset)); } }); Writer.prototype.writeByte = function (b) { if (typeof (b) !== 'number') throw new TypeError('argument must be a Number'); this._ensure(1); this._buf[this._offset++] = b; }; Writer.prototype.writeInt = function (i, tag) { if (typeof (i) !== 'number') throw new TypeError('argument must be a Number'); if (typeof (tag) !== 'number') tag = ASN1.Integer; var sz = 4; while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) && (sz > 1)) { sz--; i <<= 8; } if (sz > 4) throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff'); this._ensure(2 + sz); this._buf[this._offset++] = tag; this._buf[this._offset++] = sz; while (sz-- > 0) { this._buf[this._offset++] = ((i & 0xff000000) >>> 24); i <<= 8; } }; Writer.prototype.writeNull = function () { this.writeByte(ASN1.Null); this.writeByte(0x00); }; Writer.prototype.writeEnumeration = function (i, tag) { if (typeof (i) !== 'number') throw new TypeError('argument must be a Number'); if (typeof (tag) !== 'number') tag = ASN1.Enumeration; return this.writeInt(i, tag); }; Writer.prototype.writeBoolean = function (b, tag) { if (typeof (b) !== 'boolean') throw new TypeError('argument must be a Boolean'); if (typeof (tag) !== 'number') tag = ASN1.Boolean; this._ensure(3); this._buf[this._offset++] = tag; this._buf[this._offset++] = 0x01; this._buf[this._offset++] = b ? 0xff : 0x00; }; Writer.prototype.writeString = function (s, tag) { if (typeof (s) !== 'string') throw new TypeError('argument must be a string (was: ' + typeof (s) + ')'); if (typeof (tag) !== 'number') tag = ASN1.OctetString; var len = Buffer.byteLength(s); this.writeByte(tag); this.writeLength(len); if (len) { this._ensure(len); this._buf.write(s, this._offset); this._offset += len; } }; Writer.prototype.writeBuffer = function (buf, tag) { if (typeof (tag) !== 'number') throw new TypeError('tag must be a number'); if (!Buffer.isBuffer(buf)) throw new TypeError('argument must be a buffer'); this.writeByte(tag); this.writeLength(buf.length); this._ensure(buf.length); buf.copy(this._buf, this._offset, 0, buf.length); this._offset += buf.length; }; Writer.prototype.writeStringArray = function (strings) { if ((!strings instanceof Array)) throw new TypeError('argument must be an Array[String]'); var self = this; strings.forEach(function (s) { self.writeString(s); }); }; // This is really to solve DER cases, but whatever for now Writer.prototype.writeOID = function (s, tag) { if (typeof (s) !== 'string') throw new TypeError('argument must be a string'); if (typeof (tag) !== 'number') tag = ASN1.OID; if (!/^([0-9]+\.){3,}[0-9]+$/.test(s)) throw new Error('argument is not a valid OID string'); function encodeOctet(bytes, octet) { if (octet < 128) { bytes.push(octet); } else if (octet < 16384) { bytes.push((octet >>> 7) | 0x80); bytes.push(octet & 0x7F); } else if (octet < 2097152) { bytes.push((octet >>> 14) | 0x80); bytes.push(((octet >>> 7) | 0x80) & 0xFF); bytes.push(octet & 0x7F); } else if (octet < 268435456) { bytes.push((octet >>> 21) | 0x80); bytes.push(((octet >>> 14) | 0x80) & 0xFF); bytes.push(((octet >>> 7) | 0x80) & 0xFF); bytes.push(octet & 0x7F); } else { bytes.push(((octet >>> 28) | 0x80) & 0xFF); bytes.push(((octet >>> 21) | 0x80) & 0xFF); bytes.push(((octet >>> 14) | 0x80) & 0xFF); bytes.push(((octet >>> 7) | 0x80) & 0xFF); bytes.push(octet & 0x7F); } } var tmp = s.split('.'); var bytes = []; bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10)); tmp.slice(2).forEach(function (b) { encodeOctet(bytes, parseInt(b, 10)); }); var self = this; this._ensure(2 + bytes.length); this.writeByte(tag); this.writeLength(bytes.length); bytes.forEach(function (b) { self.writeByte(b); }); }; Writer.prototype.writeLength = function (len) { if (typeof (len) !== 'number') throw new TypeError('argument must be a Number'); this._ensure(4); if (len <= 0x7f) { this._buf[this._offset++] = len; } else if (len <= 0xff) { this._buf[this._offset++] = 0x81; this._buf[this._offset++] = len; } else if (len <= 0xffff) { this._buf[this._offset++] = 0x82; this._buf[this._offset++] = len >> 8; this._buf[this._offset++] = len; } else if (len <= 0xffffff) { this._buf[this._offset++] = 0x83; this._buf[this._offset++] = len >> 16; this._buf[this._offset++] = len >> 8; this._buf[this._offset++] = len; } else { throw newInvalidAsn1Error('Length too long (> 4 bytes)'); } }; Writer.prototype.startSequence = function (tag) { if (typeof (tag) !== 'number') tag = ASN1.Sequence | ASN1.Constructor; this.writeByte(tag); this._seq.push(this._offset); this._ensure(3); this._offset += 3; }; Writer.prototype.endSequence = function () { var seq = this._seq.pop(); var start = seq + 3; var len = this._offset - start; if (len <= 0x7f) { this._shift(start, len, -2); this._buf[seq] = len; } else if (len <= 0xff) { this._shift(start, len, -1); this._buf[seq] = 0x81; this._buf[seq + 1] = len; } else if (len <= 0xffff) { this._buf[seq] = 0x82; this._buf[seq + 1] = len >> 8; this._buf[seq + 2] = len; } else if (len <= 0xffffff) { this._shift(start, len, 1); this._buf[seq] = 0x83; this._buf[seq + 1] = len >> 16; this._buf[seq + 2] = len >> 8; this._buf[seq + 3] = len; } else { throw newInvalidAsn1Error('Sequence too long'); } }; Writer.prototype._shift = function (start, len, shift) { assert.ok(start !== undefined); assert.ok(len !== undefined); assert.ok(shift); this._buf.copy(this._buf, start + shift, start, start + len); this._offset += shift; }; Writer.prototype._ensure = function (len) { assert.ok(len); if (this._size - this._offset < len) { var sz = this._size * this._options.growthFactor; if (sz - this._offset < len) sz += len; var buf = Buffer.alloc(sz); this._buf.copy(buf, 0, 0, this._offset); this._buf = buf; this._size = sz; } }; // --- Exported API module.exports = Writer; /***/ }), /***/ 90476: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Copyright 2011 Mark Cavage All rights reserved. // If you have no idea what ASN.1 or BER is, see this: // ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc var Ber = __webpack_require__(20279); // --- Exported API module.exports = { Ber: Ber, BerReader: Ber.Reader, BerWriter: Ber.Writer }; /***/ }), /***/ 85792: /***/ ((module) => { function isBuffer (value) { return Buffer.isBuffer(value) || value instanceof Uint8Array } function isEncoding (encoding) { return Buffer.isEncoding(encoding) } function alloc (size, fill, encoding) { return Buffer.alloc(size, fill, encoding) } function allocUnsafe (size) { return Buffer.allocUnsafe(size) } function allocUnsafeSlow (size) { return Buffer.allocUnsafeSlow(size) } function byteLength (string, encoding) { return Buffer.byteLength(string, encoding) } function compare (a, b) { return Buffer.compare(a, b) } function concat (buffers, totalLength) { return Buffer.concat(buffers, totalLength) } function copy (source, target, targetStart, start, end) { return toBuffer(source).copy(target, targetStart, start, end) } function equals (a, b) { return toBuffer(a).equals(b) } function fill (buffer, value, offset, end, encoding) { return toBuffer(buffer).fill(value, offset, end, encoding) } function from (value, encodingOrOffset, length) { return Buffer.from(value, encodingOrOffset, length) } function includes (buffer, value, byteOffset, encoding) { return toBuffer(buffer).includes(value, byteOffset, encoding) } function indexOf (buffer, value, byfeOffset, encoding) { return toBuffer(buffer).indexOf(value, byfeOffset, encoding) } function lastIndexOf (buffer, value, byteOffset, encoding) { return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding) } function swap16 (buffer) { return toBuffer(buffer).swap16() } function swap32 (buffer) { return toBuffer(buffer).swap32() } function swap64 (buffer) { return toBuffer(buffer).swap64() } function toBuffer (buffer) { if (Buffer.isBuffer(buffer)) return buffer return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength) } function toString (buffer, encoding, start, end) { return toBuffer(buffer).toString(encoding, start, end) } function write (buffer, string, offset, length, encoding) { return toBuffer(buffer).write(string, offset, length, encoding) } function writeDoubleLE (buffer, value, offset) { return toBuffer(buffer).writeDoubleLE(value, offset) } function writeFloatLE (buffer, value, offset) { return toBuffer(buffer).writeFloatLE(value, offset) } function writeUInt32LE (buffer, value, offset) { return toBuffer(buffer).writeUInt32LE(value, offset) } function writeInt32LE (buffer, value, offset) { return toBuffer(buffer).writeInt32LE(value, offset) } function readDoubleLE (buffer, offset) { return toBuffer(buffer).readDoubleLE(offset) } function readFloatLE (buffer, offset) { return toBuffer(buffer).readFloatLE(offset) } function readUInt32LE (buffer, offset) { return toBuffer(buffer).readUInt32LE(offset) } function readInt32LE (buffer, offset) { return toBuffer(buffer).readInt32LE(offset) } function writeDoubleBE (buffer, value, offset) { return toBuffer(buffer).writeDoubleBE(value, offset) } function writeFloatBE (buffer, value, offset) { return toBuffer(buffer).writeFloatBE(value, offset) } function writeUInt32BE (buffer, value, offset) { return toBuffer(buffer).writeUInt32BE(value, offset) } function writeInt32BE (buffer, value, offset) { return toBuffer(buffer).writeInt32BE(value, offset) } function readDoubleBE (buffer, offset) { return toBuffer(buffer).readDoubleBE(offset) } function readFloatBE (buffer, offset) { return toBuffer(buffer).readFloatBE(offset) } function readUInt32BE (buffer, offset) { return toBuffer(buffer).readUInt32BE(offset) } function readInt32BE (buffer, offset) { return toBuffer(buffer).readInt32BE(offset) } module.exports = { isBuffer, isEncoding, alloc, allocUnsafe, allocUnsafeSlow, byteLength, compare, concat, copy, equals, fill, from, includes, indexOf, lastIndexOf, swap16, swap32, swap64, toBuffer, toString, write, writeDoubleLE, writeFloatLE, writeUInt32LE, writeInt32LE, readDoubleLE, readFloatLE, readUInt32LE, readInt32LE, writeDoubleBE, writeFloatBE, writeUInt32BE, writeInt32BE, readDoubleBE, readFloatBE, readUInt32BE, readInt32BE } /***/ }), /***/ 62703: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var crypto_hash_sha512 = __webpack_require__(50780).lowlevel.crypto_hash; /* * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a * result, it retains the original copyright and license. The two files are * under slightly different (but compatible) licenses, and are here combined in * one file. * * Credit for the actual porting work goes to: * Devi Mandiri */ /* * The Blowfish portions are under the following license: * * Blowfish block cipher for OpenBSD * Copyright 1997 Niels Provos * All rights reserved. * * Implementation advice by David Mazieres . * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * The bcrypt_pbkdf portions are under the following license: * * Copyright (c) 2013 Ted Unangst * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * 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. */ /* * Performance improvements (Javascript-specific): * * Copyright 2016, Joyent Inc * Author: Alex Wilson * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * 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. */ // Ported from OpenBSD bcrypt_pbkdf.c v1.9 var BLF_J = 0; var Blowfish = function() { this.S = [ new Uint32Array([ 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]), new Uint32Array([ 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]), new Uint32Array([ 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]), new Uint32Array([ 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6]) ]; this.P = new Uint32Array([ 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b]); }; function F(S, x8, i) { return (((S[0][x8[i+3]] + S[1][x8[i+2]]) ^ S[2][x8[i+1]]) + S[3][x8[i]]); }; Blowfish.prototype.encipher = function(x, x8) { if (x8 === undefined) { x8 = new Uint8Array(x.buffer); if (x.byteOffset !== 0) x8 = x8.subarray(x.byteOffset); } x[0] ^= this.P[0]; for (var i = 1; i < 16; i += 2) { x[1] ^= F(this.S, x8, 0) ^ this.P[i]; x[0] ^= F(this.S, x8, 4) ^ this.P[i+1]; } var t = x[0]; x[0] = x[1] ^ this.P[17]; x[1] = t; }; Blowfish.prototype.decipher = function(x) { var x8 = new Uint8Array(x.buffer); if (x.byteOffset !== 0) x8 = x8.subarray(x.byteOffset); x[0] ^= this.P[17]; for (var i = 16; i > 0; i -= 2) { x[1] ^= F(this.S, x8, 0) ^ this.P[i]; x[0] ^= F(this.S, x8, 4) ^ this.P[i-1]; } var t = x[0]; x[0] = x[1] ^ this.P[0]; x[1] = t; }; function stream2word(data, databytes){ var i, temp = 0; for (i = 0; i < 4; i++, BLF_J++) { if (BLF_J >= databytes) BLF_J = 0; temp = (temp << 8) | data[BLF_J]; } return temp; }; Blowfish.prototype.expand0state = function(key, keybytes) { var d = new Uint32Array(2), i, k; var d8 = new Uint8Array(d.buffer); for (i = 0, BLF_J = 0; i < 18; i++) { this.P[i] ^= stream2word(key, keybytes); } BLF_J = 0; for (i = 0; i < 18; i += 2) { this.encipher(d, d8); this.P[i] = d[0]; this.P[i+1] = d[1]; } for (i = 0; i < 4; i++) { for (k = 0; k < 256; k += 2) { this.encipher(d, d8); this.S[i][k] = d[0]; this.S[i][k+1] = d[1]; } } }; Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) { var d = new Uint32Array(2), i, k; for (i = 0, BLF_J = 0; i < 18; i++) { this.P[i] ^= stream2word(key, keybytes); } for (i = 0, BLF_J = 0; i < 18; i += 2) { d[0] ^= stream2word(data, databytes); d[1] ^= stream2word(data, databytes); this.encipher(d); this.P[i] = d[0]; this.P[i+1] = d[1]; } for (i = 0; i < 4; i++) { for (k = 0; k < 256; k += 2) { d[0] ^= stream2word(data, databytes); d[1] ^= stream2word(data, databytes); this.encipher(d); this.S[i][k] = d[0]; this.S[i][k+1] = d[1]; } } BLF_J = 0; }; Blowfish.prototype.enc = function(data, blocks) { for (var i = 0; i < blocks; i++) { this.encipher(data.subarray(i*2)); } }; Blowfish.prototype.dec = function(data, blocks) { for (var i = 0; i < blocks; i++) { this.decipher(data.subarray(i*2)); } }; var BCRYPT_BLOCKS = 8, BCRYPT_HASHSIZE = 32; function bcrypt_hash(sha2pass, sha2salt, out) { var state = new Blowfish(), cdata = new Uint32Array(BCRYPT_BLOCKS), i, ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105, 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109, 105,116,101]); //"OxychromaticBlowfishSwatDynamite" state.expandstate(sha2salt, 64, sha2pass, 64); for (i = 0; i < 64; i++) { state.expand0state(sha2salt, 64); state.expand0state(sha2pass, 64); } for (i = 0; i < BCRYPT_BLOCKS; i++) cdata[i] = stream2word(ciphertext, ciphertext.byteLength); for (i = 0; i < 64; i++) state.enc(cdata, cdata.byteLength / 8); for (i = 0; i < BCRYPT_BLOCKS; i++) { out[4*i+3] = cdata[i] >>> 24; out[4*i+2] = cdata[i] >>> 16; out[4*i+1] = cdata[i] >>> 8; out[4*i+0] = cdata[i]; } }; function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) { var sha2pass = new Uint8Array(64), sha2salt = new Uint8Array(64), out = new Uint8Array(BCRYPT_HASHSIZE), tmpout = new Uint8Array(BCRYPT_HASHSIZE), countsalt = new Uint8Array(saltlen+4), i, j, amt, stride, dest, count, origkeylen = keylen; if (rounds < 1) return -1; if (passlen === 0 || saltlen === 0 || keylen === 0 || keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20)) return -1; stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength); amt = Math.floor((keylen + stride - 1) / stride); for (i = 0; i < saltlen; i++) countsalt[i] = salt[i]; crypto_hash_sha512(sha2pass, pass, passlen); for (count = 1; keylen > 0; count++) { countsalt[saltlen+0] = count >>> 24; countsalt[saltlen+1] = count >>> 16; countsalt[saltlen+2] = count >>> 8; countsalt[saltlen+3] = count; crypto_hash_sha512(sha2salt, countsalt, saltlen + 4); bcrypt_hash(sha2pass, sha2salt, tmpout); for (i = out.byteLength; i--;) out[i] = tmpout[i]; for (i = 1; i < rounds; i++) { crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength); bcrypt_hash(sha2pass, sha2salt, tmpout); for (j = 0; j < out.byteLength; j++) out[j] ^= tmpout[j]; } amt = Math.min(amt, keylen); for (i = 0; i < amt; i++) { dest = i * stride + (count - 1); if (dest >= origkeylen) break; key[dest] = out[i]; } keylen -= i; } return 0; }; module.exports = { BLOCKS: BCRYPT_BLOCKS, HASHSIZE: BCRYPT_HASHSIZE, hash: bcrypt_hash, pbkdf: bcrypt_pbkdf }; /***/ }), /***/ 95581: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getBinjumper = void 0; const zlib_1 = __webpack_require__(59796); let decompressedJumper = null; function getBinjumper() { if (!decompressedJumper) { decompressedJumper = zlib_1.gunzipSync(Buffer.from('H4sIAAAAAAAACu18DXgU1dXwzOwkLMmaWTUgYtQlXRRKCASwJRh0Q7IBJdHwE0BJCCHZhejmx91ZCELM4uxqpuPWaG1rW3wV0YqVT7GlCf4U80cSLNKIgAhUUWmdZdFGsCEhkP3OuXM32fBT+/Tp+3zv99bNc/f+nb977rnnnntnsjn31jE6hmF4SKEQw+xgtI+F+faPB1LcjW/GMduHvzdmB5v93piFq0pdpkpnxUpnUZmpuKi8vEI0rbCZnO5yU2m5KfPuBaayihJb8hVXxJgpjVwrw2Szw5lP214sDNM9xgi6WJYzMdOgsgQSxzCdV0FuRAQqnVFrR7lZKj/5dGqVxVNYMi6GMWmw+GXUQIyRg6hjmFHDIG8EVPafGPQFH34b4F+iffkTwOcf0EsWbVUi5OapVKBpkYOgNJjc5cklRWIRlOOxAccOY2amD4WzMJMbk50aYOYwgsgwekgzLoKzJNtWFdphdipjoaESkgHSrEvArXC5sFyFX55Lj8GDfEs1vkSHdZTvXZeQL2P+QiwTXT1Hx7HoEnCig/A14dc2CrfkUuN1OYsZOmeNFO7ei+EuLfl3n/BHOpmgZJpNCqMwM38CmhSvW5M983ooCN490L26JsoVCt2esk/q4dfc3J5pJibazptxmtWlyUCghxW8B6HmaxR8/ZCn7JM7pdaEZp7xizcxM58CWu61F2KO0TDd72IHG9Ghh443Q/AJvoHodTOjEP+VCHw0XPXTiZTzs4Sz+CPaEeokyIG18KXh/wzH4lsJ9QgamKvPaDTEdSC5NwsBtI4wjVvgq+5C+VZNJGWkoz4nUFkDMciuPmKAYRpf92t82QjZxyLfd0OBA0P7iEzDad8b/VT+BdLJUZu2FFlwkAkArSdMAItjBgQJdUonDVg2Whj1NaRwkldbohlmE59rYWTerHbHAe0rwR9uMnuQlPtO9W6AU0boEcCo/hW8gHS8S70NyKszsYeRgdcmBqChwG/iPRqhAPTJLWoMZglm9bcIen3XExrUZqSmZBgRsDGJMsMOJWMytm0d2paLbU9DW6AC1bf9Js0e0/yZ5iQyVxqkcZMJCqggyKRjLHQlISR0GQB0HAqqPgFNUmtaSx3YM4CiSkMjjoJc6lv9A7RRoVo/N9j/q6H9obGGJy1MuGE11M8BVN3AJ0/+yyKYEyOqezmgr0oi6obZcdMmUM9UrXGziILDSK7GZlCX1q6X27BxPG28ARo3M6A56PF1i1din14bcUelhQkdhMKxq4FVEWrJ1rN0WUHLoHztUYiKn534FfxDuEvLUF60IAQCGYeHiXZuEokhiLE4CX+cQOTd3ULGt3iR/w/HQSsLNpxMAkXK6808Gh7aadjyHyQIBrnFb4kOmzASevP7GjyU5Tb2tPr97xM7QZBM1NZoqPtt38hdS5cVFrQQXgvmK9Z4Jc8gW7sUq/FHBV0K4z3i5tt4LlFx6y0/ivP0xohjPL2J4lTvbn8V677NU93FUACrUZ6+hNACnDhsasvkWBN8cYlSoy54HTQPh+Z8bIYWLjgcWnS1Bk7uyQpurqPjhQnN7o5CM+Pccera86jnbwjZOvUlHIKtEUfUos4fD/JnMlc2qXzTMV792ziGGd+q2af1OGpG2HmrXzQbxzKZgOXukDqMsrXVn8HKfbJ1vy+kOdV26x5iwF0p+9qtnRGzBfPp6btdeHwx2Kenb4zw+DJQrH+a0bdP8O7jSL/UyLZZQvmpXe6/Kzmdvt2CrxkQN3WCkUrTWcH3GNYYMGGF6earLIIXnDqT6u4QHt4HBSVvD9DytQ8VIvAIFpqJv0nN63AOU6x7wDTMfuuhNo6ss7DjUaytZO1aO3C2u0Zjy9HNuDAV67HNuGAVW2NYd4QeTj3ap5xmVt8ep+0SZWDIUmi44C0ZXPe1N/izWNhmrPtZpXq/sLMmJPeBvnwnwRBx+AUAyjbb68Lj73T/PZCL6CBj9FAZ3a2yCDJWd0h7WWR7x2ici1a5B9VNBh18mnK11/nnfuzpvV549GfAR6jfHTL7N4Kh+p0gYI3wVJP8J03LP20a3otiLMAJWTiZHcCPkEc+6N0teKeCUG1cjd/JBsZBUTMro+C9BRjI77/fK3ivBxpsU9jfUfwO99+l6s5Ecbj0Gexq70NPG3uzP50lMuPyCnw6QOAAQwjUX4x/s7gG8N1Oyd2ZKHcM4r7YH96fPH33Cj9+GS187oueXrPw6DPnwwOPh12G0JgrNbMBJ6I4qfwmbSLeQGJoQL0oS3MgfnD+2tjEIdJOpRtYG5MPIgbMUAWhbo4UyohE2gK3nCe0dmKtKfDDEMm6oEb87caNS+TmWzAezH1m45JnUjpfxrLgDQCFBSmNwvO4eR+Byg6kKTyf0tjdxoo6qYPt3mUSo67A0LW7zYMt3JlmjFmxyGORYcUyqUMPHmDDSQwfYQMUXuXNykZzB3Ru2E6yjxuvZoRXDWZZa0WAR8NFg3mqVty9oQ/h3DcQshxyMJIij0VTdxORyLJ5HKgSD1ge4fmZmK0ei1J7UGrfvrVRO/AkQ/AsIDmKNDwKUZaebhnYfzYZcI9Fzz0WHLC9Djw5tvhzecXCyyMMxM+7A1KrQVt/LRfsBxhPKNcbM2Cq+0LieN8R8UoCF4p/hjQGWfc34OW3XQveuqsHJq111NIW8DspjZr9yC0wnUq8D4F9+9xdF244m5K0fWVYC42HorAB5yboRfm1eNMs9ejEeAAzkmnDcNFAtt864l4WmsdhUCovNOvRz8zh6PRSOMqQ0EffHS/NXIW+GwmLMe1RpILgPZx4DUZ486XWeEJg6bIwnx3xz1mYifgltzX1c77Gh46kHIFxKvwz2AiicRBWtbCpH9ecHIqtcQde4wZ2PvA8RF6QdSOLYl4MH9Z/SuPgXOKHyA8KnwMyq/ebMZyyYJwDIcURcaK9TtEh1X3fIxu03KbqzehD3QaIFPRKBi9PM4c6laV63xH3gTCVP2jAIMXSZS2bMrWALzwfOP8ot0ELH1FMlf8ezisM2YKjoGRkHapTzuDVA9C9CYWSw6KFQTL0ai50pjQSdmAoUkco2D1kfkj8ijIo+WYTyCEAXErj0rBZ1oWFrgwz0YKpcSm7gwacKLnJt08cLXcqxtTDSq7e/TffbnGCPI/YxXM8GQPB70iMlGNwP5VHINFgZ5jfgP2xYjwaYSEwmxA2rhZ7HdWXWNMelUkNd6AX5QnrczYp4BGmmYqgIZDw6JVEMgPBlwbpbVSvApc2SCq8f6h94P7CtASfE08+r2JcR8fVM4aQCuCeOWAvmzDixv3uGhykaDb7l1gGjDHfjGeBreDM1T4TMVQT7Id6CMNwbak10KaOHhOen7zF8oeL5L0LYF2TyDseySZoRs1jeDqbCGBAN/sCtXupB/wTHAjdiWCFRnDC9YZhtQYdOIbULucpCMO17b+erhOT32E2IlkSBzjMBrLGgRWJIUxI3qhkm8cRYvuEev6aWv5q2IJSTwGxXov4qtTLiy8DgpEia4stgsgrGpEwZ1CBHtWRoNl4K6qile5Hm5Zf6J+Wh6c5cyV4BPySeoY9dIxEhSZlhNYQKzz+JMC8hTXcAGcABiw/jGYmkaKeTF8VG9ar1GLY0IfQrmxFp8zlhfoFev8OvJPwv47fige/pbMQGcgIftbkLhnfo4t+g9eQYXgJ/oXmBLlLvQdE12g5t0utJhhihH2jMFvQ786Bfrk9dmY25ILvL6j6EblQfgu/AnPC52HprF6cC44V13DSCmJFCcRmN2NMsJoRGp5AweywH0VveBfvBMeffQOdKdtJxMkkIrUBcOBaNEmhPs67G0B3A2RofC/CsB1vUK+IoL9C0K8G4g+iQW00gpQ8GD8oC3hFRwev1z1MFPVb8j3INff8gCI6qSLqCL2AiMFDJhlUD872wXM0fKDr3QTDNHhuxC3hvJgt9ZwTJ4ENLJB6QuIcqadfnPCRSWiwIB9DN9lyjWKU8OpCswFcCq5WPGcZYWvtx0P9CBVWX/DDsP1gOzYf+TyI/gOrwV8P+HfpZJIfLVezVnIM/sVoclgKjSiBMF1qTRqyIeQRu0sTdo6TceCwLOSgdH6iFuPIzdL5AsHbSdfhWLwHlXEtqPIB+bDcEoytkw9OEM0JsJRK/NWs/LHUR+GlPqDRgOHbEcH7Djb0TxK89aSQL3j/DwY0O2+Uz8unUF3g4OrleDOIYFYXgX3IbQpOAe7FUIP92Ty+zdft3ih/BG59nHxC+tzkn8V6egvEUk9vjXiNd7e4TKi/k4VDhdY8H5rdAWwC/r4b8Szj5ORmuSu4X9OjUD+H9eeytzrMCYL3JRalCQSuGbQPYWcB6+krEK8Rdp4GziacmEg/I59/cyIGlbdRQ/dXc+AtzKCX9eYk+Ywimk1BI+4HwQn55gRpF8gh3px6vroGiAXlJDO0qI7rcB8Mj3QZ1Ma3wMb6EY4XHZQCpIT6+Zz0qck/m/WcBdWuAXaeszXijV44HKwKYSi9mJXbw91LtG73p9iMh7U/4Kot5OR2+VBwD9nf+uUTSFdBYddDOiMfBMGxbgoK9jr5NJH3K5R3Qmq/8OMgzuGX7i9g54dWdcfoSJl/M5rKfABkTqIymy+QuaU/Qubt/RfK/EL/BTLLkTLL7QFmcFYgPoH5H5h9wbsSkXuRNhyFlhDag1YgeOdo3UgbLcF9ZdgKBvZnuTn4O6KX5sBvYLnXyf04gsBd56n/Av7TIvnnybsWL5IPwpqBqZkh7DTCSbvT05cseKegLy5g8dTWiwbyJ+kLE2g4Xj6Tdrvg/Qaa0pYK3o2Yf19c2t1kcg+XztYI3lnE+KK9jaIbb5+6d1kEH95v4nrIBjUvNI9SZ10L9V1kSwKtT4Ma6DoBdD5q/C7fl9qt5ISFZmNwCoSQQr0OOHSn7AOSifLeDXvxiYX8tXxWPqTOhLHgvYzUznpqQoxbhSXemiR3DhyghZ0jcQQ4GE81O0askQ+BFEZ1fx94vF24K+tQ3noUwCjs7IQRS204aF88scYaVu6B5jOHgy8R/Xlug8PTYbLgdPKfg+/JB8bvCtwxqFHP2WRx6ZkmFBGsFU9tJ5IDpYP9/gIO+YPo80ECZCo3C/VWDqK0JPnPgQfD+4ywM4+o/rfo+Qu4wG/o/gvyBR6AclqB2wB4On+BjsD772fTCsQRaTXi9aCmKUJ9BisHSaM7iJWAKUT2J9BxPNbh7DHcv4CTg/KB4F45GHznzQJc/u8A6Tdvx9LvsbQUS6/0R9jLYv8cdhFEO8JOjAKKmk5EpYTkg1I3K/2VDX4PzvM93xfvl3puF+1Sz1L5j8JTEN00yu3CTp3UxALGJKmnxh0tn/Lucyf5QmKnFGIfglioQPyB/EepZ4x4ELJ2FmABA7zo+2S3hgF61rGMfy4njgKkF4OHB+RZSkJCAEppDH4A4wNjblsgf4Ah0SyDbhbv5316Go0ps0jUO3oEufG+CYIKZYEBYnD/WpZ9nz0rr4PTQG07X0fCj1aIy5A3FOhZRJMD1wrGevHkDBmlngS1QvQCZR484RgS04jD5FPqB3gQh/jv1l48BOJRQlt/p9R7MEY9SEeA4iI1i8G/hPXzzxBfDFJWjYQ8C+mOac8i1+6+Iw/FgX6DbDv/NNbd36APR8I78EFd8DShH76Pc8jWVjmvU87p8PyVF3wzMciqbpVtb+ONzh9BBbBZSI1GehFnH4EXcbDRGsiZUbuBVI+P0GTZMpwJ38/JVphMv/WQmonDs+7HAG4DsIdZuUoBdj3qkfO4IgVfbxReJTXKn4OjVe8dgTctYW498chNPuVfD/x6YVvBe+UmVj5Vmx4C471OqOf8Tjatxn1CqJ+FtiA1c6TL/ReU/st4FGc/iZGO4grGB5X+vEMqhhcgk5KzH93uCdgklYJWNPY02KqnAlAa7NQTdHjp1uiZngz7KJQ9VbhSR0Cp29ppFHyvRTNMm/XZ/HYrefYVuEunnYNsO+Q2VMbj8ZFDmRiPnuAG0B2Opfpt/12wy9aIiZ6+dWJm7Y2wJ3ghXvgFh1DLWHkvKI9AuD/GetuwGu8Rt8GfxYHNQ2dTcE9tIfgfDkhK7VzwdXsdQTslgyJz9oNStMjwULt1D97hp60TJ1A7qvmBFzRxA3SnJYEj7mUF75WE6ywOFA3aXOc+ihWi5+BXA+snrVrwjcIzd4B175Oq96yDOQMFUpddvV+p7lSs+99EtiC24H2aoc8B2li5ydNXLZZ7+pIE3+9JDA4R/FZEO/UWS8HqYOeC7ZPF/TIh8Ddm4CAv1OdyUiMH7YLvEKNNg/tEGxueWcW2A/gOXIUOxOvSCRgZ3r+2sdX+dBbVg3L5HMRbL+PamBr/HK52CehdvB8adFKbLrAwIk7O2d82bJ28FxQeuBsdWzrgr3Pr29h1cGQKvlZ7LczIy8Fp4f00DWg3kH14Focafo1c68EEzdLJpwKbB+LyNgsXFj1gGWRX5zm7TlznOVsteJ+HKkYMo0Lkvu7zfuKP5S449uG5od6Iht7I1s4LgW/sUqx6+az0JxZMTsnpUKxvq4kQk+Ox+xee20DhT1KTCizT6ICyFNvbl9BXC4QPgdUDcuI4wHrWkWkKfA6LFTQd+LQv3A/+RfCWaiJaAAuWCom5ryT+Q8lr9ScMg60v9RPXNWR+0yaJCWn5YgziQfNh91fQEgMt0biIglcT/riDTxK/gdau2rxnlepjoCk8EynDcPn+ABdqTqdcsEPu2/ApPiyXc1qD2Zo8sCjhnKxUd4CHSVTfvZI+WuPJvU7oQ/CPBu2enJqNTmohvqv1NMiuQ/JfoHVX72fFo+QZWgw6MbyefxGG1m7dTlxro3iFdlH0uhG7tyvW7e3WbUQfjZxsfW5Qn4p1D8LZDBjUI/nJmmcF8aKlh/RG98f+hwwwGsW6Qz6r/lc3OkP3u0LDXdGK9TnZttWfyQrUd3wtoIfcDr4DDkpy3ha509ct+G5HcWGR5r0AcYLmir9AjouN+PjhBYiiVIMx0gX9hpDZQt239QWIAEdGzH8zOJbaWdSvRoP30fxqFjhV9DSky/0XBfCAyZNASz6nDWw6Tkv1fthkQhxs45LKjmkHhwATYhG8n6Gu8/QYJ+EzFsW2NfCZ5n0Ds86Rpwq4G1DbbfTs9ajFvVr3srNoVESJ+A6FYt2GzDLR1PL0UFN/2QMH3mlIDDYOVtCcvGgm3MTrIVNH9SCJYxBQw25w5Gs04bcDe/toYzAASoXZzHkaI068ucGbmLwX1BECmn/mtFhQo5LzNG4KrzPapvAyQ6YCAqpna/kp/swpbKAKJarehs+cQthrBQPdop0YW4I3Dt4/PR4HnYKyGPb9Gk5+F2S8Rv5Qma0H6ZExBOlH1akAEzysFGyRrVvgiI13h+rPES9vCw6eXN1X6tst2uN1hpjkvofGyLP5wPOaYuD0nngG9PITsiS3s52BQ3jtPyzwMBGzVdt7C7vppizqYecL3IIqTzPLn6uHr4i0mKoryP7b6xfBYE4FjXIv2AIxBMH7KPF1LMREYCd/FerTYf/lgp+Epf70ClwfZMr0RJRtFwoe6ALBYDViTBI4fn4w8NWycHySpLjjlQK9Uk1uYs+0ozsQZ2y4bckKCyNeAcP9HMbSHo1V0KSSYyTh/g1n8OkG3kvfiI9BOyKek2WhfIPPb6UvjLDgrUdl23GMwj4yRCpgjQE9zlGyZHgZjKY5eHUYD9ZL38B60fnX0fWSQdZLy+B6OSbnEIdSiLRsx4EcKsWOnvOUnHNcdf0d1JNzPHLvQUHJ4I14nKZjjYMIM+JKSnmIV5YZfKGHrmM/QXglS6/wT6MXBV5/+yoUSv3EHYRGvLbQMAMffRW+rIl4HpsU8bYG6lY9E0svqWOQ0sukhjCOFZYBmA9wQebofbvBfqx6z3TGXRX5ykS5BopVsnb9lSw+KdzkoC83NEKcuJlURO0CERGwIyOW3KvyYT73x2qvP9wIkiu3IMbgQ22qB9l2dPChqZ5yJRewi2LJw9bBp8gvxxBzhsAVIEkclqZd1SbF4ts0sGfK1kN2OX620DBs9e1yk122fiY0zObk6uN2qRe8gB6EghL4gX4WSz0z3BC5gWEcBzAewYNCeD/HGkGs/oxxX6XYjgYOR7wAgfsDIOV9BqHctVq832aXzuaL3xMaFmG8Ywf/MA1aJsHaajCSgvb8CPpog/gNwfgKMAF4GFDC+7PUnOPCw4/jBt5g/QxEnCReCd/5YiwwfCMZXZEMwz+ess8u53JhzZFXD+iEvTOcxPx4dalNWN5xnBqDHt3QcW3a2iKj/x8PHzpp9cO1SbvvJDrco4E7YNz2OrlDCnAonJSD5+gGlsgWILJ9ntJol9NhXMPkXtJ8FTYLvvcG3UGd0DAPYlKODPw0GfiX8rvjz0pneeHHL+IQeu24rjAWlwuOy+8GzTSOabgXDgkcIej9OQmK5VMEFO+ZkaKc3o9M3QeEhtF2qS9fNMiHIJ/k/ojcCzRALNzMEbFOE2m/DDaCnu2pYBy+63FsUg0PJwN87BCphtf0mhqKg6AGt568oWRPnc0JvnkYgjawgbmR9yvgXx8m67jguGI9lNJtl1PwBh6VjCEe6PkmnAG3XuqBneYxINbGRzMBCd2w7238bnDDfPdDUGXHm0bflnBb6gPA85ekNo9H/WnoqEPB+7D2NHhdf4RroM/L5A82nFxIHsOT2xc0CHX0cPpiDd7oiimN/rkGu5wRDbulOa02wwDO8GY4Xw8j99sZ0RClYq99Js8KDXC+z+TTpPeZWhYc4zG80zEvkXqMa0bA0XpDK3LClR1e1+0ZenyFMbKDzKdaoSdvRqnDIBsl9elEs3oUyhumxwIgVP4EFWk6J25Vdw3DvWYkevtn1R2kgjMTfFJ9hVTwVc+gL3y+vuR4E/V0vPje0aWGOw6Gq9fs5L9pvDU4np6rxD3q36PDQ7gYndxna+8RKV6zhSUvgHhfw9us6YzgfYQlz68Swu8XkVAHwqZfAknPenMCxPhijhIjNfP+DaH+/v4z74/pGOuBj3jiZQ8E2oJ3GmK1MC3SYd34U0J9dvx1fn6kp3eSaPH05ou3vpGvuRZ/5kg2OBH92z8i9iGjEZM7pUM6fJeJkU/bZaMCpwDe/zDB2TemMxLHHd2kGmFblZuYJumIbvxpv5TAarcOq6PwjpBE8Ogv5rJ+Dzmo9vLO+cpCw6imIF6pLtSfkz86/aJ8Qk3EgMiH7wyTpbQZkHZgrd1K4pJ2Xzx9nRhcOL+hlbyapQ4EELDnvSXUj6w1djdx4utCw8K4fjsQ7w++qM0XitnMBW4I38/RelP4PUN1Eoib8mV4HiOpa/Mt0H5it55B/5BkTvlSHfkFxHZ4/a2q+EyWvFQcwMtvfN8AH9cZwVCnKXXxZLb8d7JyLRYhSBypeHCQ8mH1qvPkfHht45nOMS1Sq14+tLQF4tOfA8GUI+3McOSrau8v4KPkIxBSS0aq68So8Ft4Avq2R/8aCuHl0qilLepiIhBi7yCvlQaGxnMR9EYM0tvHU3rua9SRAwSGPFqWRmli348XsRKdNvFouxSeJgJdJ5000OHHKJ548nKAoUVt1g0V6sSAPsnzXQivzESo7qq7cTyL8Za4W/yh9BbyCbmvCyaF1xeV+bD6QR+5Sb5aIQLAkpdJIbVr/VF6fafN42xd2PtozUPdK33+hFOWgKYrYfxySyU+M+0W1/oX6VOb1zj9ueeU9RC+fXZOuUr+QH5f+lwnfXpOLuRlIXXvmgX+yp7Ur9dkw/GP725mYf2myuf9a4ad+TPYCj7WkKv10mecGOtfwDad4JT4J9j3SXOeAdymW+dfE6skmdmvx7w3/kCq6sbHZjyYA7FFO74vAKen0E44CzHvYJAQ3DpEfvrYNt88GZQ4DWZ1BkRURnz4DTuWiuaf2iLeBIO5IRX8jnOy+kNuUB8m7c6U7Hf5gCWSR+ChEavIgzrywJEcyNZrj8aNGhJ5DjlUfwnIXIlGU3oHXd8ivdyuZPH+e4dJx3RSD47y3lgY2HT2ELkMiCbPA5GNMjK1Gfwig4sNpvMeJRtGMhEnYPz7vi/dSzZjUSnndcsMbMvwXWyHnKyU68/8eUxwwjKD/GcYXMKEhebJ7Ie3rjdPX5MCourDT/IxbFGipSAvfX5O1kmtCRHuoy511+qXg8/b62Bipwd3R8SDDvNkAF26TFbxdci6ebkz8d8V/Nlmg3PEhgCWpeHMRMxJx5rg+CZoWHIPwIbGtpJ3Z0NjG2m+/Ektz6f5EpovpHkuzbNpPofmmTS30DyN5tNpPo3mk2meRPNxNDfT3ETzBJqPonk8zY0019Ocp3kPlf8bmp+k+XGaH6P5IZrvp/kemu+g+Xaab6P5VppvofkLNH+O5htp/jTNn6J5Hc0fo3ktzb0099B8Pc2raC7SvJLmDpqvonlJeJ5IDpPMS8e7Qg+c005l8zacxFcNFFZZC4cLr2o8POQFdhJe4hM+teEDrePO5eT8JFs9ah25B/CAR70Cr4BSoRq4miPnMjy+0MMcCfoB4afrcS/J7tceQaRpeeRRjgAC2fFINscTlsKfTs6ZU7VWua2N1zPkGiqfvB868J7y2fOEor+gVg3hFSLhh3LlHMNLAS/EIPjGAH2fRj9nkGWtmvUBfY/nVqu3elwkWBhKiX8UZENyoz9Ach5L8APFWhsWwIIS1JFbhscI0RbobON1jN/6GImtNeaMRpVXD+wjd0k7ybtaWz9Bio/d6vZWTwAcExyJAG0APpOMlVf4hiw57zFk9HPADr6n5NWmNovXox4IjPYCSDa+k/3rczAVtai8vC0QSrpfeAP9mvyhP++pdusLmVA+/Yr8IXk1AwoLzXgnZQq/NgL5KJrH09xIcwPN9eGBhE9yP8WN/uQ4MIUENfU8+beLmuXaPwWo156jyg1mK9anUGO4P+I4GqAnN9dv1d4QtD6FbTqcO+tT8+djJYtUnp6H5RlQXoSmU/0xNtb5bV33oK/zF50Dv2SP+AtM6BxyxEB2TIb2Hhcp/wd8zuM4YcimDMt/zJi/+2gfR+mKlcXFha7CkjVTJqYklzgcTGGh07ay1CXanOQ/BW2FpeX2CmgtsV2qHT7JpOBkcoucrtLylSZ7UanDVpJkslVV2opFW4lpLFRWVoiQxySZEMpWMsN081jXzUyG01Yk2nKdFcU2l4simsaNLRmfHMMwr15jYZ4fMTQtj2gbec3Q/N+RkNb1oyyMMOrfR/NfkeHCvHG0hckB5a7Bf6YVS8tsRFlup21GDGMyLSp1iu4ixzy3zbk2rEV7hRMUblqxVrS5TEWiqaikxIlKHov/9Qk4eeX3l1esKTdVumzukgqT0+aoKC4SSyvK8R94xYriCodptQ0mFBrGluB0/EOcFaWiyVX6oC0Mu9JRsQLsafLEMhR66hTN2pLJ9+yMjBmmcTCa2YuTK5wrTRnOCpdrIrSaZrlLHSUTp0yeMnnyLVNTJqaMN6UmT0me/G/CiYAeAPp/Jct3ON/hfIfzvwPn/+dPPM3ZB+cz7Ho9e52B52tZ7f/0McI/9mwo9CsMyDPiTNyimDh+diwzjtF+gqBkE5wcEDk9Ti9xALAiLh6+s+MSEPi+mLiEWEK/BNK450MhfC8P6FjWxfHkJw/WQ8qF9hFauwnb8O21/Ava8P8OVkFbNJUV2/DfqEoi2i43jnF0HHMAdhOV1cfNuiLK+ohO4rl1MS3pbem7AHhurAYHaQ/AJkfC3ocAl+eRRHm0Ap4jEm/Wo7pH+BwpiluEXNrTNTIEPhvhNodCGyLhMxEewNNjBuHTY8lvcaCuKveGQgfxsJwJR87ZxijOzWQJOndltHEY515vjObcVUYd5xZ1f+CaACKdEslArpeTPY3K3gOy/0oXIUuWJsv8CFFmxep+yEbUs2IvrxMzpWv5dSg0DO2nAG2Em2OIMvh0HKLrucKWOP5y+PEU3/hSKJSCAHfFGfPBbvB3IfCnMqZD+/xI26uIidOnA8HMWGIf+JMRIsAkfIt9JFA+qwA2g9pcHpj5nNjlcThXeP5FHT390qD9PMKlxxkkHUCWxMQZslqAcRtiVETU7owtHKxQm/Ui/pZQSPctMk2nMh0Hnssv4gnL6444Uy5ZZPeR74w4Q3qYUxIdux74kB/SmEf144pLuCvOdHdcghUQqK7AtpAXHv6XAHxtpD5zASYDYO6IBYZz4kxVQzDn4i8ZoO9rhbQVcN+mursXdJcRuxS+rbGlRDpsuTO2hJS/fR5ML4dCd140Zs2H4DzkQv/JgTUD/Y9Cv/ERPiMuXoqyxuUuicvMiMsti4mLBzGNoBJDejuIvAsdV0mcBfq4WSTLuAQI6APXP/qbQ8DnBNrtfXH6R5HPI7r0OKMEfCZzP4kBtBZAawO0dlQG13dB06zYfzC/Yd9a8kootIbqDdY8sd1vWw/bAMes4UxGC/22dY3wN+uG6Csd9ZWO+gI16G5iL6krxMdnZ8+9CvhcGD9jAD9Dw7dw7wJ6xgXo1ljCH9+tr9sWCj1D5+tRLnNAj9z9MRHqssbeg9UsWoV5wHV3FFIX4OcP4JN5yEB8sEXOAkrPiKCSHgtdWRENjOb/8b8c9a+HQncM2FUG2pWVOI2BpZMVi7C56M8Bdu5QWJihByNg04l+1gNsLsA+qWcu8pu63VyEp5wbq0tkh9Rxnb4N+NveCIX+zlyMz2UNdbS4B5zEx6ZvhkKLh+qD2qXp7gtsEBzS0IZv27+8QPsq/hKybI+QZc7lbdRC6eTvHIwL6BqeE3eMy407BMo8xnGLQZMZA14zJ6I2Oxb3RfLzRe+EQjv+RRpLBysM/ugQvghZ9Q7+gMBl1kFWXCOnW8Be0pK5BZdonh2L+5Ae6JmaQqG7I/ymcTX1mxlanIQPUrMBZlakb11EnOG8QS+szcESgK0E2MKLYedT2DmxNq2APgR1/hzA36z5AyMQJMRwf3wB+rZD3wMX+VJufoQhz469a7Dybb7kOND7HXMZHWbEJXBPXsKVZFzeXhZSutnN1A9eZNOTqy5Y4tbYhRdYeXrsgqENl/e7uWH7BH4fX34ck7kXLzHlWbChDwwugzZqfC7Hz0j5bWwPhaKY/5mf3LrB8pyfab9bti2ibTn+fhK0vR3RZvg5xMhPXJpe5ZMM8xCkOkhbIDVC2gvpMKSTkM5BivkJ6AXSFEizIC2B5ID0EKRfQvotpGZIxyB9hb9f8hTo8imN/k2QT6blNMizIeVDckB6ENJjkH4G6TlIWyHtwN+fgrQH0kFIxyCdgNQNqR+S/qcMcxWkBEhmSEmQpkFKg5QFKRdSPiQ7pEpID0LyQqqD9EtIL0B6FdIOSM2Q9kI6DOmzn36nj0vpYwGT4ahw2eYUlZc4bBBpDbkATsef78u0OWyiLcNZKpYWFzkW2IrxfpH5krGWizbnhc3MKNZaVSpSfGYim1VaXkI4MCmknFXqdIlZpQ4b0J5FWu6yVdGGIjbLabNll65wFjnXMj52tk3MqCgrA9GyS8uh/2NsQfIZFSVhERkmhK3ZRS7R6nRWOGEmOKjnVJS4HTYke1dRGfK6arBVGyvyxzakk65dxTLMJ9wd5TCgIkfpgxeNeJIu21a0+qJmZoouu6KohEoNVB38ApuYV76KcCmxVhXbKhEQZAF9MX5+ocMFbBcVOdw25vc8vSkGKUQgyDANfOTdMcO8wy8uKhWzKpwLSstXOmx3r7gPweYxhS7RWeKuhPnDUmlxhcPB3MMUFq60iWVFpeVFzpUupgrqZSsKi93OwrKiKjzvFBZWFhbayleXOlHyR7S6HX8DEqwFai6bWFhUWVkorq2Elg+ZwmIbqBtntdDmdJZXMMztbKG9EpRlg9Z7oOx2OCqLxFXMRrawtGIFw2yC3FWs4b/MFZbhHTRYOldYUU5I/Z4rrNS6T3LITuP9A75oRYVTZG7jwfgIRysPOnZUFDPMfN5eTAyIKeDtFZW2csbG28FKS0DTdpfNdj9TzttFG4z/Ad6+BmYHIP+LL6PYL/JlK1xixZpimN3f8GW2suJK0OpWLJVVrLYxr/OVNs1ufsdXOkvLRTvDtPEgGN6kw4ro4F2lK8uLHAxzgAdFEz0fJCWkcxRLDhCJ6eHFCkfFGpjhEL/aHqY0LgoYixUgAqxQlNqGMwrCa8KhD/9vSnOt8++yZk+dQp4gwSe+TktlrtXFTlFrHVf3PztFyvqf9MFnS5Wj/5lffP3u87/xw26zMAmQ0jwWhn/uOzv4z/2w5G5q1EW/+MuSX8iZfIn24bx2Z76kkWEeYAd70m6vKht4gDwzMSV5cqLJVl5cUQJhxczEvIVZE6cnmlwiBC1FDtiqZyautbkSb78tJq3I5bKVrXCsNQF+uWtmottZPsNVvMpWVuSaWFZa7KxwVdjFicUVZTOKXGXJq1MSTRCwldptLnFRJLPbYkymNNHpdol3lNsr/kliUwkaILpsEMSUimu1KjQ4bQ+4gYWtJNdZuhqivJU2V7gvstdaBYgYfWXbVtscJgd+z0wsct1Rvrrifpsz0eQuTS/GMHJmor3I4bIlThrgMOmyLNImRYqTNmlgVKCtSWF13fYvzvj/BUaIzSoAXAAA', 'base64')); } return decompressedJumper; } exports.getBinjumper = getBinjumper; /***/ }), /***/ 94372: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.makeBinjumperSync = exports.makeBinjumper = exports.getBinjumper = void 0; const path_1 = __webpack_require__(71017); const fs_1 = __webpack_require__(57147); const util_1 = __webpack_require__(73837); const binjumper_1 = __webpack_require__(95581); Object.defineProperty(exports, "getBinjumper", ({ enumerable: true, get: function () { return binjumper_1.getBinjumper; } })); async function makeBinjumper(opts) { const writeFilePromise = util_1.promisify(fs_1.writeFile); const mkdirPromise = util_1.promisify(fs_1.mkdir); await mkdirPromise(opts.dir, { recursive: true }); if (process.platform === 'win32') { await Promise.all([ writeFilePromise(path_1.join(opts.dir, `${opts.name}.exe`), binjumper_1.getBinjumper()), writeFilePromise(path_1.join(opts.dir, `${opts.name}.exe.info`), [opts.target, ...(opts.args || [])].join('\n')), ]); } await writeFilePromise(path_1.join(opts.dir, opts.name), `#!/bin/sh\nexec "${opts.target}" ${(opts.args || []) .map((arg) => `'${arg.replace(/'/g, `'"'"'`)}'`) .join(' ')} "$@"\n`, { mode: 0o755 }); } exports.makeBinjumper = makeBinjumper; function makeBinjumperSync(opts) { fs_1.mkdirSync(opts.dir, { recursive: true }); if (process.platform === 'win32') { fs_1.writeFileSync(path_1.join(opts.dir, `${opts.name}.exe`), binjumper_1.getBinjumper()); fs_1.writeFileSync(path_1.join(opts.dir, `${opts.name}.exe.info`), [opts.target, ...(opts.args || [])].join('\n')); } fs_1.writeFileSync(path_1.join(opts.dir, opts.name), `#!/bin/sh\nexec "${opts.target}" ${(opts.args || []) .map((arg) => `'${arg.replace(/'/g, `'"'"'`)}'`) .join(' ')} "$@"\n`, { mode: 0o755 }); } exports.makeBinjumperSync = makeBinjumperSync; /***/ }), /***/ 86744: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const stringify = __webpack_require__(13349); const compile = __webpack_require__(27529); const expand = __webpack_require__(98050); const parse = __webpack_require__(94339); /** * Expand the given pattern or create a regex-compatible string. * * ```js * const braces = require('braces'); * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)'] * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c'] * ``` * @param {String} `str` * @param {Object} `options` * @return {String} * @api public */ const braces = (input, options = {}) => { let output = []; if (Array.isArray(input)) { for (const pattern of input) { const result = braces.create(pattern, options); if (Array.isArray(result)) { output.push(...result); } else { output.push(result); } } } else { output = [].concat(braces.create(input, options)); } if (options && options.expand === true && options.nodupes === true) { output = [...new Set(output)]; } return output; }; /** * Parse the given `str` with the given `options`. * * ```js * // braces.parse(pattern, [, options]); * const ast = braces.parse('a/{b,c}/d'); * console.log(ast); * ``` * @param {String} pattern Brace pattern to parse * @param {Object} options * @return {Object} Returns an AST * @api public */ braces.parse = (input, options = {}) => parse(input, options); /** * Creates a braces string from an AST, or an AST node. * * ```js * const braces = require('braces'); * let ast = braces.parse('foo/{a,b}/bar'); * console.log(stringify(ast.nodes[2])); //=> '{a,b}' * ``` * @param {String} `input` Brace pattern or AST. * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces.stringify = (input, options = {}) => { if (typeof input === 'string') { return stringify(braces.parse(input, options), options); } return stringify(input, options); }; /** * Compiles a brace pattern into a regex-compatible, optimized string. * This method is called by the main [braces](#braces) function by default. * * ```js * const braces = require('braces'); * console.log(braces.compile('a/{b,c}/d')); * //=> ['a/(b|c)/d'] * ``` * @param {String} `input` Brace pattern or AST. * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces.compile = (input, options = {}) => { if (typeof input === 'string') { input = braces.parse(input, options); } return compile(input, options); }; /** * Expands a brace pattern into an array. This method is called by the * main [braces](#braces) function when `options.expand` is true. Before * using this method it's recommended that you read the [performance notes](#performance)) * and advantages of using [.compile](#compile) instead. * * ```js * const braces = require('braces'); * console.log(braces.expand('a/{b,c}/d')); * //=> ['a/b/d', 'a/c/d']; * ``` * @param {String} `pattern` Brace pattern * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces.expand = (input, options = {}) => { if (typeof input === 'string') { input = braces.parse(input, options); } let result = expand(input, options); // filter out empty strings if specified if (options.noempty === true) { result = result.filter(Boolean); } // filter out duplicates if specified if (options.nodupes === true) { result = [...new Set(result)]; } return result; }; /** * Processes a brace pattern and returns either an expanded array * (if `options.expand` is true), a highly optimized regex-compatible string. * This method is called by the main [braces](#braces) function. * * ```js * const braces = require('braces'); * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' * ``` * @param {String} `pattern` Brace pattern * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces.create = (input, options = {}) => { if (input === '' || input.length < 3) { return [input]; } return options.expand !== true ? braces.compile(input, options) : braces.expand(input, options); }; /** * Expose "braces" */ module.exports = braces; /***/ }), /***/ 27529: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const fill = __webpack_require__(2664); const utils = __webpack_require__(73083); const compile = (ast, options = {}) => { const walk = (node, parent = {}) => { const invalidBlock = utils.isInvalidBrace(parent); const invalidNode = node.invalid === true && options.escapeInvalid === true; const invalid = invalidBlock === true || invalidNode === true; const prefix = options.escapeInvalid === true ? '\\' : ''; let output = ''; if (node.isOpen === true) { return prefix + node.value; } if (node.isClose === true) { console.log('node.isClose', prefix, node.value); return prefix + node.value; } if (node.type === 'open') { return invalid ? prefix + node.value : '('; } if (node.type === 'close') { return invalid ? prefix + node.value : ')'; } if (node.type === 'comma') { return node.prev.type === 'comma' ? '' : invalid ? node.value : '|'; } if (node.value) { return node.value; } if (node.nodes && node.ranges > 0) { const args = utils.reduce(node.nodes); const range = fill(...args, { ...options, wrap: false, toRegex: true, strictZeros: true }); if (range.length !== 0) { return args.length > 1 && range.length > 1 ? `(${range})` : range; } } if (node.nodes) { for (const child of node.nodes) { output += walk(child, node); } } return output; }; return walk(ast); }; module.exports = compile; /***/ }), /***/ 86611: /***/ ((module) => { "use strict"; module.exports = { MAX_LENGTH: 10000, // Digits CHAR_0: '0', /* 0 */ CHAR_9: '9', /* 9 */ // Alphabet chars. CHAR_UPPERCASE_A: 'A', /* A */ CHAR_LOWERCASE_A: 'a', /* a */ CHAR_UPPERCASE_Z: 'Z', /* Z */ CHAR_LOWERCASE_Z: 'z', /* z */ CHAR_LEFT_PARENTHESES: '(', /* ( */ CHAR_RIGHT_PARENTHESES: ')', /* ) */ CHAR_ASTERISK: '*', /* * */ // Non-alphabetic chars. CHAR_AMPERSAND: '&', /* & */ CHAR_AT: '@', /* @ */ CHAR_BACKSLASH: '\\', /* \ */ CHAR_BACKTICK: '`', /* ` */ CHAR_CARRIAGE_RETURN: '\r', /* \r */ CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */ CHAR_COLON: ':', /* : */ CHAR_COMMA: ',', /* , */ CHAR_DOLLAR: '$', /* . */ CHAR_DOT: '.', /* . */ CHAR_DOUBLE_QUOTE: '"', /* " */ CHAR_EQUAL: '=', /* = */ CHAR_EXCLAMATION_MARK: '!', /* ! */ CHAR_FORM_FEED: '\f', /* \f */ CHAR_FORWARD_SLASH: '/', /* / */ CHAR_HASH: '#', /* # */ CHAR_HYPHEN_MINUS: '-', /* - */ CHAR_LEFT_ANGLE_BRACKET: '<', /* < */ CHAR_LEFT_CURLY_BRACE: '{', /* { */ CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */ CHAR_LINE_FEED: '\n', /* \n */ CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */ CHAR_PERCENT: '%', /* % */ CHAR_PLUS: '+', /* + */ CHAR_QUESTION_MARK: '?', /* ? */ CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */ CHAR_RIGHT_CURLY_BRACE: '}', /* } */ CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */ CHAR_SEMICOLON: ';', /* ; */ CHAR_SINGLE_QUOTE: '\'', /* ' */ CHAR_SPACE: ' ', /* */ CHAR_TAB: '\t', /* \t */ CHAR_UNDERSCORE: '_', /* _ */ CHAR_VERTICAL_LINE: '|', /* | */ CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */ }; /***/ }), /***/ 98050: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const fill = __webpack_require__(2664); const stringify = __webpack_require__(13349); const utils = __webpack_require__(73083); const append = (queue = '', stash = '', enclose = false) => { const result = []; queue = [].concat(queue); stash = [].concat(stash); if (!stash.length) return queue; if (!queue.length) { return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash; } for (const item of queue) { if (Array.isArray(item)) { for (const value of item) { result.push(append(value, stash, enclose)); } } else { for (let ele of stash) { if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele); } } } return utils.flatten(result); }; const expand = (ast, options = {}) => { const rangeLimit = options.rangeLimit === undefined ? 1000 : options.rangeLimit; const walk = (node, parent = {}) => { node.queue = []; let p = parent; let q = parent.queue; while (p.type !== 'brace' && p.type !== 'root' && p.parent) { p = p.parent; q = p.queue; } if (node.invalid || node.dollar) { q.push(append(q.pop(), stringify(node, options))); return; } if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) { q.push(append(q.pop(), ['{}'])); return; } if (node.nodes && node.ranges > 0) { const args = utils.reduce(node.nodes); if (utils.exceedsLimit(...args, options.step, rangeLimit)) { throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); } let range = fill(...args, options); if (range.length === 0) { range = stringify(node, options); } q.push(append(q.pop(), range)); node.nodes = []; return; } const enclose = utils.encloseBrace(node); let queue = node.queue; let block = node; while (block.type !== 'brace' && block.type !== 'root' && block.parent) { block = block.parent; queue = block.queue; } for (let i = 0; i < node.nodes.length; i++) { const child = node.nodes[i]; if (child.type === 'comma' && node.type === 'brace') { if (i === 1) queue.push(''); queue.push(''); continue; } if (child.type === 'close') { q.push(append(q.pop(), queue, enclose)); continue; } if (child.value && child.type !== 'open') { queue.push(append(queue.pop(), child.value)); continue; } if (child.nodes) { walk(child, node); } } return queue; }; return utils.flatten(walk(ast)); }; module.exports = expand; /***/ }), /***/ 94339: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const stringify = __webpack_require__(13349); /** * Constants */ const { MAX_LENGTH, CHAR_BACKSLASH, /* \ */ CHAR_BACKTICK, /* ` */ CHAR_COMMA, /* , */ CHAR_DOT, /* . */ CHAR_LEFT_PARENTHESES, /* ( */ CHAR_RIGHT_PARENTHESES, /* ) */ CHAR_LEFT_CURLY_BRACE, /* { */ CHAR_RIGHT_CURLY_BRACE, /* } */ CHAR_LEFT_SQUARE_BRACKET, /* [ */ CHAR_RIGHT_SQUARE_BRACKET, /* ] */ CHAR_DOUBLE_QUOTE, /* " */ CHAR_SINGLE_QUOTE, /* ' */ CHAR_NO_BREAK_SPACE, CHAR_ZERO_WIDTH_NOBREAK_SPACE } = __webpack_require__(86611); /** * parse */ const parse = (input, options = {}) => { if (typeof input !== 'string') { throw new TypeError('Expected a string'); } const opts = options || {}; const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; if (input.length > max) { throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); } const ast = { type: 'root', input, nodes: [] }; const stack = [ast]; let block = ast; let prev = ast; let brackets = 0; const length = input.length; let index = 0; let depth = 0; let value; /** * Helpers */ const advance = () => input[index++]; const push = node => { if (node.type === 'text' && prev.type === 'dot') { prev.type = 'text'; } if (prev && prev.type === 'text' && node.type === 'text') { prev.value += node.value; return; } block.nodes.push(node); node.parent = block; node.prev = prev; prev = node; return node; }; push({ type: 'bos' }); while (index < length) { block = stack[stack.length - 1]; value = advance(); /** * Invalid chars */ if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { continue; } /** * Escaped chars */ if (value === CHAR_BACKSLASH) { push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() }); continue; } /** * Right square bracket (literal): ']' */ if (value === CHAR_RIGHT_SQUARE_BRACKET) { push({ type: 'text', value: '\\' + value }); continue; } /** * Left square bracket: '[' */ if (value === CHAR_LEFT_SQUARE_BRACKET) { brackets++; let next; while (index < length && (next = advance())) { value += next; if (next === CHAR_LEFT_SQUARE_BRACKET) { brackets++; continue; } if (next === CHAR_BACKSLASH) { value += advance(); continue; } if (next === CHAR_RIGHT_SQUARE_BRACKET) { brackets--; if (brackets === 0) { break; } } } push({ type: 'text', value }); continue; } /** * Parentheses */ if (value === CHAR_LEFT_PARENTHESES) { block = push({ type: 'paren', nodes: [] }); stack.push(block); push({ type: 'text', value }); continue; } if (value === CHAR_RIGHT_PARENTHESES) { if (block.type !== 'paren') { push({ type: 'text', value }); continue; } block = stack.pop(); push({ type: 'text', value }); block = stack[stack.length - 1]; continue; } /** * Quotes: '|"|` */ if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { const open = value; let next; if (options.keepQuotes !== true) { value = ''; } while (index < length && (next = advance())) { if (next === CHAR_BACKSLASH) { value += next + advance(); continue; } if (next === open) { if (options.keepQuotes === true) value += next; break; } value += next; } push({ type: 'text', value }); continue; } /** * Left curly brace: '{' */ if (value === CHAR_LEFT_CURLY_BRACE) { depth++; const dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; const brace = { type: 'brace', open: true, close: false, dollar, depth, commas: 0, ranges: 0, nodes: [] }; block = push(brace); stack.push(block); push({ type: 'open', value }); continue; } /** * Right curly brace: '}' */ if (value === CHAR_RIGHT_CURLY_BRACE) { if (block.type !== 'brace') { push({ type: 'text', value }); continue; } const type = 'close'; block = stack.pop(); block.close = true; push({ type, value }); depth--; block = stack[stack.length - 1]; continue; } /** * Comma: ',' */ if (value === CHAR_COMMA && depth > 0) { if (block.ranges > 0) { block.ranges = 0; const open = block.nodes.shift(); block.nodes = [open, { type: 'text', value: stringify(block) }]; } push({ type: 'comma', value }); block.commas++; continue; } /** * Dot: '.' */ if (value === CHAR_DOT && depth > 0 && block.commas === 0) { const siblings = block.nodes; if (depth === 0 || siblings.length === 0) { push({ type: 'text', value }); continue; } if (prev.type === 'dot') { block.range = []; prev.value += value; prev.type = 'range'; if (block.nodes.length !== 3 && block.nodes.length !== 5) { block.invalid = true; block.ranges = 0; prev.type = 'text'; continue; } block.ranges++; block.args = []; continue; } if (prev.type === 'range') { siblings.pop(); const before = siblings[siblings.length - 1]; before.value += prev.value + value; prev = before; block.ranges--; continue; } push({ type: 'dot', value }); continue; } /** * Text */ push({ type: 'text', value }); } // Mark imbalanced braces and brackets as invalid do { block = stack.pop(); if (block.type !== 'root') { block.nodes.forEach(node => { if (!node.nodes) { if (node.type === 'open') node.isOpen = true; if (node.type === 'close') node.isClose = true; if (!node.nodes) node.type = 'text'; node.invalid = true; } }); // get the location of the block on parent.nodes (block's siblings) const parent = stack[stack.length - 1]; const index = parent.nodes.indexOf(block); // replace the (invalid) block with it's nodes parent.nodes.splice(index, 1, ...block.nodes); } } while (stack.length > 0); push({ type: 'eos' }); return ast; }; module.exports = parse; /***/ }), /***/ 13349: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const utils = __webpack_require__(73083); module.exports = (ast, options = {}) => { const stringify = (node, parent = {}) => { const invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent); const invalidNode = node.invalid === true && options.escapeInvalid === true; let output = ''; if (node.value) { if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) { return '\\' + node.value; } return node.value; } if (node.value) { return node.value; } if (node.nodes) { for (const child of node.nodes) { output += stringify(child); } } return output; }; return stringify(ast); }; /***/ }), /***/ 73083: /***/ ((__unused_webpack_module, exports) => { "use strict"; exports.isInteger = num => { if (typeof num === 'number') { return Number.isInteger(num); } if (typeof num === 'string' && num.trim() !== '') { return Number.isInteger(Number(num)); } return false; }; /** * Find a node of the given type */ exports.find = (node, type) => node.nodes.find(node => node.type === type); /** * Find a node of the given type */ exports.exceedsLimit = (min, max, step = 1, limit) => { if (limit === false) return false; if (!exports.isInteger(min) || !exports.isInteger(max)) return false; return ((Number(max) - Number(min)) / Number(step)) >= limit; }; /** * Escape the given node with '\\' before node.value */ exports.escapeNode = (block, n = 0, type) => { const node = block.nodes[n]; if (!node) return; if ((type && node.type === type) || node.type === 'open' || node.type === 'close') { if (node.escaped !== true) { node.value = '\\' + node.value; node.escaped = true; } } }; /** * Returns true if the given brace node should be enclosed in literal braces */ exports.encloseBrace = node => { if (node.type !== 'brace') return false; if ((node.commas >> 0 + node.ranges >> 0) === 0) { node.invalid = true; return true; } return false; }; /** * Returns true if a brace node is invalid. */ exports.isInvalidBrace = block => { if (block.type !== 'brace') return false; if (block.invalid === true || block.dollar) return true; if ((block.commas >> 0 + block.ranges >> 0) === 0) { block.invalid = true; return true; } if (block.open !== true || block.close !== true) { block.invalid = true; return true; } return false; }; /** * Returns true if a node is an open or close node */ exports.isOpenOrClose = node => { if (node.type === 'open' || node.type === 'close') { return true; } return node.open === true || node.close === true; }; /** * Reduce an array of text nodes. */ exports.reduce = nodes => nodes.reduce((acc, node) => { if (node.type === 'text') acc.push(node.value); if (node.type === 'range') node.type = 'text'; return acc; }, []); /** * Flatten an array */ exports.flatten = (...args) => { const result = []; const flat = arr => { for (let i = 0; i < arr.length; i++) { const ele = arr[i]; if (Array.isArray(ele)) { flat(ele); continue; } if (ele !== undefined) { result.push(ele); } } return result; }; flat(args); return result; }; /***/ }), /***/ 55420: /***/ ((module) => { /* eslint-disable node/no-deprecated-api */ var toString = Object.prototype.toString var isModern = ( typeof Buffer !== 'undefined' && typeof Buffer.alloc === 'function' && typeof Buffer.allocUnsafe === 'function' && typeof Buffer.from === 'function' ) function isArrayBuffer (input) { return toString.call(input).slice(8, -1) === 'ArrayBuffer' } function fromArrayBuffer (obj, byteOffset, length) { byteOffset >>>= 0 var maxLength = obj.byteLength - byteOffset if (maxLength < 0) { throw new RangeError("'offset' is out of bounds") } if (length === undefined) { length = maxLength } else { length >>>= 0 if (length > maxLength) { throw new RangeError("'length' is out of bounds") } } return isModern ? Buffer.from(obj.slice(byteOffset, byteOffset + length)) : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length))) } function fromString (string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8' } if (!Buffer.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } return isModern ? Buffer.from(string, encoding) : new Buffer(string, encoding) } function bufferFrom (value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } if (isArrayBuffer(value)) { return fromArrayBuffer(value, encodingOrOffset, length) } if (typeof value === 'string') { return fromString(value, encodingOrOffset) } return isModern ? Buffer.from(value) : new Buffer(value) } module.exports = bufferFrom /***/ }), /***/ 78397: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const { V4MAPPED, ADDRCONFIG, ALL, promises: { Resolver: AsyncResolver }, lookup: dnsLookup } = __webpack_require__(9523); const {promisify} = __webpack_require__(73837); const os = __webpack_require__(22037); const kCacheableLookupCreateConnection = Symbol('cacheableLookupCreateConnection'); const kCacheableLookupInstance = Symbol('cacheableLookupInstance'); const kExpires = Symbol('expires'); const supportsALL = typeof ALL === 'number'; const verifyAgent = agent => { if (!(agent && typeof agent.createConnection === 'function')) { throw new Error('Expected an Agent instance as the first argument'); } }; const map4to6 = entries => { for (const entry of entries) { if (entry.family === 6) { continue; } entry.address = `::ffff:${entry.address}`; entry.family = 6; } }; const getIfaceInfo = () => { let has4 = false; let has6 = false; for (const device of Object.values(os.networkInterfaces())) { for (const iface of device) { if (iface.internal) { continue; } if (iface.family === 'IPv6') { has6 = true; } else { has4 = true; } if (has4 && has6) { return {has4, has6}; } } } return {has4, has6}; }; const isIterable = map => { return Symbol.iterator in map; }; const ttl = {ttl: true}; const all = {all: true}; class CacheableLookup { constructor({ cache = new Map(), maxTtl = Infinity, fallbackDuration = 3600, errorTtl = 0.15, resolver = new AsyncResolver(), lookup = dnsLookup } = {}) { this.maxTtl = maxTtl; this.errorTtl = errorTtl; this._cache = cache; this._resolver = resolver; this._dnsLookup = promisify(lookup); if (this._resolver instanceof AsyncResolver) { this._resolve4 = this._resolver.resolve4.bind(this._resolver); this._resolve6 = this._resolver.resolve6.bind(this._resolver); } else { this._resolve4 = promisify(this._resolver.resolve4.bind(this._resolver)); this._resolve6 = promisify(this._resolver.resolve6.bind(this._resolver)); } this._iface = getIfaceInfo(); this._pending = {}; this._nextRemovalTime = false; this._hostnamesToFallback = new Set(); if (fallbackDuration < 1) { this._fallback = false; } else { this._fallback = true; const interval = setInterval(() => { this._hostnamesToFallback.clear(); }, fallbackDuration * 1000); /* istanbul ignore next: There is no `interval.unref()` when running inside an Electron renderer */ if (interval.unref) { interval.unref(); } } this.lookup = this.lookup.bind(this); this.lookupAsync = this.lookupAsync.bind(this); } set servers(servers) { this.clear(); this._resolver.setServers(servers); } get servers() { return this._resolver.getServers(); } lookup(hostname, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } else if (typeof options === 'number') { options = { family: options }; } if (!callback) { throw new Error('Callback must be a function.'); } // eslint-disable-next-line promise/prefer-await-to-then this.lookupAsync(hostname, options).then(result => { if (options.all) { callback(null, result); } else { callback(null, result.address, result.family, result.expires, result.ttl); } }, callback); } async lookupAsync(hostname, options = {}) { if (typeof options === 'number') { options = { family: options }; } let cached = await this.query(hostname); if (options.family === 6) { const filtered = cached.filter(entry => entry.family === 6); if (options.hints & V4MAPPED) { if ((supportsALL && options.hints & ALL) || filtered.length === 0) { map4to6(cached); } else { cached = filtered; } } else { cached = filtered; } } else if (options.family === 4) { cached = cached.filter(entry => entry.family === 4); } if (options.hints & ADDRCONFIG) { const {_iface} = this; cached = cached.filter(entry => entry.family === 6 ? _iface.has6 : _iface.has4); } if (cached.length === 0) { const error = new Error(`cacheableLookup ENOTFOUND ${hostname}`); error.code = 'ENOTFOUND'; error.hostname = hostname; throw error; } if (options.all) { return cached; } return cached[0]; } async query(hostname) { let cached = await this._cache.get(hostname); if (!cached) { const pending = this._pending[hostname]; if (pending) { cached = await pending; } else { const newPromise = this.queryAndCache(hostname); this._pending[hostname] = newPromise; try { cached = await newPromise; } finally { delete this._pending[hostname]; } } } cached = cached.map(entry => { return {...entry}; }); return cached; } async _resolve(hostname) { const wrap = async promise => { try { return await promise; } catch (error) { if (error.code === 'ENODATA' || error.code === 'ENOTFOUND') { return []; } throw error; } }; // ANY is unsafe as it doesn't trigger new queries in the underlying server. const [A, AAAA] = await Promise.all([ this._resolve4(hostname, ttl), this._resolve6(hostname, ttl) ].map(promise => wrap(promise))); let aTtl = 0; let aaaaTtl = 0; let cacheTtl = 0; const now = Date.now(); for (const entry of A) { entry.family = 4; entry.expires = now + (entry.ttl * 1000); aTtl = Math.max(aTtl, entry.ttl); } for (const entry of AAAA) { entry.family = 6; entry.expires = now + (entry.ttl * 1000); aaaaTtl = Math.max(aaaaTtl, entry.ttl); } if (A.length > 0) { if (AAAA.length > 0) { cacheTtl = Math.min(aTtl, aaaaTtl); } else { cacheTtl = aTtl; } } else { cacheTtl = aaaaTtl; } return { entries: [ ...A, ...AAAA ], cacheTtl }; } async _lookup(hostname) { try { const entries = await this._dnsLookup(hostname, { all: true }); return { entries, cacheTtl: 0 }; } catch (_) { return { entries: [], cacheTtl: 0 }; } } async _set(hostname, data, cacheTtl) { if (this.maxTtl > 0 && cacheTtl > 0) { cacheTtl = Math.min(cacheTtl, this.maxTtl) * 1000; data[kExpires] = Date.now() + cacheTtl; try { await this._cache.set(hostname, data, cacheTtl); } catch (error) { this.lookupAsync = async () => { const cacheError = new Error('Cache Error. Please recreate the CacheableLookup instance.'); cacheError.cause = error; throw cacheError; }; } if (isIterable(this._cache)) { this._tick(cacheTtl); } } } async queryAndCache(hostname) { if (this._hostnamesToFallback.has(hostname)) { return this._dnsLookup(hostname, all); } let query = await this._resolve(hostname); if (query.entries.length === 0 && this._fallback) { query = await this._lookup(hostname); if (query.entries.length !== 0) { // Use `dns.lookup(...)` for that particular hostname this._hostnamesToFallback.add(hostname); } } const cacheTtl = query.entries.length === 0 ? this.errorTtl : query.cacheTtl; await this._set(hostname, query.entries, cacheTtl); return query.entries; } _tick(ms) { const nextRemovalTime = this._nextRemovalTime; if (!nextRemovalTime || ms < nextRemovalTime) { clearTimeout(this._removalTimeout); this._nextRemovalTime = ms; this._removalTimeout = setTimeout(() => { this._nextRemovalTime = false; let nextExpiry = Infinity; const now = Date.now(); for (const [hostname, entries] of this._cache) { const expires = entries[kExpires]; if (now >= expires) { this._cache.delete(hostname); } else if (expires < nextExpiry) { nextExpiry = expires; } } if (nextExpiry !== Infinity) { this._tick(nextExpiry - now); } }, ms); /* istanbul ignore next: There is no `timeout.unref()` when running inside an Electron renderer */ if (this._removalTimeout.unref) { this._removalTimeout.unref(); } } } install(agent) { verifyAgent(agent); if (kCacheableLookupCreateConnection in agent) { throw new Error('CacheableLookup has been already installed'); } agent[kCacheableLookupCreateConnection] = agent.createConnection; agent[kCacheableLookupInstance] = this; agent.createConnection = (options, callback) => { if (!('lookup' in options)) { options.lookup = this.lookup; } return agent[kCacheableLookupCreateConnection](options, callback); }; } uninstall(agent) { verifyAgent(agent); if (agent[kCacheableLookupCreateConnection]) { if (agent[kCacheableLookupInstance] !== this) { throw new Error('The agent is not owned by this CacheableLookup instance'); } agent.createConnection = agent[kCacheableLookupCreateConnection]; delete agent[kCacheableLookupCreateConnection]; delete agent[kCacheableLookupInstance]; } } updateInterfaceInfo() { const {_iface} = this; this._iface = getIfaceInfo(); if ((_iface.has4 && !this._iface.has4) || (_iface.has6 && !this._iface.has6)) { this._cache.clear(); } } clear(hostname) { if (hostname) { this._cache.delete(hostname); return; } this._cache.clear(); } } module.exports = CacheableLookup; module.exports["default"] = CacheableLookup; /***/ }), /***/ 20490: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const {PassThrough: PassThroughStream} = __webpack_require__(12781); module.exports = options => { options = {...options}; const {array} = options; let {encoding} = options; const isBuffer = encoding === 'buffer'; let objectMode = false; if (array) { objectMode = !(encoding || isBuffer); } else { encoding = encoding || 'utf8'; } if (isBuffer) { encoding = null; } const stream = new PassThroughStream({objectMode}); if (encoding) { stream.setEncoding(encoding); } let length = 0; const chunks = []; stream.on('data', chunk => { chunks.push(chunk); if (objectMode) { length = chunks.length; } else { length += chunk.length; } }); stream.getBufferedValue = () => { if (array) { return chunks; } return isBuffer ? Buffer.concat(chunks, length) : chunks.join(''); }; stream.getBufferedLength = () => length; return stream; }; /***/ }), /***/ 50404: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const {constants: BufferConstants} = __webpack_require__(14300); const pump = __webpack_require__(74286); const bufferStream = __webpack_require__(20490); class MaxBufferError extends Error { constructor() { super('maxBuffer exceeded'); this.name = 'MaxBufferError'; } } async function getStream(inputStream, options) { if (!inputStream) { return Promise.reject(new Error('Expected a stream')); } options = { maxBuffer: Infinity, ...options }; const {maxBuffer} = options; let stream; await new Promise((resolve, reject) => { const rejectPromise = error => { // Don't retrieve an oversized buffer. if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) { error.bufferedData = stream.getBufferedValue(); } reject(error); }; stream = pump(inputStream, bufferStream(options), error => { if (error) { rejectPromise(error); return; } resolve(); }); stream.on('data', () => { if (stream.getBufferedLength() > maxBuffer) { rejectPromise(new MaxBufferError()); } }); }); return stream.getBufferedValue(); } module.exports = getStream; // TODO: Remove this for the next major release module.exports["default"] = getStream; module.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'}); module.exports.array = (stream, options) => getStream(stream, {...options, array: true}); module.exports.MaxBufferError = MaxBufferError; /***/ }), /***/ 93481: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const EventEmitter = __webpack_require__(82361); const urlLib = __webpack_require__(57310); const normalizeUrl = __webpack_require__(40015); const getStream = __webpack_require__(50404); const CachePolicy = __webpack_require__(26214); const Response = __webpack_require__(24259); const lowercaseKeys = __webpack_require__(25989); const cloneResponse = __webpack_require__(79715); const Keyv = __webpack_require__(64958); class CacheableRequest { constructor(request, cacheAdapter) { if (typeof request !== 'function') { throw new TypeError('Parameter `request` must be a function'); } this.cache = new Keyv({ uri: typeof cacheAdapter === 'string' && cacheAdapter, store: typeof cacheAdapter !== 'string' && cacheAdapter, namespace: 'cacheable-request' }); return this.createCacheableRequest(request); } createCacheableRequest(request) { return (opts, cb) => { let url; if (typeof opts === 'string') { url = normalizeUrlObject(urlLib.parse(opts)); opts = {}; } else if (opts instanceof urlLib.URL) { url = normalizeUrlObject(urlLib.parse(opts.toString())); opts = {}; } else { const [pathname, ...searchParts] = (opts.path || '').split('?'); const search = searchParts.length > 0 ? `?${searchParts.join('?')}` : ''; url = normalizeUrlObject({ ...opts, pathname, search }); } opts = { headers: {}, method: 'GET', cache: true, strictTtl: false, automaticFailover: false, ...opts, ...urlObjectToRequestOptions(url) }; opts.headers = lowercaseKeys(opts.headers); const ee = new EventEmitter(); const normalizedUrlString = normalizeUrl( urlLib.format(url), { stripWWW: false, removeTrailingSlash: false, stripAuthentication: false } ); const key = `${opts.method}:${normalizedUrlString}`; let revalidate = false; let madeRequest = false; const makeRequest = opts => { madeRequest = true; let requestErrored = false; let requestErrorCallback; const requestErrorPromise = new Promise(resolve => { requestErrorCallback = () => { if (!requestErrored) { requestErrored = true; resolve(); } }; }); const handler = response => { if (revalidate && !opts.forceRefresh) { response.status = response.statusCode; const revalidatedPolicy = CachePolicy.fromObject(revalidate.cachePolicy).revalidatedPolicy(opts, response); if (!revalidatedPolicy.modified) { const headers = revalidatedPolicy.policy.responseHeaders(); response = new Response(revalidate.statusCode, headers, revalidate.body, revalidate.url); response.cachePolicy = revalidatedPolicy.policy; response.fromCache = true; } } if (!response.fromCache) { response.cachePolicy = new CachePolicy(opts, response, opts); response.fromCache = false; } let clonedResponse; if (opts.cache && response.cachePolicy.storable()) { clonedResponse = cloneResponse(response); (async () => { try { const bodyPromise = getStream.buffer(response); await Promise.race([ requestErrorPromise, new Promise(resolve => response.once('end', resolve)) ]); if (requestErrored) { return; } const body = await bodyPromise; const value = { cachePolicy: response.cachePolicy.toObject(), url: response.url, statusCode: response.fromCache ? revalidate.statusCode : response.statusCode, body }; let ttl = opts.strictTtl ? response.cachePolicy.timeToLive() : undefined; if (opts.maxTtl) { ttl = ttl ? Math.min(ttl, opts.maxTtl) : opts.maxTtl; } await this.cache.set(key, value, ttl); } catch (error) { ee.emit('error', new CacheableRequest.CacheError(error)); } })(); } else if (opts.cache && revalidate) { (async () => { try { await this.cache.delete(key); } catch (error) { ee.emit('error', new CacheableRequest.CacheError(error)); } })(); } ee.emit('response', clonedResponse || response); if (typeof cb === 'function') { cb(clonedResponse || response); } }; try { const req = request(opts, handler); req.once('error', requestErrorCallback); req.once('abort', requestErrorCallback); ee.emit('request', req); } catch (error) { ee.emit('error', new CacheableRequest.RequestError(error)); } }; (async () => { const get = async opts => { await Promise.resolve(); const cacheEntry = opts.cache ? await this.cache.get(key) : undefined; if (typeof cacheEntry === 'undefined') { return makeRequest(opts); } const policy = CachePolicy.fromObject(cacheEntry.cachePolicy); if (policy.satisfiesWithoutRevalidation(opts) && !opts.forceRefresh) { const headers = policy.responseHeaders(); const response = new Response(cacheEntry.statusCode, headers, cacheEntry.body, cacheEntry.url); response.cachePolicy = policy; response.fromCache = true; ee.emit('response', response); if (typeof cb === 'function') { cb(response); } } else { revalidate = cacheEntry; opts.headers = policy.revalidationHeaders(opts); makeRequest(opts); } }; const errorHandler = error => ee.emit('error', new CacheableRequest.CacheError(error)); this.cache.once('error', errorHandler); ee.on('response', () => this.cache.removeListener('error', errorHandler)); try { await get(opts); } catch (error) { if (opts.automaticFailover && !madeRequest) { makeRequest(opts); } ee.emit('error', new CacheableRequest.CacheError(error)); } })(); return ee; }; } } function urlObjectToRequestOptions(url) { const options = { ...url }; options.path = `${url.pathname || '/'}${url.search || ''}`; delete options.pathname; delete options.search; return options; } function normalizeUrlObject(url) { // If url was parsed by url.parse or new URL: // - hostname will be set // - host will be hostname[:port] // - port will be set if it was explicit in the parsed string // Otherwise, url was from request options: // - hostname or host may be set // - host shall not have port encoded return { protocol: url.protocol, auth: url.auth, hostname: url.hostname || url.host || 'localhost', port: url.port, pathname: url.pathname, search: url.search }; } CacheableRequest.RequestError = class extends Error { constructor(error) { super(error.message); this.name = 'RequestError'; Object.assign(this, error); } }; CacheableRequest.CacheError = class extends Error { constructor(error) { super(error.message); this.name = 'CacheError'; Object.assign(this, error); } }; module.exports = CacheableRequest; /***/ }), /***/ 75281: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const os = __webpack_require__(22037); const extractPathRegex = /\s+at.*(?:\(|\s)(.*)\)?/; const pathRegex = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/; const homeDir = typeof os.homedir === 'undefined' ? '' : os.homedir(); module.exports = (stack, options) => { options = Object.assign({pretty: false}, options); return stack.replace(/\\/g, '/') .split('\n') .filter(line => { const pathMatches = line.match(extractPathRegex); if (pathMatches === null || !pathMatches[1]) { return true; } const match = pathMatches[1]; // Electron if ( match.includes('.app/Contents/Resources/electron.asar') || match.includes('.app/Contents/Resources/default_app.asar') ) { return false; } return !pathRegex.test(match); }) .filter(line => line.trim() !== '') .map(line => { if (options.pretty) { return line.replace(extractPathRegex, (m, p1) => m.replace(p1, p1.replace(homeDir, '~'))); } return line; }) .join('\n'); }; /***/ }), /***/ 87730: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const NODE_INITIAL = 0; const NODE_SUCCESS = 1; const NODE_ERRORED = 2; const START_OF_INPUT = `\u0001`; const END_OF_INPUT = `\u0000`; const HELP_COMMAND_INDEX = -1; const HELP_REGEX = /^(-h|--help)(?:=([0-9]+))?$/; const OPTION_REGEX = /^(--[a-z]+(?:-[a-z]+)*|-[a-zA-Z]+)$/; const BATCH_REGEX = /^-[a-zA-Z]{2,}$/; const BINDING_REGEX = /^([^=]+)=([\s\S]*)$/; const DEBUG = process.env.DEBUG_CLI === `1`; /** * A generic usage error with the name `UsageError`. * * It should be used over `Error` only when it's the user's fault. */ class UsageError extends Error { constructor(message) { super(message); this.clipanion = { type: `usage` }; this.name = `UsageError`; } } class UnknownSyntaxError extends Error { constructor(input, candidates) { super(); this.input = input; this.candidates = candidates; this.clipanion = { type: `none` }; this.name = `UnknownSyntaxError`; if (this.candidates.length === 0) { this.message = `Command not found, but we're not sure what's the alternative.`; } else if (this.candidates.length === 1 && this.candidates[0].reason !== null) { const [{ usage, reason }] = this.candidates; this.message = `${reason}\n\n$ ${usage}`; } else if (this.candidates.length === 1) { const [{ usage }] = this.candidates; this.message = `Command not found; did you mean:\n\n$ ${usage}\n${whileRunning(input)}`; } else { this.message = `Command not found; did you mean one of:\n\n${this.candidates.map(({ usage }, index) => { return `${`${index}.`.padStart(4)} ${usage}`; }).join(`\n`)}\n\n${whileRunning(input)}`; } } } class AmbiguousSyntaxError extends Error { constructor(input, usages) { super(); this.input = input; this.usages = usages; this.clipanion = { type: `none` }; this.name = `AmbiguousSyntaxError`; this.message = `Cannot find who to pick amongst the following alternatives:\n\n${this.usages.map((usage, index) => { return `${`${index}.`.padStart(4)} ${usage}`; }).join(`\n`)}\n\n${whileRunning(input)}`; } } const whileRunning = (input) => `While running ${input.filter(token => { return token !== END_OF_INPUT; }).map(token => { const json = JSON.stringify(token); if (token.match(/\s/) || token.length === 0 || json !== `"${token}"`) { return json; } else { return token; } }).join(` `)}`; // ------------------------------------------------------------------------ function debug(str) { if (DEBUG) { console.log(str); } } const basicHelpState = { candidateUsage: null, errorMessage: null, ignoreOptions: false, path: [], positionals: [], options: [], remainder: null, selectedIndex: HELP_COMMAND_INDEX }; function makeStateMachine() { return { nodes: [makeNode(), makeNode(), makeNode()], }; } function makeAnyOfMachine(inputs) { const output = makeStateMachine(); const heads = []; let offset = output.nodes.length; for (const input of inputs) { heads.push(offset); for (let t = 0; t < input.nodes.length; ++t) if (!isTerminalNode(t)) output.nodes.push(cloneNode(input.nodes[t], offset)); offset += input.nodes.length - 2; } for (const head of heads) registerShortcut(output, NODE_INITIAL, head); return output; } function injectNode(machine, node) { machine.nodes.push(node); return machine.nodes.length - 1; } function simplifyMachine(input) { const visited = new Set(); const process = (node) => { if (visited.has(node)) return; visited.add(node); const nodeDef = input.nodes[node]; for (const transitions of Object.values(nodeDef.statics)) for (const { to } of transitions) process(to); for (const [, { to }] of nodeDef.dynamics) process(to); for (const { to } of nodeDef.shortcuts) process(to); const shortcuts = new Set(nodeDef.shortcuts.map(({ to }) => to)); while (nodeDef.shortcuts.length > 0) { const { to } = nodeDef.shortcuts.shift(); const toDef = input.nodes[to]; for (const [segment, transitions] of Object.entries(toDef.statics)) { let store = !Object.prototype.hasOwnProperty.call(nodeDef.statics, segment) ? nodeDef.statics[segment] = [] : nodeDef.statics[segment]; for (const transition of transitions) { if (!store.some(({ to }) => transition.to === to)) { store.push(transition); } } } for (const [test, transition] of toDef.dynamics) if (!nodeDef.dynamics.some(([otherTest, { to }]) => test === otherTest && transition.to === to)) nodeDef.dynamics.push([test, transition]); for (const transition of toDef.shortcuts) { if (!shortcuts.has(transition.to)) { nodeDef.shortcuts.push(transition); shortcuts.add(transition.to); } } } }; process(NODE_INITIAL); } function debugMachine(machine, { prefix = `` } = {}) { debug(`${prefix}Nodes are:`); for (let t = 0; t < machine.nodes.length; ++t) { debug(`${prefix} ${t}: ${JSON.stringify(machine.nodes[t])}`); } } function runMachineInternal(machine, input, partial = false) { debug(`Running a vm on ${JSON.stringify(input)}`); let branches = [{ node: NODE_INITIAL, state: { candidateUsage: null, errorMessage: null, ignoreOptions: false, options: [], path: [], positionals: [], remainder: null, selectedIndex: null, } }]; debugMachine(machine, { prefix: ` ` }); const tokens = [START_OF_INPUT, ...input]; for (let t = 0; t < tokens.length; ++t) { const segment = tokens[t]; debug(` Processing ${JSON.stringify(segment)}`); const nextBranches = []; for (const { node, state } of branches) { debug(` Current node is ${node}`); const nodeDef = machine.nodes[node]; if (node === NODE_ERRORED) { nextBranches.push({ node, state }); continue; } console.assert(nodeDef.shortcuts.length === 0, `Shortcuts should have been eliminated by now`); const hasExactMatch = Object.prototype.hasOwnProperty.call(nodeDef.statics, segment); if (!partial || t < tokens.length - 1 || hasExactMatch) { if (hasExactMatch) { const transitions = nodeDef.statics[segment]; for (const { to, reducer } of transitions) { nextBranches.push({ node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment) : state }); debug(` Static transition to ${to} found`); } } else { debug(` No static transition found`); } } else { let hasMatches = false; for (const candidate of Object.keys(nodeDef.statics)) { if (!candidate.startsWith(segment)) continue; if (segment === candidate) { for (const { to, reducer } of nodeDef.statics[candidate]) { nextBranches.push({ node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment) : state }); debug(` Static transition to ${to} found`); } } else { for (const { to, reducer } of nodeDef.statics[candidate]) { nextBranches.push({ node: to, state: Object.assign(Object.assign({}, state), { remainder: candidate.slice(segment.length) }) }); debug(` Static transition to ${to} found (partial match)`); } } hasMatches = true; } if (!hasMatches) { debug(` No partial static transition found`); } } if (segment !== END_OF_INPUT) { for (const [test, { to, reducer }] of nodeDef.dynamics) { if (execute(tests, test, state, segment)) { nextBranches.push({ node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment) : state }); debug(` Dynamic transition to ${to} found (via ${test})`); } } } } if (nextBranches.length === 0 && segment === END_OF_INPUT && input.length === 1) { return [{ node: NODE_INITIAL, state: basicHelpState, }]; } if (nextBranches.length === 0) { throw new UnknownSyntaxError(input, branches.filter(({ node }) => { return node !== NODE_ERRORED; }).map(({ state }) => { return { usage: state.candidateUsage, reason: null }; })); } if (nextBranches.every(({ node }) => node === NODE_ERRORED)) { throw new UnknownSyntaxError(input, nextBranches.map(({ state }) => { return { usage: state.candidateUsage, reason: state.errorMessage }; })); } branches = trimSmallerBranches(nextBranches); } if (branches.length > 0) { debug(` Results:`); for (const branch of branches) { debug(` - ${branch.node} -> ${JSON.stringify(branch.state)}`); } } else { debug(` No results`); } return branches; } function checkIfNodeIsFinished(node, state) { if (state.selectedIndex !== null) return true; if (Object.prototype.hasOwnProperty.call(node.statics, END_OF_INPUT)) for (const { to } of node.statics[END_OF_INPUT]) if (to === NODE_SUCCESS) return true; return false; } function suggestMachine(machine, input, partial) { // If we're accepting partial matches, then exact matches need to be // prefixed with an extra space. const prefix = partial && input.length > 0 ? [``] : []; const branches = runMachineInternal(machine, input, partial); const suggestions = []; const suggestionsJson = new Set(); const traverseSuggestion = (suggestion, node, skipFirst = true) => { let nextNodes = [node]; while (nextNodes.length > 0) { const currentNodes = nextNodes; nextNodes = []; for (const node of currentNodes) { const nodeDef = machine.nodes[node]; const keys = Object.keys(nodeDef.statics); for (const key of Object.keys(nodeDef.statics)) { const segment = keys[0]; for (const { to, reducer } of nodeDef.statics[segment]) { if (reducer !== `pushPath`) continue; if (!skipFirst) suggestion.push(segment); nextNodes.push(to); } } } skipFirst = false; } const json = JSON.stringify(suggestion); if (suggestionsJson.has(json)) return; suggestions.push(suggestion); suggestionsJson.add(json); }; for (const { node, state } of branches) { if (state.remainder !== null) { traverseSuggestion([state.remainder], node); continue; } const nodeDef = machine.nodes[node]; const isFinished = checkIfNodeIsFinished(nodeDef, state); for (const [candidate, transitions] of Object.entries(nodeDef.statics)) if ((isFinished && candidate !== END_OF_INPUT) || (!candidate.startsWith(`-`) && transitions.some(({ reducer }) => reducer === `pushPath`))) traverseSuggestion([...prefix, candidate], node); if (!isFinished) continue; for (const [test, { to }] of nodeDef.dynamics) { if (to === NODE_ERRORED) continue; const tokens = suggest(test, state); if (tokens === null) continue; for (const token of tokens) { traverseSuggestion([...prefix, token], node); } } } return [...suggestions].sort(); } function runMachine(machine, input) { const branches = runMachineInternal(machine, [...input, END_OF_INPUT]); return selectBestState(input, branches.map(({ state }) => { return state; })); } function trimSmallerBranches(branches) { let maxPathSize = 0; for (const { state } of branches) if (state.path.length > maxPathSize) maxPathSize = state.path.length; return branches.filter(({ state }) => { return state.path.length === maxPathSize; }); } function selectBestState(input, states) { const terminalStates = states.filter(state => { return state.selectedIndex !== null; }); if (terminalStates.length === 0) throw new Error(); let maxPathSize = 0; for (const state of terminalStates) if (state.path.length > maxPathSize) maxPathSize = state.path.length; const bestPathBranches = terminalStates.filter(state => { return state.path.length === maxPathSize; }); const getPositionalCount = (state) => state.positionals.filter(({ extra }) => { return !extra; }).length + state.options.length; const statesWithPositionalCount = bestPathBranches.map(state => { return { state, positionalCount: getPositionalCount(state) }; }); let maxPositionalCount = 0; for (const { positionalCount } of statesWithPositionalCount) if (positionalCount > maxPositionalCount) maxPositionalCount = positionalCount; const bestPositionalStates = statesWithPositionalCount.filter(({ positionalCount }) => { return positionalCount === maxPositionalCount; }).map(({ state }) => { return state; }); const fixedStates = aggregateHelpStates(bestPositionalStates); if (fixedStates.length > 1) throw new AmbiguousSyntaxError(input, fixedStates.map(state => state.candidateUsage)); return fixedStates[0]; } function aggregateHelpStates(states) { const notHelps = []; const helps = []; for (const state of states) { if (state.selectedIndex === HELP_COMMAND_INDEX) { helps.push(state); } else { notHelps.push(state); } } if (helps.length > 0) { notHelps.push(Object.assign(Object.assign({}, basicHelpState), { path: findCommonPrefix(...helps.map(state => state.path)), options: helps.reduce((options, state) => options.concat(state.options), []) })); } return notHelps; } function findCommonPrefix(firstPath, secondPath, ...rest) { if (secondPath === undefined) return Array.from(firstPath); return findCommonPrefix(firstPath.filter((segment, i) => segment === secondPath[i]), ...rest); } function makeNode() { return { dynamics: [], shortcuts: [], statics: {}, }; } function isTerminalNode(node) { return node === NODE_SUCCESS || node === NODE_ERRORED; } function cloneTransition(input, offset = 0) { return { to: !isTerminalNode(input.to) ? input.to > 2 ? input.to + offset - 2 : input.to + offset : input.to, reducer: input.reducer, }; } function cloneNode(input, offset = 0) { const output = makeNode(); for (const [test, transition] of input.dynamics) output.dynamics.push([test, cloneTransition(transition, offset)]); for (const transition of input.shortcuts) output.shortcuts.push(cloneTransition(transition, offset)); for (const [segment, transitions] of Object.entries(input.statics)) output.statics[segment] = transitions.map(transition => cloneTransition(transition, offset)); return output; } function registerDynamic(machine, from, test, to, reducer) { machine.nodes[from].dynamics.push([ test, { to, reducer: reducer } ]); } function registerShortcut(machine, from, to, reducer) { machine.nodes[from].shortcuts.push({ to, reducer: reducer }); } function registerStatic(machine, from, test, to, reducer) { let store = !Object.prototype.hasOwnProperty.call(machine.nodes[from].statics, test) ? machine.nodes[from].statics[test] = [] : machine.nodes[from].statics[test]; store.push({ to, reducer: reducer }); } function execute(store, callback, state, segment) { // TypeScript's control flow can't properly narrow // generic conditionals for some mysterious reason if (Array.isArray(callback)) { const [name, ...args] = callback; return store[name](state, segment, ...args); } else { return store[callback](state, segment); } } function suggest(callback, state) { const fn = Array.isArray(callback) ? tests[callback[0]] : tests[callback]; // @ts-ignore if (typeof fn.suggest === `undefined`) return null; const args = Array.isArray(callback) ? callback.slice(1) : []; // @ts-ignore return fn.suggest(state, ...args); } const tests = { always: () => { return true; }, isOptionLike: (state, segment) => { return !state.ignoreOptions && segment.startsWith(`-`); }, isNotOptionLike: (state, segment) => { return state.ignoreOptions || !segment.startsWith(`-`); }, isOption: (state, segment, name, hidden) => { return !state.ignoreOptions && segment === name; }, isBatchOption: (state, segment, names) => { return !state.ignoreOptions && BATCH_REGEX.test(segment) && [...segment.slice(1)].every(name => names.includes(`-${name}`)); }, isBoundOption: (state, segment, names, options) => { const optionParsing = segment.match(BINDING_REGEX); return !state.ignoreOptions && !!optionParsing && OPTION_REGEX.test(optionParsing[1]) && names.includes(optionParsing[1]) // Disallow bound options with no arguments (i.e. booleans) && options.filter(opt => opt.names.includes(optionParsing[1])).every(opt => opt.allowBinding); }, isNegatedOption: (state, segment, name) => { return !state.ignoreOptions && segment === `--no-${name.slice(2)}`; }, isHelp: (state, segment) => { return !state.ignoreOptions && HELP_REGEX.test(segment); }, isUnsupportedOption: (state, segment, names) => { return !state.ignoreOptions && segment.startsWith(`-`) && OPTION_REGEX.test(segment) && !names.includes(segment); }, isInvalidOption: (state, segment) => { return !state.ignoreOptions && segment.startsWith(`-`) && !OPTION_REGEX.test(segment); }, }; // @ts-ignore tests.isOption.suggest = (state, name, hidden = true) => { return !hidden ? [name] : null; }; const reducers = { setCandidateUsage: (state, segment, usage) => { return Object.assign(Object.assign({}, state), { candidateUsage: usage }); }, setSelectedIndex: (state, segment, index) => { return Object.assign(Object.assign({}, state), { selectedIndex: index }); }, pushBatch: (state, segment) => { return Object.assign(Object.assign({}, state), { options: state.options.concat([...segment.slice(1)].map(name => ({ name: `-${name}`, value: true }))) }); }, pushBound: (state, segment) => { const [, name, value] = segment.match(BINDING_REGEX); return Object.assign(Object.assign({}, state), { options: state.options.concat({ name, value }) }); }, pushPath: (state, segment) => { return Object.assign(Object.assign({}, state), { path: state.path.concat(segment) }); }, pushPositional: (state, segment) => { return Object.assign(Object.assign({}, state), { positionals: state.positionals.concat({ value: segment, extra: false }) }); }, pushExtra: (state, segment) => { return Object.assign(Object.assign({}, state), { positionals: state.positionals.concat({ value: segment, extra: true }) }); }, pushExtraNoLimits: (state, segment) => { return Object.assign(Object.assign({}, state), { positionals: state.positionals.concat({ value: segment, extra: NoLimits }) }); }, pushTrue: (state, segment, name = segment) => { return Object.assign(Object.assign({}, state), { options: state.options.concat({ name: segment, value: true }) }); }, pushFalse: (state, segment, name = segment) => { return Object.assign(Object.assign({}, state), { options: state.options.concat({ name, value: false }) }); }, pushUndefined: (state, segment) => { return Object.assign(Object.assign({}, state), { options: state.options.concat({ name: segment, value: undefined }) }); }, pushStringValue: (state, segment) => { var _a; const copy = Object.assign(Object.assign({}, state), { options: [...state.options] }); const lastOption = state.options[state.options.length - 1]; lastOption.value = ((_a = lastOption.value) !== null && _a !== void 0 ? _a : []).concat([segment]); return copy; }, setStringValue: (state, segment) => { const copy = Object.assign(Object.assign({}, state), { options: [...state.options] }); const lastOption = state.options[state.options.length - 1]; lastOption.value = segment; return copy; }, inhibateOptions: (state) => { return Object.assign(Object.assign({}, state), { ignoreOptions: true }); }, useHelp: (state, segment, command) => { const [, name, index] = segment.match(HELP_REGEX); if (typeof index !== `undefined`) { return Object.assign(Object.assign({}, state), { options: [{ name: `-c`, value: String(command) }, { name: `-i`, value: index }] }); } else { return Object.assign(Object.assign({}, state), { options: [{ name: `-c`, value: String(command) }] }); } }, setError: (state, segment, errorMessage) => { if (segment === END_OF_INPUT) { return Object.assign(Object.assign({}, state), { errorMessage: `${errorMessage}.` }); } else { return Object.assign(Object.assign({}, state), { errorMessage: `${errorMessage} ("${segment}").` }); } }, setOptionArityError: (state, segment) => { const lastOption = state.options[state.options.length - 1]; return Object.assign(Object.assign({}, state), { errorMessage: `Not enough arguments to option ${lastOption.name}.` }); }, }; // ------------------------------------------------------------------------ const NoLimits = Symbol(); class CommandBuilder { constructor(cliIndex, cliOpts) { this.allOptionNames = []; this.arity = { leading: [], trailing: [], extra: [], proxy: false }; this.options = []; this.paths = []; this.cliIndex = cliIndex; this.cliOpts = cliOpts; } addPath(path) { this.paths.push(path); } setArity({ leading = this.arity.leading, trailing = this.arity.trailing, extra = this.arity.extra, proxy = this.arity.proxy }) { Object.assign(this.arity, { leading, trailing, extra, proxy }); } addPositional({ name = 'arg', required = true } = {}) { if (!required && this.arity.extra === NoLimits) throw new Error(`Optional parameters cannot be declared when using .rest() or .proxy()`); if (!required && this.arity.trailing.length > 0) throw new Error(`Optional parameters cannot be declared after the required trailing positional arguments`); if (!required && this.arity.extra !== NoLimits) { this.arity.extra.push(name); } else if (this.arity.extra !== NoLimits && this.arity.extra.length === 0) { this.arity.leading.push(name); } else { this.arity.trailing.push(name); } } addRest({ name = 'arg', required = 0 } = {}) { if (this.arity.extra === NoLimits) throw new Error(`Infinite lists cannot be declared multiple times in the same command`); if (this.arity.trailing.length > 0) throw new Error(`Infinite lists cannot be declared after the required trailing positional arguments`); for (let t = 0; t < required; ++t) this.addPositional({ name }); this.arity.extra = NoLimits; } addProxy({ required = 0 } = {}) { this.addRest({ required }); this.arity.proxy = true; } addOption({ names, description, arity = 0, hidden = false, allowBinding = true }) { if (!allowBinding && arity > 1) throw new Error(`The arity cannot be higher than 1 when the option only supports the --arg=value syntax`); if (!Number.isInteger(arity)) throw new Error(`The arity must be an integer, got ${arity}`); if (arity < 0) throw new Error(`The arity must be positive, got ${arity}`); this.allOptionNames.push(...names); this.options.push({ names, description, arity, hidden, allowBinding }); } setContext(context) { this.context = context; } usage({ detailed = true, inlineOptions = true } = {}) { const segments = [this.cliOpts.binaryName]; const detailedOptionList = []; if (this.paths.length > 0) segments.push(...this.paths[0]); if (detailed) { for (const { names, arity, hidden, description } of this.options) { if (hidden) continue; const args = []; for (let t = 0; t < arity; ++t) args.push(` #${t}`); const definition = `${names.join(`,`)}${args.join(``)}`; if (!inlineOptions && description) { detailedOptionList.push({ definition, description }); } else { segments.push(`[${definition}]`); } } segments.push(...this.arity.leading.map(name => `<${name}>`)); if (this.arity.extra === NoLimits) segments.push(`...`); else segments.push(...this.arity.extra.map(name => `[${name}]`)); segments.push(...this.arity.trailing.map(name => `<${name}>`)); } let usage = segments.join(` `); return { usage, options: detailedOptionList }; } compile() { if (typeof this.context === `undefined`) throw new Error(`Assertion failed: No context attached`); const machine = makeStateMachine(); let firstNode = NODE_INITIAL; firstNode = injectNode(machine, makeNode()); registerStatic(machine, NODE_INITIAL, START_OF_INPUT, firstNode, [`setCandidateUsage`, this.usage().usage]); const positionalArgument = this.arity.proxy ? `always` : `isNotOptionLike`; const paths = this.paths.length > 0 ? this.paths : [[]]; for (const path of paths) { let lastPathNode = firstNode; // We allow options to be specified before the path. Note that we // only do this when there is a path, otherwise there would be // some redundancy with the options attached later. if (path.length > 0) { const optionPathNode = injectNode(machine, makeNode()); registerShortcut(machine, lastPathNode, optionPathNode); this.registerOptions(machine, optionPathNode); lastPathNode = optionPathNode; } for (let t = 0; t < path.length; ++t) { const nextPathNode = injectNode(machine, makeNode()); registerStatic(machine, lastPathNode, path[t], nextPathNode, `pushPath`); lastPathNode = nextPathNode; } if (this.arity.leading.length > 0 || !this.arity.proxy) { const helpNode = injectNode(machine, makeNode()); registerDynamic(machine, lastPathNode, `isHelp`, helpNode, [`useHelp`, this.cliIndex]); registerStatic(machine, helpNode, END_OF_INPUT, NODE_SUCCESS, [`setSelectedIndex`, HELP_COMMAND_INDEX]); this.registerOptions(machine, lastPathNode); } if (this.arity.leading.length > 0) registerStatic(machine, lastPathNode, END_OF_INPUT, NODE_ERRORED, [`setError`, `Not enough positional arguments`]); let lastLeadingNode = lastPathNode; for (let t = 0; t < this.arity.leading.length; ++t) { const nextLeadingNode = injectNode(machine, makeNode()); if (!this.arity.proxy) this.registerOptions(machine, nextLeadingNode); if (this.arity.trailing.length > 0 || t + 1 !== this.arity.leading.length) registerStatic(machine, nextLeadingNode, END_OF_INPUT, NODE_ERRORED, [`setError`, `Not enough positional arguments`]); registerDynamic(machine, lastLeadingNode, `isNotOptionLike`, nextLeadingNode, `pushPositional`); lastLeadingNode = nextLeadingNode; } let lastExtraNode = lastLeadingNode; if (this.arity.extra === NoLimits || this.arity.extra.length > 0) { const extraShortcutNode = injectNode(machine, makeNode()); registerShortcut(machine, lastLeadingNode, extraShortcutNode); if (this.arity.extra === NoLimits) { const extraNode = injectNode(machine, makeNode()); if (!this.arity.proxy) this.registerOptions(machine, extraNode); registerDynamic(machine, lastLeadingNode, positionalArgument, extraNode, `pushExtraNoLimits`); registerDynamic(machine, extraNode, positionalArgument, extraNode, `pushExtraNoLimits`); registerShortcut(machine, extraNode, extraShortcutNode); } else { for (let t = 0; t < this.arity.extra.length; ++t) { const nextExtraNode = injectNode(machine, makeNode()); if (!this.arity.proxy) this.registerOptions(machine, nextExtraNode); registerDynamic(machine, lastExtraNode, positionalArgument, nextExtraNode, `pushExtra`); registerShortcut(machine, nextExtraNode, extraShortcutNode); lastExtraNode = nextExtraNode; } } lastExtraNode = extraShortcutNode; } if (this.arity.trailing.length > 0) registerStatic(machine, lastExtraNode, END_OF_INPUT, NODE_ERRORED, [`setError`, `Not enough positional arguments`]); let lastTrailingNode = lastExtraNode; for (let t = 0; t < this.arity.trailing.length; ++t) { const nextTrailingNode = injectNode(machine, makeNode()); if (!this.arity.proxy) this.registerOptions(machine, nextTrailingNode); if (t + 1 < this.arity.trailing.length) registerStatic(machine, nextTrailingNode, END_OF_INPUT, NODE_ERRORED, [`setError`, `Not enough positional arguments`]); registerDynamic(machine, lastTrailingNode, `isNotOptionLike`, nextTrailingNode, `pushPositional`); lastTrailingNode = nextTrailingNode; } registerDynamic(machine, lastTrailingNode, positionalArgument, NODE_ERRORED, [`setError`, `Extraneous positional argument`]); registerStatic(machine, lastTrailingNode, END_OF_INPUT, NODE_SUCCESS, [`setSelectedIndex`, this.cliIndex]); } return { machine, context: this.context, }; } registerOptions(machine, node) { registerDynamic(machine, node, [`isOption`, `--`], node, `inhibateOptions`); registerDynamic(machine, node, [`isBatchOption`, this.allOptionNames], node, `pushBatch`); registerDynamic(machine, node, [`isBoundOption`, this.allOptionNames, this.options], node, `pushBound`); registerDynamic(machine, node, [`isUnsupportedOption`, this.allOptionNames], NODE_ERRORED, [`setError`, `Unsupported option name`]); registerDynamic(machine, node, [`isInvalidOption`], NODE_ERRORED, [`setError`, `Invalid option name`]); for (const option of this.options) { const longestName = option.names.reduce((longestName, name) => { return name.length > longestName.length ? name : longestName; }, ``); if (option.arity === 0) { for (const name of option.names) { registerDynamic(machine, node, [`isOption`, name, option.hidden || name !== longestName], node, `pushTrue`); if (name.startsWith(`--`) && !name.startsWith(`--no-`)) { registerDynamic(machine, node, [`isNegatedOption`, name], node, [`pushFalse`, name]); } } } else { // We inject a new node at the end of the state machine let lastNode = injectNode(machine, makeNode()); // We register transitions from the starting node to this new node for (const name of option.names) { registerDynamic(machine, node, [`isOption`, name, option.hidden || name !== longestName], lastNode, `pushUndefined`); } // For each argument, we inject a new node at the end and we // register a transition from the current node to this new node for (let t = 0; t < option.arity; ++t) { const nextNode = injectNode(machine, makeNode()); // We can provide better errors when another option or END_OF_INPUT is encountered registerStatic(machine, lastNode, END_OF_INPUT, NODE_ERRORED, `setOptionArityError`); registerDynamic(machine, lastNode, `isOptionLike`, NODE_ERRORED, `setOptionArityError`); // If the option has a single argument, no need to store it in an array const action = option.arity === 1 ? `setStringValue` : `pushStringValue`; registerDynamic(machine, lastNode, `isNotOptionLike`, nextNode, action); lastNode = nextNode; } // In the end, we register a shortcut from // the last node back to the starting node registerShortcut(machine, lastNode, node); } } } } class CliBuilder { constructor({ binaryName = `...` } = {}) { this.builders = []; this.opts = { binaryName }; } static build(cbs, opts = {}) { return new CliBuilder(opts).commands(cbs).compile(); } getBuilderByIndex(n) { if (!(n >= 0 && n < this.builders.length)) throw new Error(`Assertion failed: Out-of-bound command index (${n})`); return this.builders[n]; } commands(cbs) { for (const cb of cbs) cb(this.command()); return this; } command() { const builder = new CommandBuilder(this.builders.length, this.opts); this.builders.push(builder); return builder; } compile() { const machines = []; const contexts = []; for (const builder of this.builders) { const { machine, context } = builder.compile(); machines.push(machine); contexts.push(context); } const machine = makeAnyOfMachine(machines); simplifyMachine(machine); return { machine, contexts, process: (input) => { return runMachine(machine, input); }, suggest: (input, partial) => { return suggestMachine(machine, input, partial); }, }; } } class Command { constructor() { /** * Predefined that will be set to true if `-h,--help` has been used, in which case `Command#execute` shouldn't be called. */ this.help = false; } static getMeta(prototype) { const base = prototype.constructor; return base.meta = Object.prototype.hasOwnProperty.call(base, `meta`) ? base.meta : { definitions: [], transformers: [ (state, command) => { for (const { name, value } of state.options) { if (name === `-h` || name === `--help`) { // @ts-ignore: The property is meant to have been defined by the child class command.help = value; } } }, ], }; } static resolveMeta(prototype) { const definitions = []; const transformers = []; for (let proto = prototype; proto instanceof Command; proto = proto.__proto__) { const meta = this.getMeta(proto); for (const definition of meta.definitions) definitions.push(definition); for (const transformer of meta.transformers) { transformers.push(transformer); } } return { definitions, transformers, }; } static registerDefinition(prototype, definition) { this.getMeta(prototype).definitions.push(definition); } static registerTransformer(prototype, transformer) { this.getMeta(prototype).transformers.push(transformer); } static addPath(...path) { this.Path(...path)(this.prototype, `execute`); } static addOption(name, builder) { builder(this.prototype, name); } /** * Wrap the specified command to be attached to the given path on the command line. * The first path thus attached will be considered the "main" one, and all others will be aliases. * @param path The command path. */ static Path(...path) { return (prototype, propertyName) => { this.registerDefinition(prototype, command => { command.addPath(path); }); }; } /** * Register a boolean listener for the given option names. When Clipanion detects that this argument is present, the value will be set to false. The value won't be set unless the option is found, so you must remember to set it to an appropriate default value. * @param descriptor the option names. */ static Boolean(descriptor, { hidden = false, description } = {}) { return (prototype, propertyName) => { const optNames = descriptor.split(`,`); this.registerDefinition(prototype, command => { command.addOption({ names: optNames, arity: 0, hidden, allowBinding: false, description }); }); this.registerTransformer(prototype, (state, command) => { for (const { name, value } of state.options) { if (optNames.includes(name)) { // @ts-ignore: The property is meant to have been defined by the child class command[propertyName] = value; } } }); }; } /** * Register a boolean listener for the given option names. Each time Clipanion detects that this argument is present, the counter will be incremented. Each time the argument is negated, the counter will be reset to `0`. The counter won't be set unless the option is found, so you must remember to set it to an appropriate default value. * @param descriptor A comma-separated list of option names. */ static Counter(descriptor, { hidden = false, description } = {}) { return (prototype, propertyName) => { const optNames = descriptor.split(`,`); this.registerDefinition(prototype, command => { command.addOption({ names: optNames, arity: 0, hidden, allowBinding: false, description }); }); this.registerTransformer(prototype, (state, command) => { var _a; for (const { name, value } of state.options) { if (optNames.includes(name)) { // @ts-ignore: The property is meant to have been defined by the child class (_a = command[propertyName]) !== null && _a !== void 0 ? _a : (command[propertyName] = 0); // Negated options reset the counter if (!value) { // @ts-ignore: The property is meant to have been defined by the child class command[propertyName] = 0; } else { // @ts-ignore: The property is meant to have been defined by the child class command[propertyName]++; } } } }); }; } static String(descriptor = {}, { arity = 1, tolerateBoolean = false, hidden = false, description } = {}) { return (prototype, propertyName) => { if (typeof descriptor === `string`) { const optNames = descriptor.split(`,`); this.registerDefinition(prototype, command => { // If tolerateBoolean is specified, the command will only accept a string value // using the bind syntax and will otherwise act like a boolean option command.addOption({ names: optNames, arity: tolerateBoolean ? 0 : arity, hidden, description }); }); this.registerTransformer(prototype, (state, command) => { for (const { name, value } of state.options) { if (optNames.includes(name)) { // @ts-ignore: The property is meant to have been defined by the child class command[propertyName] = value; } } }); } else { const { name = propertyName, required = true } = descriptor; this.registerDefinition(prototype, command => { command.addPositional({ name, required }); }); this.registerTransformer(prototype, (state, command) => { for (let i = 0; i < state.positionals.length; ++i) { // We skip NoLimits extras. We only care about // required and optional finite positionals. if (state.positionals[i].extra === NoLimits) continue; // We skip optional positionals when we only // care about required positionals. if (required && state.positionals[i].extra === true) continue; // We skip required positionals when we only // care about optional positionals. if (!required && state.positionals[i].extra === false) continue; // We remove the positional from the list const [positional] = state.positionals.splice(i, 1); // We assign its value to the property. // @ts-ignore: The property is meant to have been defined by the child class command[propertyName] = positional.value; // We stop after the first successful iteration. break; } }); } }; } /** * Register a listener that looks for an option and its followup argument. When Clipanion detects that this argument is present, the value will be pushed into the array represented in the property. */ static Array(descriptor, { arity = 1, hidden = false, description } = {}) { return (prototype, propertyName) => { if (arity === 0) throw new Error(`Array options are expected to have at least an arity of 1`); const optNames = descriptor.split(`,`); this.registerDefinition(prototype, command => { command.addOption({ names: optNames, arity, hidden, description }); }); this.registerTransformer(prototype, (state, command) => { for (const { name, value } of state.options) { if (optNames.includes(name)) { // @ts-ignore: The property is meant to have been defined by the child class command[propertyName] = command[propertyName] || []; // @ts-ignore: The property is meant to have been defined by the child class command[propertyName].push(value); } } }); }; } static Rest({ required = 0 } = {}) { return (prototype, propertyName) => { this.registerDefinition(prototype, command => { command.addRest({ name: propertyName, required }); }); this.registerTransformer(prototype, (state, command, builder) => { // The builder's arity.extra will always be NoLimits, // because it is set when we call registerDefinition const isRestPositional = (index) => { const positional = state.positionals[index]; // A NoLimits extra (i.e. an optional rest argument) if (positional.extra === NoLimits) return true; // A leading positional (i.e. a required rest argument) if (positional.extra === false && index < builder.arity.leading.length) return true; return false; }; let count = 0; while (count < state.positionals.length && isRestPositional(count)) count += 1; // @ts-ignore: The property is meant to have been defined by the child class command[propertyName] = state.positionals .splice(0, count) .map(({ value }) => value); }); }; } /** * Register a listener that takes all the arguments remaining (including options and such) and store them into the selected property. * Note that all methods affecting positional arguments are evaluated in the definition order; don't mess with it (for example sorting your properties in ascendent order might have adverse results). */ static Proxy({ required = 0 } = {}) { return (prototype, propertyName) => { this.registerDefinition(prototype, command => { command.addProxy({ required }); }); this.registerTransformer(prototype, (state, command) => { // No need to filter / splice any positionals for Command.Proxy. // Once inside a proxy, we've already reached the point of no return. // @ts-ignore: The property is meant to have been defined by the child class command[propertyName] = state.positionals.map(({ value }) => value); }); }; } /** * Defines the usage information for the given command. * @param usage */ static Usage(usage) { return usage; } /** * Defines the schema for the given command. * @param schema */ static Schema(schema) { return schema; } /** * Standard error handler which will simply rethrow the error. Can be used to add custom logic to handle errors * from the command or simply return the parent class error handling. * @param error */ async catch(error) { throw error; } async validateAndExecute() { const commandClass = this.constructor; const schema = commandClass.schema; if (typeof schema !== `undefined`) { try { await schema.validate(this); } catch (error) { if (error.name === `ValidationError`) error.clipanion = { type: `usage` }; throw error; } } const exitCode = await this.execute(); if (typeof exitCode !== `undefined`) { return exitCode; } else { return 0; } } } /** * A list of useful semi-opinionated command entries that have to be registered manually. * * They cover the basic needs of most CLIs (e.g. help command, version command). * * @example * cli.register(Command.Entries.Help); * cli.register(Command.Entries.Version); */ Command.Entries = {}; /*! ***************************************************************************** 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. ***************************************************************************** */ function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } class HelpCommand extends Command { async execute() { this.context.stdout.write(this.cli.usage(null)); } } __decorate([ Command.Path(`--help`), Command.Path(`-h`) ], HelpCommand.prototype, "execute", null); class VersionCommand extends Command { async execute() { var _a; this.context.stdout.write(`${(_a = this.cli.binaryVersion) !== null && _a !== void 0 ? _a : ``}\n`); } } __decorate([ Command.Path(`--version`), Command.Path(`-v`) ], VersionCommand.prototype, "execute", null); const richFormat = { bold: str => `\x1b[1m${str}\x1b[22m`, error: str => `\x1b[31m\x1b[1m${str}\x1b[22m\x1b[39m`, code: str => `\x1b[36m${str}\x1b[39m`, }; const textFormat = { bold: str => str, error: str => str, code: str => str, }; function formatMarkdownish(text, { format, paragraphs }) { // Enforce \n as newline character text = text.replace(/\r\n?/g, `\n`); // Remove the indentation, since it got messed up with the JS indentation text = text.replace(/^[\t ]+|[\t ]+$/gm, ``); // Remove surrounding newlines, since they got added for JS formatting text = text.replace(/^\n+|\n+$/g, ``); // List items always end with at least two newlines (in order to not be collapsed) text = text.replace(/^-([^\n]*?)\n+/gm, `-$1\n\n`); // Single newlines are removed; larger than that are collapsed into one text = text.replace(/\n(\n)?\n*/g, `$1`); if (paragraphs) { text = text.split(/\n/).map(function (paragraph) { // Does the paragraph starts with a list? let bulletMatch = paragraph.match(/^[*-][\t ]+(.*)/); if (!bulletMatch) // No, cut the paragraphs into segments of 80 characters return paragraph.match(/(.{1,80})(?: |$)/g).join('\n'); // Yes, cut the paragraphs into segments of 78 characters (to account for the prefix) return bulletMatch[1].match(/(.{1,78})(?: |$)/g).map((line, index) => { return (index === 0 ? `- ` : ` `) + line; }).join(`\n`); }).join(`\n\n`); } // Highlight the code segments text = text.replace(/(`+)((?:.|[\n])*?)\1/g, function ($0, $1, $2) { return format.code($1 + $2 + $1); }); return text ? text + `\n` : ``; } class HelpCommand$1 extends Command { constructor(contexts) { super(); this.contexts = contexts; this.commands = []; } static from(state, contexts) { const command = new HelpCommand$1(contexts); command.path = state.path; for (const opt of state.options) { switch (opt.name) { case `-c`: { command.commands.push(Number(opt.value)); } break; case `-i`: { command.index = Number(opt.value); } break; } } return command; } async execute() { let commands = this.commands; if (typeof this.index !== `undefined` && this.index >= 0 && this.index < commands.length) commands = [commands[this.index]]; if (commands.length === 0) { this.context.stdout.write(this.cli.usage()); } else if (commands.length === 1) { this.context.stdout.write(this.cli.usage(this.contexts[commands[0]].commandClass, { detailed: true })); } else if (commands.length > 1) { this.context.stdout.write(`Multiple commands match your selection:\n`); this.context.stdout.write(`\n`); let index = 0; for (const command of this.commands) this.context.stdout.write(this.cli.usage(this.contexts[command].commandClass, { prefix: `${index++}. `.padStart(5) })); this.context.stdout.write(`\n`); this.context.stdout.write(`Run again with -h= to see the longer details of any of those commands.\n`); } } } function getDefaultColorSettings() { if (process.env.FORCE_COLOR === `0`) return false; if (process.env.FORCE_COLOR === `1`) return true; if (typeof process.stdout !== `undefined` && process.stdout.isTTY) return true; return false; } /** * @template Context The context shared by all commands. Contexts are a set of values, defined when calling the `run`/`runExit` functions from the CLI instance, that will be made available to the commands via `this.context`. */ class Cli { constructor({ binaryLabel, binaryName: binaryNameOpt = `...`, binaryVersion, enableColors = getDefaultColorSettings() } = {}) { this.registrations = new Map(); this.builder = new CliBuilder({ binaryName: binaryNameOpt }); this.binaryLabel = binaryLabel; this.binaryName = binaryNameOpt; this.binaryVersion = binaryVersion; this.enableColors = enableColors; } /** * Creates a new Cli and registers all commands passed as parameters. * * @param commandClasses The Commands to register * @returns The created `Cli` instance */ static from(commandClasses, options = {}) { const cli = new Cli(options); for (const commandClass of commandClasses) cli.register(commandClass); return cli; } /** * Registers a command inside the CLI. */ register(commandClass) { const commandBuilder = this.builder.command(); this.registrations.set(commandClass, commandBuilder.cliIndex); const { definitions } = commandClass.resolveMeta(commandClass.prototype); for (const definition of definitions) definition(commandBuilder); commandBuilder.setContext({ commandClass, }); } process(input) { const { contexts, process } = this.builder.compile(); const state = process(input); switch (state.selectedIndex) { case HELP_COMMAND_INDEX: { return HelpCommand$1.from(state, contexts); } default: { const { commandClass } = contexts[state.selectedIndex]; const index = this.registrations.get(commandClass); if (typeof index === `undefined`) throw new Error(`Assertion failed: Expected the command class to have been registered.`); const commandBuilder = this.builder.getBuilderByIndex(index); const command = new commandClass(); command.path = state.path; const { transformers } = commandClass.resolveMeta(commandClass.prototype); for (const transformer of transformers) transformer(state, command, commandBuilder); return command; } } } async run(input, context) { let command; if (!Array.isArray(input)) { command = input; } else { try { command = this.process(input); } catch (error) { context.stdout.write(this.error(error)); return 1; } } if (command.help) { context.stdout.write(this.usage(command, { detailed: true })); return 0; } command.context = context; command.cli = { binaryLabel: this.binaryLabel, binaryName: this.binaryName, binaryVersion: this.binaryVersion, enableColors: this.enableColors, definitions: () => this.definitions(), error: (error, opts) => this.error(error, opts), process: input => this.process(input), run: (input, subContext) => this.run(input, Object.assign(Object.assign({}, context), subContext)), usage: (command, opts) => this.usage(command, opts), }; let exitCode; try { exitCode = await command.validateAndExecute().catch(error => command.catch(error).then(() => 0)); } catch (error) { context.stdout.write(this.error(error, { command })); return 1; } return exitCode; } /** * Runs a command and exits the current `process` with the exit code returned by the command. * * @param input An array containing the name of the command and its arguments. * * @example * cli.runExit(process.argv.slice(2), Cli.defaultContext) */ async runExit(input, context) { process.exitCode = await this.run(input, context); } suggest(input, partial) { const { contexts, process, suggest } = this.builder.compile(); return suggest(input, partial); } definitions({ colored = false } = {}) { const data = []; for (const [commandClass, number] of this.registrations) { if (typeof commandClass.usage === `undefined`) continue; const { usage: path } = this.getUsageByIndex(number, { detailed: false }); const { usage, options } = this.getUsageByIndex(number, { detailed: true, inlineOptions: false }); const category = typeof commandClass.usage.category !== `undefined` ? formatMarkdownish(commandClass.usage.category, { format: this.format(colored), paragraphs: false }) : undefined; const description = typeof commandClass.usage.description !== `undefined` ? formatMarkdownish(commandClass.usage.description, { format: this.format(colored), paragraphs: false }) : undefined; const details = typeof commandClass.usage.details !== `undefined` ? formatMarkdownish(commandClass.usage.details, { format: this.format(colored), paragraphs: true }) : undefined; const examples = typeof commandClass.usage.examples !== `undefined` ? commandClass.usage.examples.map(([label, cli]) => [formatMarkdownish(label, { format: this.format(colored), paragraphs: false }), cli.replace(/\$0/g, this.binaryName)]) : undefined; data.push({ path, usage, category, description, details, examples, options }); } return data; } usage(command = null, { colored, detailed = false, prefix = `$ ` } = {}) { // @ts-ignore const commandClass = command !== null && typeof command.getMeta === `undefined` ? command.constructor : command; let result = ``; if (!commandClass) { const commandsByCategories = new Map(); for (const [commandClass, number] of this.registrations.entries()) { if (typeof commandClass.usage === `undefined`) continue; const category = typeof commandClass.usage.category !== `undefined` ? formatMarkdownish(commandClass.usage.category, { format: this.format(colored), paragraphs: false }) : null; let categoryCommands = commandsByCategories.get(category); if (typeof categoryCommands === `undefined`) commandsByCategories.set(category, categoryCommands = []); const { usage } = this.getUsageByIndex(number); categoryCommands.push({ commandClass, usage }); } const categoryNames = Array.from(commandsByCategories.keys()).sort((a, b) => { if (a === null) return -1; if (b === null) return +1; return a.localeCompare(b, `en`, { usage: `sort`, caseFirst: `upper` }); }); const hasLabel = typeof this.binaryLabel !== `undefined`; const hasVersion = typeof this.binaryVersion !== `undefined`; if (hasLabel || hasVersion) { if (hasLabel && hasVersion) result += `${this.format(colored).bold(`${this.binaryLabel} - ${this.binaryVersion}`)}\n\n`; else if (hasLabel) result += `${this.format(colored).bold(`${this.binaryLabel}`)}\n`; else result += `${this.format(colored).bold(`${this.binaryVersion}`)}\n`; result += ` ${this.format(colored).bold(prefix)}${this.binaryName} \n`; } else { result += `${this.format(colored).bold(prefix)}${this.binaryName} \n`; } for (let categoryName of categoryNames) { const commands = commandsByCategories.get(categoryName).slice().sort((a, b) => { return a.usage.localeCompare(b.usage, `en`, { usage: `sort`, caseFirst: `upper` }); }); const header = categoryName !== null ? categoryName.trim() : `Where is one of`; result += `\n`; result += `${this.format(colored).bold(`${header}:`)}\n`; for (let { commandClass, usage } of commands) { const doc = commandClass.usage.description || `undocumented`; result += `\n`; result += ` ${this.format(colored).bold(usage)}\n`; result += ` ${formatMarkdownish(doc, { format: this.format(colored), paragraphs: false })}`; } } result += `\n`; result += formatMarkdownish(`You can also print more details about any of these commands by calling them after adding the \`-h,--help\` flag right after the command name.`, { format: this.format(colored), paragraphs: true }); } else { if (!detailed) { const { usage } = this.getUsageByRegistration(commandClass); result += `${this.format(colored).bold(prefix)}${usage}\n`; } else { const { description = ``, details = ``, examples = [], } = commandClass.usage || {}; if (description !== ``) { result += formatMarkdownish(description, { format: this.format(colored), paragraphs: false }).replace(/^./, $0 => $0.toUpperCase()); result += `\n`; } if (details !== `` || examples.length > 0) { result += `${this.format(colored).bold(`Usage:`)}\n`; result += `\n`; } const { usage, options } = this.getUsageByRegistration(commandClass, { inlineOptions: false }); result += `${this.format(colored).bold(prefix)}${usage}\n`; if (options.length > 0) { result += `\n`; result += `${richFormat.bold('Options:')}\n`; const maxDefinitionLength = options.reduce((length, option) => { return Math.max(length, option.definition.length); }, 0); result += `\n`; for (const { definition, description } of options) { result += ` ${definition.padEnd(maxDefinitionLength)} ${formatMarkdownish(description, { format: this.format(colored), paragraphs: false })}`; } } if (details !== ``) { result += `\n`; result += `${this.format(colored).bold(`Details:`)}\n`; result += `\n`; result += formatMarkdownish(details, { format: this.format(colored), paragraphs: true }); } if (examples.length > 0) { result += `\n`; result += `${this.format(colored).bold(`Examples:`)}\n`; for (let [description, example] of examples) { result += `\n`; result += formatMarkdownish(description, { format: this.format(colored), paragraphs: false }); result += example .replace(/^/m, ` ${this.format(colored).bold(prefix)}`) .replace(/\$0/g, this.binaryName) + `\n`; } } } } return result; } error(error, { colored, command = null } = {}) { if (!(error instanceof Error)) error = new Error(`Execution failed with a non-error rejection (rejected value: ${JSON.stringify(error)})`); let result = ``; let name = error.name.replace(/([a-z])([A-Z])/g, `$1 $2`); if (name === `Error`) name = `Internal Error`; result += `${this.format(colored).error(name)}: ${error.message}\n`; // @ts-ignore const meta = error.clipanion; if (typeof meta !== `undefined`) { if (meta.type === `usage`) { result += `\n`; result += this.usage(command); } } else { if (error.stack) { result += `${error.stack.replace(/^.*\n/, ``)}\n`; } } return result; } getUsageByRegistration(klass, opts) { const index = this.registrations.get(klass); if (typeof index === `undefined`) throw new Error(`Assertion failed: Unregistered command`); return this.getUsageByIndex(index, opts); } getUsageByIndex(n, opts) { return this.builder.getBuilderByIndex(n).usage(opts); } format(colored = this.enableColors) { return colored ? richFormat : textFormat; } } /** * The default context of the CLI. * * Contains the stdio of the current `process`. */ Cli.defaultContext = { stdin: process.stdin, stdout: process.stdout, stderr: process.stderr, }; Command.Entries.Help = HelpCommand; Command.Entries.Version = VersionCommand; exports.Cli = Cli; exports.Command = Command; exports.UsageError = UsageError; /***/ }), /***/ 79715: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const PassThrough = __webpack_require__(12781).PassThrough; const mimicResponse = __webpack_require__(66344); const cloneResponse = response => { if (!(response && response.pipe)) { throw new TypeError('Parameter `response` must be a response stream.'); } const clone = new PassThrough(); mimicResponse(response, clone); return response.pipe(clone); }; module.exports = cloneResponse; /***/ }), /***/ 16497: /***/ ((__unused_webpack_module, exports) => { // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(arg) { if (Array.isArray) { return Array.isArray(arg); } return objectToString(arg) === '[object Array]'; } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = Buffer.isBuffer; function objectToString(o) { return Object.prototype.toString.call(o); } /***/ }), /***/ 75487: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const binding = __webpack_require__(62536); module.exports = binding.getCPUInfo; /***/ }), /***/ 10346: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const {Transform, PassThrough} = __webpack_require__(12781); const zlib = __webpack_require__(59796); const mimicResponse = __webpack_require__(91511); module.exports = response => { const contentEncoding = (response.headers['content-encoding'] || '').toLowerCase(); if (!['gzip', 'deflate', 'br'].includes(contentEncoding)) { return response; } // TODO: Remove this when targeting Node.js 12. const isBrotli = contentEncoding === 'br'; if (isBrotli && typeof zlib.createBrotliDecompress !== 'function') { response.destroy(new Error('Brotli is not supported on Node.js < 12')); return response; } let isEmpty = true; const checker = new Transform({ transform(data, _encoding, callback) { isEmpty = false; callback(null, data); }, flush(callback) { callback(); } }); const finalStream = new PassThrough({ autoDestroy: false, destroy(error, callback) { response.destroy(); callback(error); } }); const decompressStream = isBrotli ? zlib.createBrotliDecompress() : zlib.createUnzip(); decompressStream.once('error', error => { if (isEmpty && !response.readable) { finalStream.end(); return; } finalStream.destroy(error); }); mimicResponse(response, finalStream); response.pipe(checker).pipe(decompressStream).pipe(finalStream); return finalStream; }; /***/ }), /***/ 91511: /***/ ((module) => { "use strict"; // We define these manually to ensure they're always copied // even if they would move up the prototype chain // https://nodejs.org/api/http.html#http_class_http_incomingmessage const knownProperties = [ 'aborted', 'complete', 'headers', 'httpVersion', 'httpVersionMinor', 'httpVersionMajor', 'method', 'rawHeaders', 'rawTrailers', 'setTimeout', 'socket', 'statusCode', 'statusMessage', 'trailers', 'url' ]; module.exports = (fromStream, toStream) => { if (toStream._readableState.autoDestroy) { throw new Error('The second stream must have the `autoDestroy` option set to `false`'); } const fromProperties = new Set(Object.keys(fromStream).concat(knownProperties)); const properties = {}; for (const property of fromProperties) { // Don't overwrite existing properties. if (property in toStream) { continue; } properties[property] = { get() { const value = fromStream[property]; const isFunction = typeof value === 'function'; return isFunction ? value.bind(fromStream) : value; }, set(value) { fromStream[property] = value; }, enumerable: true, configurable: false }; } Object.defineProperties(toStream, properties); fromStream.once('aborted', () => { toStream.destroy(); toStream.emit('aborted'); }); fromStream.once('close', () => { if (fromStream.complete) { if (toStream.readable) { toStream.once('end', () => { toStream.emit('close'); }); } else { toStream.emit('close'); } } else { toStream.emit('close'); } }); return toStream; }; /***/ }), /***/ 1313: /***/ ((module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); function isTLSSocket(socket) { return socket.encrypted; } const deferToConnect = (socket, fn) => { let listeners; if (typeof fn === 'function') { const connect = fn; listeners = { connect }; } else { listeners = fn; } const hasConnectListener = typeof listeners.connect === 'function'; const hasSecureConnectListener = typeof listeners.secureConnect === 'function'; const hasCloseListener = typeof listeners.close === 'function'; const onConnect = () => { if (hasConnectListener) { listeners.connect(); } if (isTLSSocket(socket) && hasSecureConnectListener) { if (socket.authorized) { listeners.secureConnect(); } else if (!socket.authorizationError) { socket.once('secureConnect', listeners.secureConnect); } } if (hasCloseListener) { socket.once('close', listeners.close); } }; if (socket.writable && !socket.connecting) { onConnect(); } else if (socket.connecting) { socket.once('connect', onConnect); } else if (socket.destroyed && hasCloseListener) { listeners.close(socket._hadError); } }; exports["default"] = deferToConnect; // For CommonJS default export support module.exports = deferToConnect; module.exports["default"] = deferToConnect; /***/ }), /***/ 36577: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createPeersFolderSuffix = exports.depPathToFilename = exports.parse = exports.refToRelative = exports.relative = exports.getRegistryByPackageName = exports.refToAbsolute = exports.tryGetPackageId = exports.resolve = exports.isAbsolute = void 0; const crypto_base32_hash_1 = __webpack_require__(91332); const encode_registry_1 = __importDefault(__webpack_require__(12346)); const semver_1 = __importDefault(__webpack_require__(33505)); function isAbsolute(dependencyPath) { return dependencyPath[0] !== '/'; } exports.isAbsolute = isAbsolute; function resolve(registries, resolutionLocation) { if (!isAbsolute(resolutionLocation)) { let registryUrl; if (resolutionLocation[1] === '@') { const slashIndex = resolutionLocation.indexOf('/', 1); const scope = resolutionLocation.slice(1, slashIndex !== -1 ? slashIndex : 0); registryUrl = registries[scope] || registries.default; } else { registryUrl = registries.default; } const registryDirectory = (0, encode_registry_1.default)(registryUrl); return `${registryDirectory}${resolutionLocation}`; } return resolutionLocation; } exports.resolve = resolve; function tryGetPackageId(registries, relDepPath) { if (relDepPath[0] !== '/') { return null; } const underscoreIndex = relDepPath.indexOf('_', relDepPath.lastIndexOf('/')); if (underscoreIndex !== -1) { return resolve(registries, relDepPath.slice(0, underscoreIndex)); } return resolve(registries, relDepPath); } exports.tryGetPackageId = tryGetPackageId; function refToAbsolute(reference, pkgName, registries) { if (reference.startsWith('link:')) { return null; } if (!reference.includes('/')) { const registryName = (0, encode_registry_1.default)(getRegistryByPackageName(registries, pkgName)); return `${registryName}/${pkgName}/${reference}`; } if (reference[0] !== '/') return reference; const registryName = (0, encode_registry_1.default)(getRegistryByPackageName(registries, pkgName)); return `${registryName}${reference}`; } exports.refToAbsolute = refToAbsolute; function getRegistryByPackageName(registries, packageName) { if (packageName[0] !== '@') return registries.default; const scope = packageName.substring(0, packageName.indexOf('/')); return registries[scope] || registries.default; } exports.getRegistryByPackageName = getRegistryByPackageName; function relative(registries, packageName, absoluteResolutionLoc) { const registryName = (0, encode_registry_1.default)(getRegistryByPackageName(registries, packageName)); if (absoluteResolutionLoc.startsWith(`${registryName}/`)) { return absoluteResolutionLoc.slice(absoluteResolutionLoc.indexOf('/')); } return absoluteResolutionLoc; } exports.relative = relative; function refToRelative(reference, pkgName) { if (reference.startsWith('link:')) { return null; } if (reference.startsWith('file:')) { return reference; } if (!reference.includes('/')) { return `/${pkgName}/${reference}`; } return reference; } exports.refToRelative = refToRelative; function parse(dependencyPath) { // eslint-disable-next-line: strict-type-predicates if (typeof dependencyPath !== 'string') { throw new TypeError(`Expected \`dependencyPath\` to be of type \`string\`, got \`${ // eslint-disable-next-line: strict-type-predicates dependencyPath === null ? 'null' : typeof dependencyPath}\``); } const _isAbsolute = isAbsolute(dependencyPath); const parts = dependencyPath.split('/'); if (!_isAbsolute) parts.shift(); const host = _isAbsolute ? parts.shift() : undefined; const name = parts[0].startsWith('@') ? `${parts.shift()}/${parts.shift()}` // eslint-disable-line @typescript-eslint/restrict-template-expressions : parts.shift(); let version = parts.shift(); if (version) { const underscoreIndex = version.indexOf('_'); let peersSuffix; if (underscoreIndex !== -1) { peersSuffix = version.substring(underscoreIndex + 1); version = version.substring(0, underscoreIndex); } if (semver_1.default.valid(version)) { return { host, isAbsolute: _isAbsolute, name, peersSuffix, version, }; } } if (!_isAbsolute) throw new Error(`${dependencyPath} is an invalid relative dependency path`); return { host, isAbsolute: _isAbsolute, }; } exports.parse = parse; function depPathToFilename(depPath) { const filename = depPathToFilenameUnescaped(depPath).replace(/[\\/:*?"<>|]/g, '+'); if (filename.length > 120 || filename !== filename.toLowerCase() && !filename.startsWith('file+')) { return `${filename.substring(0, 50)}_${(0, crypto_base32_hash_1.createBase32Hash)(filename)}`; } return filename; } exports.depPathToFilename = depPathToFilename; function depPathToFilenameUnescaped(depPath) { if (depPath.indexOf('file:') !== 0) { if (depPath.startsWith('/')) { depPath = depPath.substring(1); } const index = depPath.lastIndexOf('/'); return `${depPath.substring(0, index)}@${depPath.slice(index + 1)}`; } return depPath.replace(':', '+'); } function createPeersFolderSuffix(peers) { const folderName = peers.map(({ name, version }) => `${name.replace('/', '+')}@${version}`).sort().join('+'); // We don't want the folder name to get too long. // Otherwise, an ENAMETOOLONG error might happen. // see: https://github.com/pnpm/pnpm/issues/977 // // A bigger limit might be fine but the base32 encoded md5 hash will be 26 symbols, // so for consistency's sake, we go with 26. if (folderName.length > 26) { return `_${(0, crypto_base32_hash_1.createBase32Hash)(folderName)}`; } return `_${folderName}`; } exports.createPeersFolderSuffix = createPeersFolderSuffix; //# sourceMappingURL=index.js.map /***/ }), /***/ 33573: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // A linked list to keep track of recently-used-ness const Yallist = __webpack_require__(87600) const MAX = Symbol('max') const LENGTH = Symbol('length') const LENGTH_CALCULATOR = Symbol('lengthCalculator') const ALLOW_STALE = Symbol('allowStale') const MAX_AGE = Symbol('maxAge') const DISPOSE = Symbol('dispose') const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') const LRU_LIST = Symbol('lruList') const CACHE = Symbol('cache') const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') const naiveLength = () => 1 // lruList is a yallist where the head is the youngest // item, and the tail is the oldest. the list contains the Hit // objects as the entries. // Each Hit object has a reference to its Yallist.Node. This // never changes. // // cache is a Map (or PseudoMap) that matches the keys to // the Yallist.Node object. class LRUCache { constructor (options) { if (typeof options === 'number') options = { max: options } if (!options) options = {} if (options.max && (typeof options.max !== 'number' || options.max < 0)) throw new TypeError('max must be a non-negative number') // Kind of weird to have a default max of Infinity, but oh well. const max = this[MAX] = options.max || Infinity const lc = options.length || naiveLength this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc this[ALLOW_STALE] = options.stale || false if (options.maxAge && typeof options.maxAge !== 'number') throw new TypeError('maxAge must be a number') this[MAX_AGE] = options.maxAge || 0 this[DISPOSE] = options.dispose this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false this.reset() } // resize the cache when the max changes. set max (mL) { if (typeof mL !== 'number' || mL < 0) throw new TypeError('max must be a non-negative number') this[MAX] = mL || Infinity trim(this) } get max () { return this[MAX] } set allowStale (allowStale) { this[ALLOW_STALE] = !!allowStale } get allowStale () { return this[ALLOW_STALE] } set maxAge (mA) { if (typeof mA !== 'number') throw new TypeError('maxAge must be a non-negative number') this[MAX_AGE] = mA trim(this) } get maxAge () { return this[MAX_AGE] } // resize the cache when the lengthCalculator changes. set lengthCalculator (lC) { if (typeof lC !== 'function') lC = naiveLength if (lC !== this[LENGTH_CALCULATOR]) { this[LENGTH_CALCULATOR] = lC this[LENGTH] = 0 this[LRU_LIST].forEach(hit => { hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) this[LENGTH] += hit.length }) } trim(this) } get lengthCalculator () { return this[LENGTH_CALCULATOR] } get length () { return this[LENGTH] } get itemCount () { return this[LRU_LIST].length } rforEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].tail; walker !== null;) { const prev = walker.prev forEachStep(this, fn, walker, thisp) walker = prev } } forEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].head; walker !== null;) { const next = walker.next forEachStep(this, fn, walker, thisp) walker = next } } keys () { return this[LRU_LIST].toArray().map(k => k.key) } values () { return this[LRU_LIST].toArray().map(k => k.value) } reset () { if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) { this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) } this[CACHE] = new Map() // hash of items by key this[LRU_LIST] = new Yallist() // list of items in order of use recency this[LENGTH] = 0 // length of items in the list } dump () { return this[LRU_LIST].map(hit => isStale(this, hit) ? false : { k: hit.key, v: hit.value, e: hit.now + (hit.maxAge || 0) }).toArray().filter(h => h) } dumpLru () { return this[LRU_LIST] } set (key, value, maxAge) { maxAge = maxAge || this[MAX_AGE] if (maxAge && typeof maxAge !== 'number') throw new TypeError('maxAge must be a number') const now = maxAge ? Date.now() : 0 const len = this[LENGTH_CALCULATOR](value, key) if (this[CACHE].has(key)) { if (len > this[MAX]) { del(this, this[CACHE].get(key)) return false } const node = this[CACHE].get(key) const item = node.value // dispose of the old one before overwriting // split out into 2 ifs for better coverage tracking if (this[DISPOSE]) { if (!this[NO_DISPOSE_ON_SET]) this[DISPOSE](key, item.value) } item.now = now item.maxAge = maxAge item.value = value this[LENGTH] += len - item.length item.length = len this.get(key) trim(this) return true } const hit = new Entry(key, value, len, now, maxAge) // oversized objects fall out of cache automatically. if (hit.length > this[MAX]) { if (this[DISPOSE]) this[DISPOSE](key, value) return false } this[LENGTH] += hit.length this[LRU_LIST].unshift(hit) this[CACHE].set(key, this[LRU_LIST].head) trim(this) return true } has (key) { if (!this[CACHE].has(key)) return false const hit = this[CACHE].get(key).value return !isStale(this, hit) } get (key) { return get(this, key, true) } peek (key) { return get(this, key, false) } pop () { const node = this[LRU_LIST].tail if (!node) return null del(this, node) return node.value } del (key) { del(this, this[CACHE].get(key)) } load (arr) { // reset the cache this.reset() const now = Date.now() // A previous serialized cache has the most recent items first for (let l = arr.length - 1; l >= 0; l--) { const hit = arr[l] const expiresAt = hit.e || 0 if (expiresAt === 0) // the item was created without expiration in a non aged cache this.set(hit.k, hit.v) else { const maxAge = expiresAt - now // dont add already expired items if (maxAge > 0) { this.set(hit.k, hit.v, maxAge) } } } } prune () { this[CACHE].forEach((value, key) => get(this, key, false)) } } const get = (self, key, doUse) => { const node = self[CACHE].get(key) if (node) { const hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) return undefined } else { if (doUse) { if (self[UPDATE_AGE_ON_GET]) node.value.now = Date.now() self[LRU_LIST].unshiftNode(node) } } return hit.value } } const isStale = (self, hit) => { if (!hit || (!hit.maxAge && !self[MAX_AGE])) return false const diff = Date.now() - hit.now return hit.maxAge ? diff > hit.maxAge : self[MAX_AGE] && (diff > self[MAX_AGE]) } const trim = self => { if (self[LENGTH] > self[MAX]) { for (let walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) { // We know that we're about to delete this one, and also // what the next least recently used key will be, so just // go ahead and set it now. const prev = walker.prev del(self, walker) walker = prev } } } const del = (self, node) => { if (node) { const hit = node.value if (self[DISPOSE]) self[DISPOSE](hit.key, hit.value) self[LENGTH] -= hit.length self[CACHE].delete(hit.key) self[LRU_LIST].removeNode(node) } } class Entry { constructor (key, value, length, now, maxAge) { this.key = key this.value = value this.length = length this.now = now this.maxAge = maxAge || 0 } } const forEachStep = (self, fn, node, thisp) => { let hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) hit = undefined } if (hit) fn.call(thisp, hit.value, hit.key, self) } module.exports = LRUCache /***/ }), /***/ 28479: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const ANY = Symbol('SemVer ANY') // hoisted class for cyclic dependency class Comparator { static get ANY () { return ANY } constructor (comp, options) { options = parseOptions(options) if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } comp = comp.trim().split(/\s+/).join(' ') debug('comparator', comp, options) this.options = options this.loose = !!options.loose this.parse(comp) if (this.semver === ANY) { this.value = '' } else { this.value = this.operator + this.semver.version } debug('comp', this) } parse (comp) { const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] const m = comp.match(r) if (!m) { throw new TypeError(`Invalid comparator: ${comp}`) } this.operator = m[1] !== undefined ? m[1] : '' if (this.operator === '=') { this.operator = '' } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY } else { this.semver = new SemVer(m[2], this.options.loose) } } toString () { return this.value } test (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY || version === ANY) { return true } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } return cmp(version, this.operator, this.semver, this.options) } intersects (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (this.operator === '') { if (this.value === '') { return true } return new Range(comp.value, options).test(this.value) } else if (comp.operator === '') { if (comp.value === '') { return true } return new Range(this.value, options).test(comp.semver) } options = parseOptions(options) // Special cases where nothing can possibly be lower if (options.includePrerelease && (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { return false } if (!options.includePrerelease && (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { return false } // Same direction increasing (> or >=) if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { return true } // Same direction decreasing (< or <=) if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { return true } // same SemVer and both sides are inclusive (<= or >=) if ( (this.semver.version === comp.semver.version) && this.operator.includes('=') && comp.operator.includes('=')) { return true } // opposite directions less than if (cmp(this.semver, '<', comp.semver, options) && this.operator.startsWith('>') && comp.operator.startsWith('<')) { return true } // opposite directions greater than if (cmp(this.semver, '>', comp.semver, options) && this.operator.startsWith('<') && comp.operator.startsWith('>')) { return true } return false } } module.exports = Comparator const parseOptions = __webpack_require__(33586) const { safeRe: re, t } = __webpack_require__(48662) const cmp = __webpack_require__(82231) const debug = __webpack_require__(32386) const SemVer = __webpack_require__(54092) const Range = __webpack_require__(72027) /***/ }), /***/ 72027: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // hoisted class for cyclic dependency class Range { constructor (range, options) { options = parseOptions(options) if (range instanceof Range) { if ( range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease ) { return range } else { return new Range(range.raw, options) } } if (range instanceof Comparator) { // just put it in the set and return this.raw = range.value this.set = [[range]] this.format() return this } this.options = options this.loose = !!options.loose this.includePrerelease = !!options.includePrerelease // First reduce all whitespace as much as possible so we do not have to rely // on potentially slow regexes like \s*. This is then stored and used for // future error messages as well. this.raw = range .trim() .split(/\s+/) .join(' ') // First, split on || this.set = this.raw .split('||') // map the range to a 2d array of comparators .map(r => this.parseRange(r.trim())) // throw out any comparator lists that are empty // this generally means that it was not a valid range, which is allowed // in loose mode, but will still throw if the WHOLE range is invalid. .filter(c => c.length) if (!this.set.length) { throw new TypeError(`Invalid SemVer Range: ${this.raw}`) } // if we have any that are not the null set, throw out null sets. if (this.set.length > 1) { // keep the first one, in case they're all null sets const first = this.set[0] this.set = this.set.filter(c => !isNullSet(c[0])) if (this.set.length === 0) { this.set = [first] } else if (this.set.length > 1) { // if we have any that are *, then the range is just * for (const c of this.set) { if (c.length === 1 && isAny(c[0])) { this.set = [c] break } } } } this.format() } format () { this.range = this.set .map((comps) => comps.join(' ').trim()) .join('||') .trim() return this.range } toString () { return this.range } parseRange (range) { // memoize range parsing for performance. // this is a very hot path, and fully deterministic. const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE) const memoKey = memoOpts + ':' + range const cached = cache.get(memoKey) if (cached) { return cached } const loose = this.options.loose // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range) // `~ 1.2.3` => `~1.2.3` range = range.replace(re[t.TILDETRIM], tildeTrimReplace) debug('tilde trim', range) // `^ 1.2.3` => `^1.2.3` range = range.replace(re[t.CARETTRIM], caretTrimReplace) debug('caret trim', range) // At this point, the range is completely trimmed and // ready to be split into comparators. let rangeList = range .split(' ') .map(comp => parseComparator(comp, this.options)) .join(' ') .split(/\s+/) // >=0.0.0 is equivalent to * .map(comp => replaceGTE0(comp, this.options)) if (loose) { // in loose mode, throw out any that are not valid comparators rangeList = rangeList.filter(comp => { debug('loose invalid filter', comp, this.options) return !!comp.match(re[t.COMPARATORLOOSE]) }) } debug('range list', rangeList) // if any comparators are the null set, then replace with JUST null set // if more than one comparator, remove any * comparators // also, don't include the same comparator more than once const rangeMap = new Map() const comparators = rangeList.map(comp => new Comparator(comp, this.options)) for (const comp of comparators) { if (isNullSet(comp)) { return [comp] } rangeMap.set(comp.value, comp) } if (rangeMap.size > 1 && rangeMap.has('')) { rangeMap.delete('') } const result = [...rangeMap.values()] cache.set(memoKey, result) return result } intersects (range, options) { if (!(range instanceof Range)) { throw new TypeError('a Range is required') } return this.set.some((thisComparators) => { return ( isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => { return ( isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { return rangeComparators.every((rangeComparator) => { return thisComparator.intersects(rangeComparator, options) }) }) ) }) ) }) } // if ANY of the sets match ALL of its comparators, then pass test (version) { if (!version) { return false } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } for (let i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true } } return false } } module.exports = Range const LRU = __webpack_require__(33573) const cache = new LRU({ max: 1000 }) const parseOptions = __webpack_require__(33586) const Comparator = __webpack_require__(28479) const debug = __webpack_require__(32386) const SemVer = __webpack_require__(54092) const { safeRe: re, t, comparatorTrimReplace, tildeTrimReplace, caretTrimReplace, } = __webpack_require__(48662) const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __webpack_require__(73903) const isNullSet = c => c.value === '<0.0.0-0' const isAny = c => c.value === '' // take a set of comparators and determine whether there // exists a version which can satisfy it const isSatisfiable = (comparators, options) => { let result = true const remainingComparators = comparators.slice() let testComparator = remainingComparators.pop() while (result && remainingComparators.length) { result = remainingComparators.every((otherComparator) => { return testComparator.intersects(otherComparator, options) }) testComparator = remainingComparators.pop() } return result } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. const parseComparator = (comp, options) => { debug('comp', comp, options) comp = replaceCarets(comp, options) debug('caret', comp) comp = replaceTildes(comp, options) debug('tildes', comp) comp = replaceXRanges(comp, options) debug('xrange', comp) comp = replaceStars(comp, options) debug('stars', comp) return comp } const isX = id => !id || id.toLowerCase() === 'x' || id === '*' // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 // ~0.0.1 --> >=0.0.1 <0.1.0-0 const replaceTildes = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceTilde(c, options)) .join(' ') } const replaceTilde = (comp, options) => { const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] return comp.replace(r, (_, M, m, p, pr) => { debug('tilde', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0 <${+M + 1}.0.0-0` } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0-0 ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` } else if (pr) { debug('replaceTilde pr', pr) ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } else { // ~1.2.3 == >=1.2.3 <1.3.0-0 ret = `>=${M}.${m}.${p } <${M}.${+m + 1}.0-0` } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 // ^1.2.3 --> >=1.2.3 <2.0.0-0 // ^1.2.0 --> >=1.2.0 <2.0.0-0 // ^0.0.1 --> >=0.0.1 <0.0.2-0 // ^0.1.0 --> >=0.1.0 <0.2.0-0 const replaceCarets = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceCaret(c, options)) .join(' ') } const replaceCaret = (comp, options) => { debug('caret', comp, options) const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] const z = options.includePrerelease ? '-0' : '' return comp.replace(r, (_, M, m, p, pr) => { debug('caret', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` } else if (isX(p)) { if (M === '0') { ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` } else { ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p}-${pr } <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p}-${pr } <${+M + 1}.0.0-0` } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p }${z} <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p }${z} <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p } <${+M + 1}.0.0-0` } } debug('caret return', ret) return ret }) } const replaceXRanges = (comp, options) => { debug('replaceXRanges', comp, options) return comp .split(/\s+/) .map((c) => replaceXRange(c, options)) .join(' ') } const replaceXRange = (comp, options) => { comp = comp.trim() const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] return comp.replace(r, (ret, gtlt, M, m, p, pr) => { debug('xRange', comp, ret, gtlt, M, m, p, pr) const xM = isX(M) const xm = xM || isX(m) const xp = xm || isX(p) const anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } // if we're including prereleases in the match, then we need // to fix this to -0, the lowest possible prerelease value pr = options.includePrerelease ? '-0' : '' if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0-0' } else { // nothing is forbidden ret = '*' } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0 } p = 0 if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 gtlt = '>=' if (xm) { M = +M + 1 m = 0 p = 0 } else { m = +m + 1 p = 0 } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<' if (xm) { M = +M + 1 } else { m = +m + 1 } } if (gtlt === '<') { pr = '-0' } ret = `${gtlt + M}.${m}.${p}${pr}` } else if (xm) { ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` } else if (xp) { ret = `>=${M}.${m}.0${pr } <${M}.${+m + 1}.0-0` } debug('xRange return', ret) return ret }) } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. const replaceStars = (comp, options) => { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp .trim() .replace(re[t.STAR], '') } const replaceGTE0 = (comp, options) => { debug('replaceGTE0', comp, options) return comp .trim() .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') } // This function is passed to string.replace(re[t.HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 const hyphenReplace = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) => { if (isX(fM)) { from = '' } else if (isX(fm)) { from = `>=${fM}.0.0${incPr ? '-0' : ''}` } else if (isX(fp)) { from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` } else if (fpr) { from = `>=${from}` } else { from = `>=${from}${incPr ? '-0' : ''}` } if (isX(tM)) { to = '' } else if (isX(tm)) { to = `<${+tM + 1}.0.0-0` } else if (isX(tp)) { to = `<${tM}.${+tm + 1}.0-0` } else if (tpr) { to = `<=${tM}.${tm}.${tp}-${tpr}` } else if (incPr) { to = `<${tM}.${tm}.${+tp + 1}-0` } else { to = `<=${to}` } return `${from} ${to}`.trim() } const testSet = (set, version, options) => { for (let i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (let i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === Comparator.ANY) { continue } if (set[i].semver.prerelease.length > 0) { const allowed = set[i].semver if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } /***/ }), /***/ 54092: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const debug = __webpack_require__(32386) const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(73903) const { safeRe: re, t } = __webpack_require__(48662) const parseOptions = __webpack_require__(33586) const { compareIdentifiers } = __webpack_require__(26618) class SemVer { constructor (version, options) { options = parseOptions(options) if (version instanceof SemVer) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) } if (version.length > MAX_LENGTH) { throw new TypeError( `version is longer than ${MAX_LENGTH} characters` ) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose // this isn't actually relevant for versions, but keep it so that we // don't run into trouble passing this.options around. this.includePrerelease = !!options.includePrerelease const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) if (!m) { throw new TypeError(`Invalid Version: ${version}`) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map((id) => { if (/^[0-9]+$/.test(id)) { const num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } format () { this.version = `${this.major}.${this.minor}.${this.patch}` if (this.prerelease.length) { this.version += `-${this.prerelease.join('.')}` } return this.version } toString () { return this.version } compare (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { if (typeof other === 'string' && other === this.version) { return 0 } other = new SemVer(other, this.options) } if (other.version === this.version) { return 0 } return this.compareMain(other) || this.comparePre(other) } compareMain (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return ( compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) ) } comparePre (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } let i = 0 do { const a = this.prerelease[i] const b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } compareBuild (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } let i = 0 do { const a = this.build[i] const b = other.build[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc (release, identifier, identifierBase) { switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier, identifierBase) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier, identifierBase) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier, identifierBase) this.inc('pre', identifier, identifierBase) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier, identifierBase) } this.inc('pre', identifier, identifierBase) break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if ( this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0 ) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. case 'pre': { const base = Number(identifierBase) ? 1 : 0 if (!identifier && identifierBase === false) { throw new Error('invalid increment argument: identifier is empty') } if (this.prerelease.length === 0) { this.prerelease = [base] } else { let i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything if (identifier === this.prerelease.join('.') && identifierBase === false) { throw new Error('invalid increment argument: identifier already exists') } this.prerelease.push(base) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 let prerelease = [identifier, base] if (identifierBase === false) { prerelease = [identifier] } if (compareIdentifiers(this.prerelease[0], identifier) === 0) { if (isNaN(this.prerelease[1])) { this.prerelease = prerelease } } else { this.prerelease = prerelease } } break } default: throw new Error(`invalid increment argument: ${release}`) } this.raw = this.format() if (this.build.length) { this.raw += `+${this.build.join('.')}` } return this } } module.exports = SemVer /***/ }), /***/ 1953: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(14143) const clean = (version, options) => { const s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } module.exports = clean /***/ }), /***/ 82231: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const eq = __webpack_require__(78770) const neq = __webpack_require__(43421) const gt = __webpack_require__(42127) const gte = __webpack_require__(74630) const lt = __webpack_require__(95623) const lte = __webpack_require__(86713) const cmp = (a, op, b, loose) => { switch (op) { case '===': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a === b case '!==': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError(`Invalid operator: ${op}`) } } module.exports = cmp /***/ }), /***/ 33432: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(54092) const parse = __webpack_require__(14143) const { safeRe: re, t } = __webpack_require__(48662) const coerce = (version, options) => { if (version instanceof SemVer) { return version } if (typeof version === 'number') { version = String(version) } if (typeof version !== 'string') { return null } options = options || {} let match = null if (!options.rtl) { match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]) } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4' // // Walk through the string checking with a /g regexp // Manually set the index so as to pick up overlapping matches. // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL] let next while ((next = coerceRtlRegex.exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next } coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length } // leave it in a clean state coerceRtlRegex.lastIndex = -1 } if (match === null) { return null } const major = match[2] const minor = match[3] || '0' const patch = match[4] || '0' const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '' const build = options.includePrerelease && match[6] ? `+${match[6]}` : '' return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options) } module.exports = coerce /***/ }), /***/ 80885: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(54092) const compareBuild = (a, b, loose) => { const versionA = new SemVer(a, loose) const versionB = new SemVer(b, loose) return versionA.compare(versionB) || versionA.compareBuild(versionB) } module.exports = compareBuild /***/ }), /***/ 46638: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(2499) const compareLoose = (a, b) => compare(a, b, true) module.exports = compareLoose /***/ }), /***/ 2499: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(54092) const compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)) module.exports = compare /***/ }), /***/ 62844: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(14143) const diff = (version1, version2) => { const v1 = parse(version1, null, true) const v2 = parse(version2, null, true) const comparison = v1.compare(v2) if (comparison === 0) { return null } const v1Higher = comparison > 0 const highVersion = v1Higher ? v1 : v2 const lowVersion = v1Higher ? v2 : v1 const highHasPre = !!highVersion.prerelease.length const lowHasPre = !!lowVersion.prerelease.length if (lowHasPre && !highHasPre) { // Going from prerelease -> no prerelease requires some special casing // If the low version has only a major, then it will always be a major // Some examples: // 1.0.0-1 -> 1.0.0 // 1.0.0-1 -> 1.1.1 // 1.0.0-1 -> 2.0.0 if (!lowVersion.patch && !lowVersion.minor) { return 'major' } // Otherwise it can be determined by checking the high version if (highVersion.patch) { // anything higher than a patch bump would result in the wrong version return 'patch' } if (highVersion.minor) { // anything higher than a minor bump would result in the wrong version return 'minor' } // bumping major/minor/patch all have same result return 'major' } // add the `pre` prefix if we are going to a prerelease version const prefix = highHasPre ? 'pre' : '' if (v1.major !== v2.major) { return prefix + 'major' } if (v1.minor !== v2.minor) { return prefix + 'minor' } if (v1.patch !== v2.patch) { return prefix + 'patch' } // high and low are preleases return 'prerelease' } module.exports = diff /***/ }), /***/ 78770: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(2499) const eq = (a, b, loose) => compare(a, b, loose) === 0 module.exports = eq /***/ }), /***/ 42127: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(2499) const gt = (a, b, loose) => compare(a, b, loose) > 0 module.exports = gt /***/ }), /***/ 74630: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(2499) const gte = (a, b, loose) => compare(a, b, loose) >= 0 module.exports = gte /***/ }), /***/ 67460: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(54092) const inc = (version, release, options, identifier, identifierBase) => { if (typeof (options) === 'string') { identifierBase = identifier identifier = options options = undefined } try { return new SemVer( version instanceof SemVer ? version.version : version, options ).inc(release, identifier, identifierBase).version } catch (er) { return null } } module.exports = inc /***/ }), /***/ 95623: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(2499) const lt = (a, b, loose) => compare(a, b, loose) < 0 module.exports = lt /***/ }), /***/ 86713: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(2499) const lte = (a, b, loose) => compare(a, b, loose) <= 0 module.exports = lte /***/ }), /***/ 75270: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(54092) const major = (a, loose) => new SemVer(a, loose).major module.exports = major /***/ }), /***/ 24298: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(54092) const minor = (a, loose) => new SemVer(a, loose).minor module.exports = minor /***/ }), /***/ 43421: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(2499) const neq = (a, b, loose) => compare(a, b, loose) !== 0 module.exports = neq /***/ }), /***/ 14143: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(54092) const parse = (version, options, throwErrors = false) => { if (version instanceof SemVer) { return version } try { return new SemVer(version, options) } catch (er) { if (!throwErrors) { return null } throw er } } module.exports = parse /***/ }), /***/ 82607: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(54092) const patch = (a, loose) => new SemVer(a, loose).patch module.exports = patch /***/ }), /***/ 94847: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(14143) const prerelease = (version, options) => { const parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } module.exports = prerelease /***/ }), /***/ 15474: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(2499) const rcompare = (a, b, loose) => compare(b, a, loose) module.exports = rcompare /***/ }), /***/ 46628: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(80885) const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) module.exports = rsort /***/ }), /***/ 40194: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(72027) const satisfies = (version, range, options) => { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } module.exports = satisfies /***/ }), /***/ 84136: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(80885) const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) module.exports = sort /***/ }), /***/ 75142: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(14143) const valid = (version, options) => { const v = parse(version, options) return v ? v.version : null } module.exports = valid /***/ }), /***/ 33505: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // just pre-load all the stuff that index.js lazily exports const internalRe = __webpack_require__(48662) const constants = __webpack_require__(73903) const SemVer = __webpack_require__(54092) const identifiers = __webpack_require__(26618) const parse = __webpack_require__(14143) const valid = __webpack_require__(75142) const clean = __webpack_require__(1953) const inc = __webpack_require__(67460) const diff = __webpack_require__(62844) const major = __webpack_require__(75270) const minor = __webpack_require__(24298) const patch = __webpack_require__(82607) const prerelease = __webpack_require__(94847) const compare = __webpack_require__(2499) const rcompare = __webpack_require__(15474) const compareLoose = __webpack_require__(46638) const compareBuild = __webpack_require__(80885) const sort = __webpack_require__(84136) const rsort = __webpack_require__(46628) const gt = __webpack_require__(42127) const lt = __webpack_require__(95623) const eq = __webpack_require__(78770) const neq = __webpack_require__(43421) const gte = __webpack_require__(74630) const lte = __webpack_require__(86713) const cmp = __webpack_require__(82231) const coerce = __webpack_require__(33432) const Comparator = __webpack_require__(28479) const Range = __webpack_require__(72027) const satisfies = __webpack_require__(40194) const toComparators = __webpack_require__(68793) const maxSatisfying = __webpack_require__(65097) const minSatisfying = __webpack_require__(83931) const minVersion = __webpack_require__(56082) const validRange = __webpack_require__(74442) const outside = __webpack_require__(3819) const gtr = __webpack_require__(28692) const ltr = __webpack_require__(27032) const intersects = __webpack_require__(30484) const simplifyRange = __webpack_require__(75683) const subset = __webpack_require__(29445) module.exports = { parse, valid, clean, inc, diff, major, minor, patch, prerelease, compare, rcompare, compareLoose, compareBuild, sort, rsort, gt, lt, eq, neq, gte, lte, cmp, coerce, Comparator, Range, satisfies, toComparators, maxSatisfying, minSatisfying, minVersion, validRange, outside, gtr, ltr, intersects, simplifyRange, subset, SemVer, re: internalRe.re, src: internalRe.src, tokens: internalRe.t, SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, RELEASE_TYPES: constants.RELEASE_TYPES, compareIdentifiers: identifiers.compareIdentifiers, rcompareIdentifiers: identifiers.rcompareIdentifiers, } /***/ }), /***/ 73903: /***/ ((module) => { // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. const SEMVER_SPEC_VERSION = '2.0.0' const MAX_LENGTH = 256 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. const MAX_SAFE_COMPONENT_LENGTH = 16 // Max safe length for a build identifier. The max length minus 6 characters for // the shortest version with a build 0.0.0+BUILD. const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 const RELEASE_TYPES = [ 'major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease', ] module.exports = { MAX_LENGTH, MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_SAFE_INTEGER, RELEASE_TYPES, SEMVER_SPEC_VERSION, FLAG_INCLUDE_PRERELEASE: 0b001, FLAG_LOOSE: 0b010, } /***/ }), /***/ 32386: /***/ ((module) => { const debug = ( typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ) ? (...args) => console.error('SEMVER', ...args) : () => {} module.exports = debug /***/ }), /***/ 26618: /***/ ((module) => { const numeric = /^[0-9]+$/ const compareIdentifiers = (a, b) => { const anum = numeric.test(a) const bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) module.exports = { compareIdentifiers, rcompareIdentifiers, } /***/ }), /***/ 33586: /***/ ((module) => { // parse out just the options we care about const looseOption = Object.freeze({ loose: true }) const emptyOpts = Object.freeze({ }) const parseOptions = options => { if (!options) { return emptyOpts } if (typeof options !== 'object') { return looseOption } return options } module.exports = parseOptions /***/ }), /***/ 48662: /***/ ((module, exports, __webpack_require__) => { const { MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_LENGTH, } = __webpack_require__(73903) const debug = __webpack_require__(32386) exports = module.exports = {} // The actual regexps go on exports.re const re = exports.re = [] const safeRe = exports.safeRe = [] const src = exports.src = [] const t = exports.t = {} let R = 0 const LETTERDASHNUMBER = '[a-zA-Z0-9-]' // Replace some greedy regex tokens to prevent regex dos issues. These regex are // used internally via the safeRe object since all inputs in this library get // normalized first to trim and collapse all extra whitespace. The original // regexes are exported for userland consumption and lower level usage. A // future breaking change could export the safer regex only with a note that // all input should have extra whitespace removed. const safeRegexReplacements = [ ['\\s', 1], ['\\d', MAX_LENGTH], [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], ] const makeSafeRegex = (value) => { for (const [token, max] of safeRegexReplacements) { value = value .split(`${token}*`).join(`${token}{0,${max}}`) .split(`${token}+`).join(`${token}{1,${max}}`) } return value } const createToken = (name, value, isGlobal) => { const safe = makeSafeRegex(value) const index = R++ debug(name, index, value) t[name] = index src[index] = value re[index] = new RegExp(value, isGlobal ? 'g' : undefined) safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) } // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') createToken('NUMERICIDENTIFIERLOOSE', '\\d+') // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) // ## Main Version // Three dot-separated numeric identifiers. createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`) createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] }|${src[t.NONNUMERICIDENTIFIER]})`) createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] }|${src[t.NONNUMERICIDENTIFIER]})`) // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] }(?:\\.${src[t.BUILDIDENTIFIER]})*))`) // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. createToken('FULLPLAIN', `v?${src[t.MAINVERSION] }${src[t.PRERELEASE]}?${ src[t.BUILD]}?`) createToken('FULL', `^${src[t.FULLPLAIN]}$`) // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] }${src[t.PRERELEASELOOSE]}?${ src[t.BUILD]}?`) createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) createToken('GTLT', '((?:<|>)?=?)') // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) // Coercion. // Extract anything that could conceivably be a part of a valid semver createToken('COERCEPLAIN', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`) createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`) createToken('COERCEFULL', src[t.COERCEPLAIN] + `(?:${src[t.PRERELEASE]})?` + `(?:${src[t.BUILD]})?` + `(?:$|[^\\d])`) createToken('COERCERTL', src[t.COERCE], true) createToken('COERCERTLFULL', src[t.COERCEFULL], true) // Tilde ranges. // Meaning is "reasonably at or greater than" createToken('LONETILDE', '(?:~>?)') createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) exports.tildeTrimReplace = '$1~' createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) // Caret ranges. // Meaning is "at least and backwards compatible with" createToken('LONECARET', '(?:\\^)') createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) exports.caretTrimReplace = '$1^' createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) // A simple gt/lt/eq thing, or just "" to indicate "any version" createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) exports.comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`) createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`) // Star ranges basically just allow anything at all. createToken('STAR', '(<|>)?=?\\s*\\*') // >=0.0.0 is like a star createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') /***/ }), /***/ 28692: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Determine if version is greater than all the versions possible in the range. const outside = __webpack_require__(3819) const gtr = (version, range, options) => outside(version, range, '>', options) module.exports = gtr /***/ }), /***/ 30484: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(72027) const intersects = (r1, r2, options) => { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2, options) } module.exports = intersects /***/ }), /***/ 27032: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const outside = __webpack_require__(3819) // Determine if version is less than all the versions possible in the range const ltr = (version, range, options) => outside(version, range, '<', options) module.exports = ltr /***/ }), /***/ 65097: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(54092) const Range = __webpack_require__(72027) const maxSatisfying = (versions, range, options) => { let max = null let maxSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } module.exports = maxSatisfying /***/ }), /***/ 83931: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(54092) const Range = __webpack_require__(72027) const minSatisfying = (versions, range, options) => { let min = null let minSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } module.exports = minSatisfying /***/ }), /***/ 56082: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(54092) const Range = __webpack_require__(72027) const gt = __webpack_require__(42127) const minVersion = (range, loose) => { range = new Range(range, loose) let minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let setMin = null comparators.forEach((comparator) => { // Clone to avoid manipulating the comparator's semver object. const compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!setMin || gt(compver, setMin)) { setMin = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error(`Unexpected operation: ${comparator.operator}`) } }) if (setMin && (!minver || gt(minver, setMin))) { minver = setMin } } if (minver && range.test(minver)) { return minver } return null } module.exports = minVersion /***/ }), /***/ 3819: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(54092) const Comparator = __webpack_require__(28479) const { ANY } = Comparator const Range = __webpack_require__(72027) const satisfies = __webpack_require__(40194) const gt = __webpack_require__(42127) const lt = __webpack_require__(95623) const lte = __webpack_require__(86713) const gte = __webpack_require__(74630) const outside = (version, range, hilo, options) => { version = new SemVer(version, options) range = new Range(range, options) let gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisfies the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let high = null let low = null comparators.forEach((comparator) => { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } module.exports = outside /***/ }), /***/ 75683: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // given a set of versions and a range, create a "simplified" range // that includes the same versions that the original range does // If the original range is shorter than the simplified one, return that. const satisfies = __webpack_require__(40194) const compare = __webpack_require__(2499) module.exports = (versions, range, options) => { const set = [] let first = null let prev = null const v = versions.sort((a, b) => compare(a, b, options)) for (const version of v) { const included = satisfies(version, range, options) if (included) { prev = version if (!first) { first = version } } else { if (prev) { set.push([first, prev]) } prev = null first = null } } if (first) { set.push([first, null]) } const ranges = [] for (const [min, max] of set) { if (min === max) { ranges.push(min) } else if (!max && min === v[0]) { ranges.push('*') } else if (!max) { ranges.push(`>=${min}`) } else if (min === v[0]) { ranges.push(`<=${max}`) } else { ranges.push(`${min} - ${max}`) } } const simplified = ranges.join(' || ') const original = typeof range.raw === 'string' ? range.raw : String(range) return simplified.length < original.length ? simplified : range } /***/ }), /***/ 29445: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(72027) const Comparator = __webpack_require__(28479) const { ANY } = Comparator const satisfies = __webpack_require__(40194) const compare = __webpack_require__(2499) // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: // - Every simple range `r1, r2, ...` is a null set, OR // - Every simple range `r1, r2, ...` which is not a null set is a subset of // some `R1, R2, ...` // // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: // - If c is only the ANY comparator // - If C is only the ANY comparator, return true // - Else if in prerelease mode, return false // - else replace c with `[>=0.0.0]` // - If C is only the ANY comparator // - if in prerelease mode, return true // - else replace C with `[>=0.0.0]` // - Let EQ be the set of = comparators in c // - If EQ is more than one, return true (null set) // - Let GT be the highest > or >= comparator in c // - Let LT be the lowest < or <= comparator in c // - If GT and LT, and GT.semver > LT.semver, return true (null set) // - If any C is a = range, and GT or LT are set, return false // - If EQ // - If GT, and EQ does not satisfy GT, return true (null set) // - If LT, and EQ does not satisfy LT, return true (null set) // - If EQ satisfies every C, return true // - Else return false // - If GT // - If GT.semver is lower than any > or >= comp in C, return false // - If GT is >=, and GT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the GT.semver tuple, return false // - If LT // - If LT.semver is greater than any < or <= comp in C, return false // - If LT is <=, and LT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the LT.semver tuple, return false // - Else return true const subset = (sub, dom, options = {}) => { if (sub === dom) { return true } sub = new Range(sub, options) dom = new Range(dom, options) let sawNonNull = false OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { const isSub = simpleSubset(simpleSub, simpleDom, options) sawNonNull = sawNonNull || isSub !== null if (isSub) { continue OUTER } } // the null set is a subset of everything, but null simple ranges in // a complex range should be ignored. so if we saw a non-null range, // then we know this isn't a subset, but if EVERY simple range was null, // then it is a subset. if (sawNonNull) { return false } } return true } const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] const minimumVersion = [new Comparator('>=0.0.0')] const simpleSubset = (sub, dom, options) => { if (sub === dom) { return true } if (sub.length === 1 && sub[0].semver === ANY) { if (dom.length === 1 && dom[0].semver === ANY) { return true } else if (options.includePrerelease) { sub = minimumVersionWithPreRelease } else { sub = minimumVersion } } if (dom.length === 1 && dom[0].semver === ANY) { if (options.includePrerelease) { return true } else { dom = minimumVersion } } const eqSet = new Set() let gt, lt for (const c of sub) { if (c.operator === '>' || c.operator === '>=') { gt = higherGT(gt, c, options) } else if (c.operator === '<' || c.operator === '<=') { lt = lowerLT(lt, c, options) } else { eqSet.add(c.semver) } } if (eqSet.size > 1) { return null } let gtltComp if (gt && lt) { gtltComp = compare(gt.semver, lt.semver, options) if (gtltComp > 0) { return null } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { return null } } // will iterate one or zero times for (const eq of eqSet) { if (gt && !satisfies(eq, String(gt), options)) { return null } if (lt && !satisfies(eq, String(lt), options)) { return null } for (const c of dom) { if (!satisfies(eq, String(c), options)) { return false } } return true } let higher, lower let hasDomLT, hasDomGT // if the subset has a prerelease, we need a comparator in the superset // with the same tuple and a prerelease, or it's not a subset let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false // exception: <1.2.3-0 is the same as <1.2.3 if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { needDomLTPre = false } for (const c of dom) { hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' if (gt) { if (needDomGTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { needDomGTPre = false } } if (c.operator === '>' || c.operator === '>=') { higher = higherGT(gt, c, options) if (higher === c && higher !== gt) { return false } } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { return false } } if (lt) { if (needDomLTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { needDomLTPre = false } } if (c.operator === '<' || c.operator === '<=') { lower = lowerLT(lt, c, options) if (lower === c && lower !== lt) { return false } } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { return false } } if (!c.operator && (lt || gt) && gtltComp !== 0) { return false } } // if there was a < or >, and nothing in the dom, then must be false // UNLESS it was limited by another range in the other direction. // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 if (gt && hasDomLT && !lt && gtltComp !== 0) { return false } if (lt && hasDomGT && !gt && gtltComp !== 0) { return false } // we needed a prerelease range in a specific tuple, but didn't get one // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, // because it includes prereleases in the 1.2.3 tuple if (needDomGTPre || needDomLTPre) { return false } return true } // >=1.2.3 is lower than >1.2.3 const higherGT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp > 0 ? a : comp < 0 ? b : b.operator === '>' && a.operator === '>=' ? b : a } // <=1.2.3 is higher than <1.2.3 const lowerLT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp < 0 ? a : comp > 0 ? b : b.operator === '<' && a.operator === '<=' ? b : a } module.exports = subset /***/ }), /***/ 68793: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(72027) // Mostly just for testing and legacy API reasons const toComparators = (range, options) => new Range(range, options).set .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) module.exports = toComparators /***/ }), /***/ 74442: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(72027) const validRange = (range, options) => { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } module.exports = validRange /***/ }), /***/ 9217: /***/ ((module) => { "use strict"; module.exports = function (Yallist) { Yallist.prototype[Symbol.iterator] = function* () { for (let walker = this.head; walker; walker = walker.next) { yield walker.value } } } /***/ }), /***/ 87600: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = Yallist Yallist.Node = Node Yallist.create = Yallist function Yallist (list) { var self = this if (!(self instanceof Yallist)) { self = new Yallist() } self.tail = null self.head = null self.length = 0 if (list && typeof list.forEach === 'function') { list.forEach(function (item) { self.push(item) }) } else if (arguments.length > 0) { for (var i = 0, l = arguments.length; i < l; i++) { self.push(arguments[i]) } } return self } Yallist.prototype.removeNode = function (node) { if (node.list !== this) { throw new Error('removing node which does not belong to this list') } var next = node.next var prev = node.prev if (next) { next.prev = prev } if (prev) { prev.next = next } if (node === this.head) { this.head = next } if (node === this.tail) { this.tail = prev } node.list.length-- node.next = null node.prev = null node.list = null return next } Yallist.prototype.unshiftNode = function (node) { if (node === this.head) { return } if (node.list) { node.list.removeNode(node) } var head = this.head node.list = this node.next = head if (head) { head.prev = node } this.head = node if (!this.tail) { this.tail = node } this.length++ } Yallist.prototype.pushNode = function (node) { if (node === this.tail) { return } if (node.list) { node.list.removeNode(node) } var tail = this.tail node.list = this node.prev = tail if (tail) { tail.next = node } this.tail = node if (!this.head) { this.head = node } this.length++ } Yallist.prototype.push = function () { for (var i = 0, l = arguments.length; i < l; i++) { push(this, arguments[i]) } return this.length } Yallist.prototype.unshift = function () { for (var i = 0, l = arguments.length; i < l; i++) { unshift(this, arguments[i]) } return this.length } Yallist.prototype.pop = function () { if (!this.tail) { return undefined } var res = this.tail.value this.tail = this.tail.prev if (this.tail) { this.tail.next = null } else { this.head = null } this.length-- return res } Yallist.prototype.shift = function () { if (!this.head) { return undefined } var res = this.head.value this.head = this.head.next if (this.head) { this.head.prev = null } else { this.tail = null } this.length-- return res } Yallist.prototype.forEach = function (fn, thisp) { thisp = thisp || this for (var walker = this.head, i = 0; walker !== null; i++) { fn.call(thisp, walker.value, i, this) walker = walker.next } } Yallist.prototype.forEachReverse = function (fn, thisp) { thisp = thisp || this for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { fn.call(thisp, walker.value, i, this) walker = walker.prev } } Yallist.prototype.get = function (n) { for (var i = 0, walker = this.head; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.next } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.getReverse = function (n) { for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.prev } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.map = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.head; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.next } return res } Yallist.prototype.mapReverse = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.tail; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.prev } return res } Yallist.prototype.reduce = function (fn, initial) { var acc var walker = this.head if (arguments.length > 1) { acc = initial } else if (this.head) { walker = this.head.next acc = this.head.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = 0; walker !== null; i++) { acc = fn(acc, walker.value, i) walker = walker.next } return acc } Yallist.prototype.reduceReverse = function (fn, initial) { var acc var walker = this.tail if (arguments.length > 1) { acc = initial } else if (this.tail) { walker = this.tail.prev acc = this.tail.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = this.length - 1; walker !== null; i--) { acc = fn(acc, walker.value, i) walker = walker.prev } return acc } Yallist.prototype.toArray = function () { var arr = new Array(this.length) for (var i = 0, walker = this.head; walker !== null; i++) { arr[i] = walker.value walker = walker.next } return arr } Yallist.prototype.toArrayReverse = function () { var arr = new Array(this.length) for (var i = 0, walker = this.tail; walker !== null; i++) { arr[i] = walker.value walker = walker.prev } return arr } Yallist.prototype.slice = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = 0, walker = this.head; walker !== null && i < from; i++) { walker = walker.next } for (; walker !== null && i < to; i++, walker = walker.next) { ret.push(walker.value) } return ret } Yallist.prototype.sliceReverse = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { walker = walker.prev } for (; walker !== null && i > from; i--, walker = walker.prev) { ret.push(walker.value) } return ret } Yallist.prototype.splice = function (start, deleteCount, ...nodes) { if (start > this.length) { start = this.length - 1 } if (start < 0) { start = this.length + start; } for (var i = 0, walker = this.head; walker !== null && i < start; i++) { walker = walker.next } var ret = [] for (var i = 0; walker && i < deleteCount; i++) { ret.push(walker.value) walker = this.removeNode(walker) } if (walker === null) { walker = this.tail } if (walker !== this.head && walker !== this.tail) { walker = walker.prev } for (var i = 0; i < nodes.length; i++) { walker = insert(this, walker, nodes[i]) } return ret; } Yallist.prototype.reverse = function () { var head = this.head var tail = this.tail for (var walker = head; walker !== null; walker = walker.prev) { var p = walker.prev walker.prev = walker.next walker.next = p } this.head = tail this.tail = head return this } function insert (self, node, value) { var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self) if (inserted.next === null) { self.tail = inserted } if (inserted.prev === null) { self.head = inserted } self.length++ return inserted } function push (self, item) { self.tail = new Node(item, self.tail, null, self) if (!self.head) { self.head = self.tail } self.length++ } function unshift (self, item) { self.head = new Node(item, null, self.head, self) if (!self.tail) { self.tail = self.head } self.length++ } function Node (value, prev, next, list) { if (!(this instanceof Node)) { return new Node(value, prev, next, list) } this.list = list this.value = value if (prev) { prev.next = this this.prev = prev } else { this.prev = null } if (next) { next.prev = this this.next = next } else { this.next = null } } try { // add if support for Symbol.iterator is present __webpack_require__(9217)(Yallist) } catch (er) {} /***/ }), /***/ 88507: /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "Diff": () => (/* binding */ Diff), /* harmony export */ "diffChars": () => (/* binding */ diffChars), /* harmony export */ "diffWords": () => (/* binding */ diffWords), /* harmony export */ "diffWordsWithSpace": () => (/* binding */ diffWordsWithSpace), /* harmony export */ "diffLines": () => (/* binding */ diffLines), /* harmony export */ "diffTrimmedLines": () => (/* binding */ diffTrimmedLines), /* harmony export */ "diffSentences": () => (/* binding */ diffSentences), /* harmony export */ "diffCss": () => (/* binding */ diffCss), /* harmony export */ "diffJson": () => (/* binding */ diffJson), /* harmony export */ "diffArrays": () => (/* binding */ diffArrays), /* harmony export */ "structuredPatch": () => (/* binding */ structuredPatch), /* harmony export */ "createTwoFilesPatch": () => (/* binding */ createTwoFilesPatch), /* harmony export */ "createPatch": () => (/* binding */ createPatch), /* harmony export */ "applyPatch": () => (/* binding */ applyPatch), /* harmony export */ "applyPatches": () => (/* binding */ applyPatches), /* harmony export */ "parsePatch": () => (/* binding */ parsePatch), /* harmony export */ "merge": () => (/* binding */ merge), /* harmony export */ "convertChangesToDMP": () => (/* binding */ convertChangesToDMP), /* harmony export */ "convertChangesToXML": () => (/* binding */ convertChangesToXML), /* harmony export */ "canonicalize": () => (/* binding */ canonicalize) /* harmony export */ }); function Diff() {} Diff.prototype = { diff: function diff(oldString, newString) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var callback = options.callback; if (typeof options === 'function') { callback = options; options = {}; } this.options = options; var self = this; function done(value) { if (callback) { setTimeout(function () { callback(undefined, value); }, 0); return true; } else { return value; } } // Allow subclasses to massage the input prior to running oldString = this.castInput(oldString); newString = this.castInput(newString); oldString = this.removeEmpty(this.tokenize(oldString)); newString = this.removeEmpty(this.tokenize(newString)); var newLen = newString.length, oldLen = oldString.length; var editLength = 1; var maxEditLength = newLen + oldLen; var bestPath = [{ newPos: -1, components: [] }]; // Seed editLength = 0, i.e. the content starts with the same values var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { // Identity per the equality and tokenizer return done([{ value: this.join(newString), count: newString.length }]); } // Main worker method. checks all permutations of a given edit length for acceptance. function execEditLength() { for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { var basePath = void 0; var addPath = bestPath[diagonalPath - 1], removePath = bestPath[diagonalPath + 1], _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; if (addPath) { // No one else is going to attempt to use this value, clear it bestPath[diagonalPath - 1] = undefined; } var canAdd = addPath && addPath.newPos + 1 < newLen, canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen; if (!canAdd && !canRemove) { // If this path is a terminal then prune bestPath[diagonalPath] = undefined; continue; } // Select the diagonal that we want to branch from. We select the prior // path whose position in the new string is the farthest from the origin // and does not pass the bounds of the diff graph if (!canAdd || canRemove && addPath.newPos < removePath.newPos) { basePath = clonePath(removePath); self.pushComponent(basePath.components, undefined, true); } else { basePath = addPath; // No need to clone, we've pulled it from the list basePath.newPos++; self.pushComponent(basePath.components, true, undefined); } _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) { return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken)); } else { // Otherwise track this path as a potential candidate and continue. bestPath[diagonalPath] = basePath; } } editLength++; } // Performs the length of edit iteration. Is a bit fugly as this has to support the // sync and async mode which is never fun. Loops over execEditLength until a value // is produced. if (callback) { (function exec() { setTimeout(function () { // This should not happen, but we want to be safe. /* istanbul ignore next */ if (editLength > maxEditLength) { return callback(); } if (!execEditLength()) { exec(); } }, 0); })(); } else { while (editLength <= maxEditLength) { var ret = execEditLength(); if (ret) { return ret; } } } }, pushComponent: function pushComponent(components, added, removed) { var last = components[components.length - 1]; if (last && last.added === added && last.removed === removed) { // We need to clone here as the component clone operation is just // as shallow array clone components[components.length - 1] = { count: last.count + 1, added: added, removed: removed }; } else { components.push({ count: 1, added: added, removed: removed }); } }, extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { var newLen = newString.length, oldLen = oldString.length, newPos = basePath.newPos, oldPos = newPos - diagonalPath, commonCount = 0; while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { newPos++; oldPos++; commonCount++; } if (commonCount) { basePath.components.push({ count: commonCount }); } basePath.newPos = newPos; return oldPos; }, equals: function equals(left, right) { if (this.options.comparator) { return this.options.comparator(left, right); } else { return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase(); } }, removeEmpty: function removeEmpty(array) { var ret = []; for (var i = 0; i < array.length; i++) { if (array[i]) { ret.push(array[i]); } } return ret; }, castInput: function castInput(value) { return value; }, tokenize: function tokenize(value) { return value.split(''); }, join: function join(chars) { return chars.join(''); } }; function buildValues(diff, components, newString, oldString, useLongestToken) { var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0; for (; componentPos < componentLen; componentPos++) { var component = components[componentPos]; if (!component.removed) { if (!component.added && useLongestToken) { var value = newString.slice(newPos, newPos + component.count); value = value.map(function (value, i) { var oldValue = oldString[oldPos + i]; return oldValue.length > value.length ? oldValue : value; }); component.value = diff.join(value); } else { component.value = diff.join(newString.slice(newPos, newPos + component.count)); } newPos += component.count; // Common case if (!component.added) { oldPos += component.count; } } else { component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); oldPos += component.count; // Reverse add and remove so removes are output first to match common convention // The diffing algorithm is tied to add then remove output and this is the simplest // route to get the desired output with minimal overhead. if (componentPos && components[componentPos - 1].added) { var tmp = components[componentPos - 1]; components[componentPos - 1] = components[componentPos]; components[componentPos] = tmp; } } } // Special case handle for when one terminal is ignored (i.e. whitespace). // For this case we merge the terminal into the prior string and drop the change. // This is only available for string mode. var lastComponent = components[componentLen - 1]; if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) { components[componentLen - 2].value += lastComponent.value; components.pop(); } return components; } function clonePath(path) { return { newPos: path.newPos, components: path.components.slice(0) }; } var characterDiff = new Diff(); function diffChars(oldStr, newStr, options) { return characterDiff.diff(oldStr, newStr, options); } function generateOptions(options, defaults) { if (typeof options === 'function') { defaults.callback = options; } else if (options) { for (var name in options) { /* istanbul ignore else */ if (options.hasOwnProperty(name)) { defaults[name] = options[name]; } } } return defaults; } // // Ranges and exceptions: // Latin-1 Supplement, 0080–00FF // - U+00D7 × Multiplication sign // - U+00F7 ÷ Division sign // Latin Extended-A, 0100–017F // Latin Extended-B, 0180–024F // IPA Extensions, 0250–02AF // Spacing Modifier Letters, 02B0–02FF // - U+02C7 ˇ ˇ Caron // - U+02D8 ˘ ˘ Breve // - U+02D9 ˙ ˙ Dot Above // - U+02DA ˚ ˚ Ring Above // - U+02DB ˛ ˛ Ogonek // - U+02DC ˜ ˜ Small Tilde // - U+02DD ˝ ˝ Double Acute Accent // Latin Extended Additional, 1E00–1EFF var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; var reWhitespace = /\S/; var wordDiff = new Diff(); wordDiff.equals = function (left, right) { if (this.options.ignoreCase) { left = left.toLowerCase(); right = right.toLowerCase(); } return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); }; wordDiff.tokenize = function (value) { var tokens = value.split(/(\s+|[()[\]{}'"]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. for (var i = 0; i < tokens.length - 1; i++) { // If we have an empty string in the next field and we have only word chars before and after, merge if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { tokens[i] += tokens[i + 2]; tokens.splice(i + 1, 2); i--; } } return tokens; }; function diffWords(oldStr, newStr, options) { options = generateOptions(options, { ignoreWhitespace: true }); return wordDiff.diff(oldStr, newStr, options); } function diffWordsWithSpace(oldStr, newStr, options) { return wordDiff.diff(oldStr, newStr, options); } var lineDiff = new Diff(); lineDiff.tokenize = function (value) { var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line if (!linesAndNewlines[linesAndNewlines.length - 1]) { linesAndNewlines.pop(); } // Merge the content and line separators into single tokens for (var i = 0; i < linesAndNewlines.length; i++) { var line = linesAndNewlines[i]; if (i % 2 && !this.options.newlineIsToken) { retLines[retLines.length - 1] += line; } else { if (this.options.ignoreWhitespace) { line = line.trim(); } retLines.push(line); } } return retLines; }; function diffLines(oldStr, newStr, callback) { return lineDiff.diff(oldStr, newStr, callback); } function diffTrimmedLines(oldStr, newStr, callback) { var options = generateOptions(callback, { ignoreWhitespace: true }); return lineDiff.diff(oldStr, newStr, options); } var sentenceDiff = new Diff(); sentenceDiff.tokenize = function (value) { return value.split(/(\S.+?[.!?])(?=\s+|$)/); }; function diffSentences(oldStr, newStr, callback) { return sentenceDiff.diff(oldStr, newStr, callback); } var cssDiff = new Diff(); cssDiff.tokenize = function (value) { return value.split(/([{}:;,]|\s+)/); }; function diffCss(oldStr, newStr, callback) { return cssDiff.diff(oldStr, newStr, callback); } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } } function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } var objectPrototypeToString = Object.prototype.toString; var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: jsonDiff.useLongestToken = true; jsonDiff.tokenize = lineDiff.tokenize; jsonDiff.castInput = function (value) { var _this$options = this.options, undefinedReplacement = _this$options.undefinedReplacement, _this$options$stringi = _this$options.stringifyReplacer, stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) { return typeof v === 'undefined' ? undefinedReplacement : v; } : _this$options$stringi; return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); }; jsonDiff.equals = function (left, right) { return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')); }; function diffJson(oldObj, newObj, options) { return jsonDiff.diff(oldObj, newObj, options); } // This function handles the presence of circular references by bailing out when encountering an // object that is already on the "stack" of items being processed. Accepts an optional replacer function canonicalize(obj, stack, replacementStack, replacer, key) { stack = stack || []; replacementStack = replacementStack || []; if (replacer) { obj = replacer(key, obj); } var i; for (i = 0; i < stack.length; i += 1) { if (stack[i] === obj) { return replacementStack[i]; } } var canonicalizedObj; if ('[object Array]' === objectPrototypeToString.call(obj)) { stack.push(obj); canonicalizedObj = new Array(obj.length); replacementStack.push(canonicalizedObj); for (i = 0; i < obj.length; i += 1) { canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key); } stack.pop(); replacementStack.pop(); return canonicalizedObj; } if (obj && obj.toJSON) { obj = obj.toJSON(); } if (_typeof(obj) === 'object' && obj !== null) { stack.push(obj); canonicalizedObj = {}; replacementStack.push(canonicalizedObj); var sortedKeys = [], _key; for (_key in obj) { /* istanbul ignore else */ if (obj.hasOwnProperty(_key)) { sortedKeys.push(_key); } } sortedKeys.sort(); for (i = 0; i < sortedKeys.length; i += 1) { _key = sortedKeys[i]; canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); } stack.pop(); replacementStack.pop(); } else { canonicalizedObj = obj; } return canonicalizedObj; } var arrayDiff = new Diff(); arrayDiff.tokenize = function (value) { return value.slice(); }; arrayDiff.join = arrayDiff.removeEmpty = function (value) { return value; }; function diffArrays(oldArr, newArr, callback) { return arrayDiff.diff(oldArr, newArr, callback); } function parsePatch(uniDiff) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], list = [], i = 0; function parseIndex() { var index = {}; list.push(index); // Parse diff metadata while (i < diffstr.length) { var line = diffstr[i]; // File header found, end parsing diff metadata if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { break; } // Diff index var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); if (header) { index.index = header[1]; } i++; } // Parse file headers if they are defined. Unified diff requires them, but // there's no technical issues to have an isolated hunk without file header parseFileHeader(index); parseFileHeader(index); // Parse hunks index.hunks = []; while (i < diffstr.length) { var _line = diffstr[i]; if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { break; } else if (/^@@/.test(_line)) { index.hunks.push(parseHunk()); } else if (_line && options.strict) { // Ignore unexpected content unless in strict mode throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); } else { i++; } } } // Parses the --- and +++ headers, if none are found, no lines // are consumed. function parseFileHeader(index) { var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]); if (fileHeader) { var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; var data = fileHeader[2].split('\t', 2); var fileName = data[0].replace(/\\\\/g, '\\'); if (/^".*"$/.test(fileName)) { fileName = fileName.substr(1, fileName.length - 2); } index[keyPrefix + 'FileName'] = fileName; index[keyPrefix + 'Header'] = (data[1] || '').trim(); i++; } } // Parses a hunk // This assumes that we are at the start of a hunk. function parseHunk() { var chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); var hunk = { oldStart: +chunkHeader[1], oldLines: +chunkHeader[2] || 1, newStart: +chunkHeader[3], newLines: +chunkHeader[4] || 1, lines: [], linedelimiters: [] }; var addCount = 0, removeCount = 0; for (; i < diffstr.length; i++) { // Lines starting with '---' could be mistaken for the "remove line" operation // But they could be the header for the next file. Therefore prune such cases out. if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { break; } var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { hunk.lines.push(diffstr[i]); hunk.linedelimiters.push(delimiters[i] || '\n'); if (operation === '+') { addCount++; } else if (operation === '-') { removeCount++; } else if (operation === ' ') { addCount++; removeCount++; } } else { break; } } // Handle the empty block count case if (!addCount && hunk.newLines === 1) { hunk.newLines = 0; } if (!removeCount && hunk.oldLines === 1) { hunk.oldLines = 0; } // Perform optional sanity checking if (options.strict) { if (addCount !== hunk.newLines) { throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } if (removeCount !== hunk.oldLines) { throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } } return hunk; } while (i < diffstr.length) { parseIndex(); } return list; } // Iterator that traverses in the range of [min, max], stepping // by distance from a given start position. I.e. for [0, 4], with // start of 2, this will iterate 2, 3, 1, 4, 0. function distanceIterator (start, minLine, maxLine) { var wantForward = true, backwardExhausted = false, forwardExhausted = false, localOffset = 1; return function iterator() { if (wantForward && !forwardExhausted) { if (backwardExhausted) { localOffset++; } else { wantForward = false; } // Check if trying to fit beyond text length, and if not, check it fits // after offset location (or desired location on first iteration) if (start + localOffset <= maxLine) { return localOffset; } forwardExhausted = true; } if (!backwardExhausted) { if (!forwardExhausted) { wantForward = true; } // Check if trying to fit before text beginning, and if not, check it fits // before offset location if (minLine <= start - localOffset) { return -localOffset++; } backwardExhausted = true; return iterator(); } // We tried to fit hunk before text beginning and beyond text length, then // hunk can't fit on the text. Return undefined }; } function applyPatch(source, uniDiff) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (typeof uniDiff === 'string') { uniDiff = parsePatch(uniDiff); } if (Array.isArray(uniDiff)) { if (uniDiff.length > 1) { throw new Error('applyPatch only works with a single input.'); } uniDiff = uniDiff[0]; } // Apply the diff to the input var lines = source.split(/\r\n|[\n\v\f\r\x85]/), delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], hunks = uniDiff.hunks, compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) { return line === patchContent; }, errorCount = 0, fuzzFactor = options.fuzzFactor || 0, minLine = 0, offset = 0, removeEOFNL, addEOFNL; /** * Checks if the hunk exactly fits on the provided location */ function hunkFits(hunk, toPos) { for (var j = 0; j < hunk.lines.length; j++) { var line = hunk.lines[j], operation = line.length > 0 ? line[0] : ' ', content = line.length > 0 ? line.substr(1) : line; if (operation === ' ' || operation === '-') { // Context sanity check if (!compareLine(toPos + 1, lines[toPos], operation, content)) { errorCount++; if (errorCount > fuzzFactor) { return false; } } toPos++; } } return true; } // Search best fit offsets for each hunk based on the previous ones for (var i = 0; i < hunks.length; i++) { var hunk = hunks[i], maxLine = lines.length - hunk.oldLines, localOffset = 0, toPos = offset + hunk.oldStart - 1; var iterator = distanceIterator(toPos, minLine, maxLine); for (; localOffset !== undefined; localOffset = iterator()) { if (hunkFits(hunk, toPos + localOffset)) { hunk.offset = offset += localOffset; break; } } if (localOffset === undefined) { return false; } // Set lower text limit to end of the current hunk, so next ones don't try // to fit over already patched text minLine = hunk.offset + hunk.oldStart + hunk.oldLines; } // Apply patch hunks var diffOffset = 0; for (var _i = 0; _i < hunks.length; _i++) { var _hunk = hunks[_i], _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1; diffOffset += _hunk.newLines - _hunk.oldLines; if (_toPos < 0) { // Creating a new file _toPos = 0; } for (var j = 0; j < _hunk.lines.length; j++) { var line = _hunk.lines[j], operation = line.length > 0 ? line[0] : ' ', content = line.length > 0 ? line.substr(1) : line, delimiter = _hunk.linedelimiters[j]; if (operation === ' ') { _toPos++; } else if (operation === '-') { lines.splice(_toPos, 1); delimiters.splice(_toPos, 1); /* istanbul ignore else */ } else if (operation === '+') { lines.splice(_toPos, 0, content); delimiters.splice(_toPos, 0, delimiter); _toPos++; } else if (operation === '\\') { var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; if (previousOperation === '+') { removeEOFNL = true; } else if (previousOperation === '-') { addEOFNL = true; } } } } // Handle EOFNL insertion/removal if (removeEOFNL) { while (!lines[lines.length - 1]) { lines.pop(); delimiters.pop(); } } else if (addEOFNL) { lines.push(''); delimiters.push('\n'); } for (var _k = 0; _k < lines.length - 1; _k++) { lines[_k] = lines[_k] + delimiters[_k]; } return lines.join(''); } // Wrapper that supports multiple file patches via callbacks. function applyPatches(uniDiff, options) { if (typeof uniDiff === 'string') { uniDiff = parsePatch(uniDiff); } var currentIndex = 0; function processIndex() { var index = uniDiff[currentIndex++]; if (!index) { return options.complete(); } options.loadFile(index, function (err, data) { if (err) { return options.complete(err); } var updatedContent = applyPatch(data, index, options); options.patched(index, updatedContent, function (err) { if (err) { return options.complete(err); } processIndex(); }); }); } processIndex(); } function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { if (!options) { options = {}; } if (typeof options.context === 'undefined') { options.context = 4; } var diff = diffLines(oldStr, newStr, options); diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier function contextLines(lines) { return lines.map(function (entry) { return ' ' + entry; }); } var hunks = []; var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; var _loop = function _loop(i) { var current = diff[i], lines = current.lines || current.value.replace(/\n$/, '').split('\n'); current.lines = lines; if (current.added || current.removed) { var _curRange; // If we have previous context, start with that if (!oldRangeStart) { var prev = diff[i - 1]; oldRangeStart = oldLine; newRangeStart = newLine; if (prev) { curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; oldRangeStart -= curRange.length; newRangeStart -= curRange.length; } } // Output our changes (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) { return (current.added ? '+' : '-') + entry; }))); // Track the updated file position if (current.added) { newLine += lines.length; } else { oldLine += lines.length; } } else { // Identical context lines. Track line changes if (oldRangeStart) { // Close out any changes that have been output (or join overlapping) if (lines.length <= options.context * 2 && i < diff.length - 2) { var _curRange2; // Overlapping (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines))); } else { var _curRange3; // end the range and output var contextSize = Math.min(lines.length, options.context); (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize)))); var hunk = { oldStart: oldRangeStart, oldLines: oldLine - oldRangeStart + contextSize, newStart: newRangeStart, newLines: newLine - newRangeStart + contextSize, lines: curRange }; if (i >= diff.length - 2 && lines.length <= options.context) { // EOF is inside this hunk var oldEOFNewline = /\n$/.test(oldStr); var newEOFNewline = /\n$/.test(newStr); var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines; if (!oldEOFNewline && noNlBeforeAdds) { // special case: old has no eol and no trailing context; no-nl can end up before adds curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); } if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) { curRange.push('\\ No newline at end of file'); } } hunks.push(hunk); oldRangeStart = 0; newRangeStart = 0; curRange = []; } } oldLine += lines.length; newLine += lines.length; } }; for (var i = 0; i < diff.length; i++) { _loop(i); } return { oldFileName: oldFileName, newFileName: newFileName, oldHeader: oldHeader, newHeader: newHeader, hunks: hunks }; } function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); var ret = []; if (oldFileName == newFileName) { ret.push('Index: ' + oldFileName); } ret.push('==================================================================='); ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); for (var i = 0; i < diff.hunks.length; i++) { var hunk = diff.hunks[i]; ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); ret.push.apply(ret, hunk.lines); } return ret.join('\n') + '\n'; } function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); } function arrayEqual(a, b) { if (a.length !== b.length) { return false; } return arrayStartsWith(a, b); } function arrayStartsWith(array, start) { if (start.length > array.length) { return false; } for (var i = 0; i < start.length; i++) { if (start[i] !== array[i]) { return false; } } return true; } function calcLineCount(hunk) { var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines), oldLines = _calcOldNewLineCount.oldLines, newLines = _calcOldNewLineCount.newLines; if (oldLines !== undefined) { hunk.oldLines = oldLines; } else { delete hunk.oldLines; } if (newLines !== undefined) { hunk.newLines = newLines; } else { delete hunk.newLines; } } function merge(mine, theirs, base) { mine = loadPatch(mine, base); theirs = loadPatch(theirs, base); var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning. // Leaving sanity checks on this to the API consumer that may know more about the // meaning in their own context. if (mine.index || theirs.index) { ret.index = mine.index || theirs.index; } if (mine.newFileName || theirs.newFileName) { if (!fileNameChanged(mine)) { // No header or no change in ours, use theirs (and ours if theirs does not exist) ret.oldFileName = theirs.oldFileName || mine.oldFileName; ret.newFileName = theirs.newFileName || mine.newFileName; ret.oldHeader = theirs.oldHeader || mine.oldHeader; ret.newHeader = theirs.newHeader || mine.newHeader; } else if (!fileNameChanged(theirs)) { // No header or no change in theirs, use ours ret.oldFileName = mine.oldFileName; ret.newFileName = mine.newFileName; ret.oldHeader = mine.oldHeader; ret.newHeader = mine.newHeader; } else { // Both changed... figure it out ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName); ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName); ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader); ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader); } } ret.hunks = []; var mineIndex = 0, theirsIndex = 0, mineOffset = 0, theirsOffset = 0; while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) { var mineCurrent = mine.hunks[mineIndex] || { oldStart: Infinity }, theirsCurrent = theirs.hunks[theirsIndex] || { oldStart: Infinity }; if (hunkBefore(mineCurrent, theirsCurrent)) { // This patch does not overlap with any of the others, yay. ret.hunks.push(cloneHunk(mineCurrent, mineOffset)); mineIndex++; theirsOffset += mineCurrent.newLines - mineCurrent.oldLines; } else if (hunkBefore(theirsCurrent, mineCurrent)) { // This patch does not overlap with any of the others, yay. ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset)); theirsIndex++; mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines; } else { // Overlap, merge as best we can var mergedHunk = { oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart), oldLines: 0, newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset), newLines: 0, lines: [] }; mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines); theirsIndex++; mineIndex++; ret.hunks.push(mergedHunk); } } return ret; } function loadPatch(param, base) { if (typeof param === 'string') { if (/^@@/m.test(param) || /^Index:/m.test(param)) { return parsePatch(param)[0]; } if (!base) { throw new Error('Must provide a base reference or pass in a patch'); } return structuredPatch(undefined, undefined, base, param); } return param; } function fileNameChanged(patch) { return patch.newFileName && patch.newFileName !== patch.oldFileName; } function selectField(index, mine, theirs) { if (mine === theirs) { return mine; } else { index.conflict = true; return { mine: mine, theirs: theirs }; } } function hunkBefore(test, check) { return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart; } function cloneHunk(hunk, offset) { return { oldStart: hunk.oldStart, oldLines: hunk.oldLines, newStart: hunk.newStart + offset, newLines: hunk.newLines, lines: hunk.lines }; } function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) { // This will generally result in a conflicted hunk, but there are cases where the context // is the only overlap where we can successfully merge the content here. var mine = { offset: mineOffset, lines: mineLines, index: 0 }, their = { offset: theirOffset, lines: theirLines, index: 0 }; // Handle any leading content insertLeading(hunk, mine, their); insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each. while (mine.index < mine.lines.length && their.index < their.lines.length) { var mineCurrent = mine.lines[mine.index], theirCurrent = their.lines[their.index]; if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) { // Both modified ... mutualChange(hunk, mine, their); } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') { var _hunk$lines; // Mine inserted (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine))); } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') { var _hunk$lines2; // Theirs inserted (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their))); } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') { // Mine removed or edited removal(hunk, mine, their); } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') { // Their removed or edited removal(hunk, their, mine, true); } else if (mineCurrent === theirCurrent) { // Context identity hunk.lines.push(mineCurrent); mine.index++; their.index++; } else { // Context mismatch conflict(hunk, collectChange(mine), collectChange(their)); } } // Now push anything that may be remaining insertTrailing(hunk, mine); insertTrailing(hunk, their); calcLineCount(hunk); } function mutualChange(hunk, mine, their) { var myChanges = collectChange(mine), theirChanges = collectChange(their); if (allRemoves(myChanges) && allRemoves(theirChanges)) { // Special case for remove changes that are supersets of one another if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) { var _hunk$lines3; (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges)); return; } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) { var _hunk$lines4; (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges)); return; } } else if (arrayEqual(myChanges, theirChanges)) { var _hunk$lines5; (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges)); return; } conflict(hunk, myChanges, theirChanges); } function removal(hunk, mine, their, swap) { var myChanges = collectChange(mine), theirChanges = collectContext(their, myChanges); if (theirChanges.merged) { var _hunk$lines6; (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged)); } else { conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges); } } function conflict(hunk, mine, their) { hunk.conflict = true; hunk.lines.push({ conflict: true, mine: mine, theirs: their }); } function insertLeading(hunk, insert, their) { while (insert.offset < their.offset && insert.index < insert.lines.length) { var line = insert.lines[insert.index++]; hunk.lines.push(line); insert.offset++; } } function insertTrailing(hunk, insert) { while (insert.index < insert.lines.length) { var line = insert.lines[insert.index++]; hunk.lines.push(line); } } function collectChange(state) { var ret = [], operation = state.lines[state.index][0]; while (state.index < state.lines.length) { var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change. if (operation === '-' && line[0] === '+') { operation = '+'; } if (operation === line[0]) { ret.push(line); state.index++; } else { break; } } return ret; } function collectContext(state, matchChanges) { var changes = [], merged = [], matchIndex = 0, contextChanges = false, conflicted = false; while (matchIndex < matchChanges.length && state.index < state.lines.length) { var change = state.lines[state.index], match = matchChanges[matchIndex]; // Once we've hit our add, then we are done if (match[0] === '+') { break; } contextChanges = contextChanges || change[0] !== ' '; merged.push(match); matchIndex++; // Consume any additions in the other block as a conflict to attempt // to pull in the remaining context after this if (change[0] === '+') { conflicted = true; while (change[0] === '+') { changes.push(change); change = state.lines[++state.index]; } } if (match.substr(1) === change.substr(1)) { changes.push(change); state.index++; } else { conflicted = true; } } if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) { conflicted = true; } if (conflicted) { return changes; } while (matchIndex < matchChanges.length) { merged.push(matchChanges[matchIndex++]); } return { merged: merged, changes: changes }; } function allRemoves(changes) { return changes.reduce(function (prev, change) { return prev && change[0] === '-'; }, true); } function skipRemoveSuperset(state, removeChanges, delta) { for (var i = 0; i < delta; i++) { var changeContent = removeChanges[removeChanges.length - delta + i].substr(1); if (state.lines[state.index + i] !== ' ' + changeContent) { return false; } } state.index += delta; return true; } function calcOldNewLineCount(lines) { var oldLines = 0; var newLines = 0; lines.forEach(function (line) { if (typeof line !== 'string') { var myCount = calcOldNewLineCount(line.mine); var theirCount = calcOldNewLineCount(line.theirs); if (oldLines !== undefined) { if (myCount.oldLines === theirCount.oldLines) { oldLines += myCount.oldLines; } else { oldLines = undefined; } } if (newLines !== undefined) { if (myCount.newLines === theirCount.newLines) { newLines += myCount.newLines; } else { newLines = undefined; } } } else { if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) { newLines++; } if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) { oldLines++; } } }); return { oldLines: oldLines, newLines: newLines }; } // See: http://code.google.com/p/google-diff-match-patch/wiki/API function convertChangesToDMP(changes) { var ret = [], change, operation; for (var i = 0; i < changes.length; i++) { change = changes[i]; if (change.added) { operation = 1; } else if (change.removed) { operation = -1; } else { operation = 0; } ret.push([operation, change.value]); } return ret; } function convertChangesToXML(changes) { var ret = []; for (var i = 0; i < changes.length; i++) { var change = changes[i]; if (change.added) { ret.push(''); } else if (change.removed) { ret.push(''); } ret.push(escapeHTML(change.value)); if (change.added) { ret.push(''); } else if (change.removed) { ret.push(''); } } return ret.join(''); } function escapeHTML(s) { var n = s; n = n.replace(/&/g, '&'); n = n.replace(//g, '>'); n = n.replace(/"/g, '"'); return n; } /* See LICENSE file for terms of use */ /***/ }), /***/ 50367: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const path = __webpack_require__(71017); const pathType = __webpack_require__(29847); const getExtensions = extensions => extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0]; const getPath = (filepath, cwd) => { const pth = filepath[0] === '!' ? filepath.slice(1) : filepath; return path.isAbsolute(pth) ? pth : path.join(cwd, pth); }; const addExtensions = (file, extensions) => { if (path.extname(file)) { return `**/${file}`; } return `**/${file}.${getExtensions(extensions)}`; }; const getGlob = (directory, options) => { if (options.files && !Array.isArray(options.files)) { throw new TypeError(`Expected \`files\` to be of type \`Array\` but received type \`${typeof options.files}\``); } if (options.extensions && !Array.isArray(options.extensions)) { throw new TypeError(`Expected \`extensions\` to be of type \`Array\` but received type \`${typeof options.extensions}\``); } if (options.files && options.extensions) { return options.files.map(x => path.posix.join(directory, addExtensions(x, options.extensions))); } if (options.files) { return options.files.map(x => path.posix.join(directory, `**/${x}`)); } if (options.extensions) { return [path.posix.join(directory, `**/*.${getExtensions(options.extensions)}`)]; } return [path.posix.join(directory, '**')]; }; module.exports = async (input, options) => { options = { cwd: process.cwd(), ...options }; if (typeof options.cwd !== 'string') { throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``); } const globs = await Promise.all([].concat(input).map(async x => { const isDirectory = await pathType.isDirectory(getPath(x, options.cwd)); return isDirectory ? getGlob(x, options) : x; })); return [].concat.apply([], globs); // eslint-disable-line prefer-spread }; module.exports.sync = (input, options) => { options = { cwd: process.cwd(), ...options }; if (typeof options.cwd !== 'string') { throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``); } const globs = [].concat(input).map(x => pathType.isDirectorySync(getPath(x, options.cwd)) ? getGlob(x, options) : x); return [].concat.apply([], globs); // eslint-disable-line prefer-spread }; /***/ }), /***/ 38360: /***/ ((module, exports, __webpack_require__) => { //Based on follow-redirects v0.0.x var nativeHttps = __webpack_require__(95687), nativeHttp = __webpack_require__(13685), url = __webpack_require__(57310), utils = __webpack_require__(76174); var maxRedirects = module.exports.maxRedirects = 5; var protocols = { https: nativeHttps, http: nativeHttp }; for (var protocol in protocols) { var h = function() {}; h.prototype = protocols[protocol]; h = new h(); h.request = function(h) { return function(options, callback, redirectOptions) { redirectOptions = redirectOptions || {}; var max = (typeof options === 'object' && 'maxRedirects' in options) ? options.maxRedirects : exports.maxRedirects; var redirect = utils.extend({ count: 0, max: max, clientRequest: null, userCallback: callback }, redirectOptions); if (redirect.count > redirect.max) { var err = new Error('Max redirects exceeded. To allow more redirects, pass options.maxRedirects property.'); redirect.clientRequest.emit('error', err); return redirect.clientRequest; } redirect.count++; var reqUrl; if (typeof options === 'string') { reqUrl = options; } else { reqUrl = url.format(utils.extend({ protocol: protocol }, options)); } var clientRequest = Object.getPrototypeOf(h).request(options, redirectCallback(reqUrl, redirect)); if (!redirect.clientRequest) redirect.clientRequest = clientRequest; function redirectCallback(reqUrl, redirect) { return function(res) { if (res.statusCode < 300 || res.statusCode > 399) { return redirect.userCallback(res); } if (!('location' in res.headers)) { return redirect.userCallback(res); } var redirectUrl = url.resolve(reqUrl, res.headers.location); var proto = url.parse(redirectUrl).protocol; proto = proto.substr(0, proto.length - 1); return module.exports[proto].get(redirectUrl, redirectCallback(reqUrl, redirect), redirect); }; } return clientRequest; }; }(h); // see https://github.com/joyent/node/blob/master/lib/http.js#L1623 h.get = function(h) { return function(options, cb, redirectOptions) { var req = h.request(options, cb, redirectOptions); req.end(); return req; }; }(h); module.exports[protocol] = h; } /***/ }), /***/ 7009: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = HttpDuplex; var util = __webpack_require__(73837), stream = __webpack_require__(11451); util.inherits(HttpDuplex, stream.Duplex); function HttpDuplex(req, res, options) { var self = this; if (!(self instanceof HttpDuplex)) return new HttpDuplex(req, res, options); stream.Duplex.call(self, options); self._output = null; self.connect(req, res); } HttpDuplex.prototype.connect = function(req, res) { var self = this; self.req = req; self._output = res; self.emit('response', res); res.on('data', function(c) { if (!self.push(c)) self._output.pause(); }); res.on('end', function() { self.push(null); }); }; HttpDuplex.prototype._read = function(n) { if (this._output) this._output.resume(); }; HttpDuplex.prototype._write = function(chunk, encoding, cb) { this.req.write(chunk, encoding); cb(); }; HttpDuplex.prototype.end = function(chunk, encoding, cb) { this._output.socket.destroy(); return this.req.end(chunk, encoding, cb); }; HttpDuplex.prototype.destroy = function() { this.req.destroy(); this._output.socket.destroy(); }; /***/ }), /***/ 89168: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var querystring = __webpack_require__(63477), http = __webpack_require__(38360), fs = __webpack_require__(57147), path = __webpack_require__(71017), url = __webpack_require__(57310), ssh = __webpack_require__(44456), HttpDuplex = __webpack_require__(7009), debug = __webpack_require__(15158)('modem'), utils = __webpack_require__(76174), util = __webpack_require__(73837), splitca = __webpack_require__(22714), isWin = __webpack_require__(22037).type() === 'Windows_NT', stream = __webpack_require__(12781); var defaultOpts = function () { var host; var opts = {}; if (!process.env.DOCKER_HOST) { // Windows socket path: //./pipe/docker_engine ( Windows 10 ) // Linux & Darwin socket path: /var/run/docker.sock opts.socketPath = isWin ? '//./pipe/docker_engine' : '/var/run/docker.sock'; } else if (process.env.DOCKER_HOST.indexOf('unix://') === 0) { // Strip off unix://, fall back to default of /var/run/docker.sock if // unix:// was passed without a path opts.socketPath = process.env.DOCKER_HOST.substring(7) || '/var/run/docker.sock'; } else if (process.env.DOCKER_HOST.indexOf('npipe://') === 0) { // Strip off npipe://, fall back to default of //./pipe/docker_engine if // npipe:// was passed without a path opts.socketPath = process.env.DOCKER_HOST.substring(8) || '//./pipe/docker_engine'; } else { var hostStr = process.env.DOCKER_HOST; if (hostStr.indexOf('\/\/') < 0) { hostStr = 'tcp://' + hostStr; } try { host = new url.URL(hostStr); } catch (err) { throw new Error('DOCKER_HOST env variable should be something like tcp://localhost:1234'); } opts.port = host.port; if (process.env.DOCKER_TLS_VERIFY === '1' || opts.port === '2376') { opts.protocol = 'https'; } else if (host.protocol === 'ssh:') { opts.protocol = 'ssh'; opts.username = host.username; opts.sshOptions = { agent: process.env.SSH_AUTH_SOCK, } } else { opts.protocol = 'http'; } opts.host = host.hostname; if (process.env.DOCKER_CERT_PATH) { opts.ca = splitca(path.join(process.env.DOCKER_CERT_PATH, 'ca.pem')); opts.cert = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'cert.pem')); opts.key = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'key.pem')); } if (process.env.DOCKER_CLIENT_TIMEOUT) { opts.timeout = parseInt(process.env.DOCKER_CLIENT_TIMEOUT, 10); } } return opts; }; var Modem = function (options) { var optDefaults = defaultOpts(); var opts = Object.assign({}, optDefaults, options); this.host = opts.host; if (!this.host) { this.socketPath = opts.socketPath; } this.port = opts.port; this.username = opts.username; this.password = opts.password; this.version = opts.version; this.key = opts.key; this.cert = opts.cert; this.ca = opts.ca; this.timeout = opts.timeout; this.connectionTimeout = opts.connectionTimeout; this.checkServerIdentity = opts.checkServerIdentity; this.agent = opts.agent; this.headers = opts.headers || {}; this.sshOptions = Object.assign({}, options ? options.sshOptions : {}, optDefaults.sshOptions); //retrocompabitlity if (this.sshOptions.agentForward === undefined) { this.sshOptions.agentForward = opts.agentForward; } if (this.key && this.cert && this.ca) { this.protocol = 'https'; } this.protocol = opts.protocol || this.protocol || 'http'; }; Modem.prototype.dial = function (options, callback) { var opts, address, data; var self = this; if (options.options) { opts = options.options; } // Prevent credentials from showing up in URL if (opts && opts.authconfig) { delete opts.authconfig; } // Prevent abortsignal from showing up in the URL if (opts && opts.abortSignal) { delete opts.abortSignal; } if (this.version) { options.path = '/' + this.version + options.path; } if (this.host) { var parsed = url.parse(self.host); address = url.format({ 'protocol': parsed.protocol || self.protocol, 'hostname': parsed.hostname || self.host, 'port': self.port }); address = url.resolve(address, options.path); } else { address = options.path; } if (options.path.indexOf('?') !== -1) { if (opts && Object.keys(opts).length > 0) { address += this.buildQuerystring(opts._query || opts); } else { address = address.substring(0, address.length - 1); } } var optionsf = { path: address, method: options.method, headers: options.headers || Object.assign({}, self.headers), key: self.key, cert: self.cert, ca: self.ca }; if (this.checkServerIdentity) { optionsf.checkServerIdentity = this.checkServerIdentity; } if (this.agent) { optionsf.agent = this.agent; } if (options.authconfig) { optionsf.headers['X-Registry-Auth'] = options.authconfig.key || options.authconfig.base64 || Buffer.from(JSON.stringify(options.authconfig)).toString('base64').replace(/\+/g, "-").replace(/\//g, "_"); } if (options.registryconfig) { optionsf.headers['X-Registry-Config'] = options.registryconfig.base64 || Buffer.from(JSON.stringify(options.registryconfig)).toString('base64'); } if (options.abortSignal) { optionsf.signal = options.abortSignal; } if (options.file) { if (typeof options.file === 'string') { data = fs.createReadStream(path.resolve(options.file)); } else { data = options.file; } optionsf.headers['Content-Type'] = 'application/tar'; } else if (opts && options.method === 'POST') { data = JSON.stringify(opts._body || opts); if (options.allowEmpty) { optionsf.headers['Content-Type'] = 'application/json'; } else { if (data !== '{}' && data !== '""') { optionsf.headers['Content-Type'] = 'application/json'; } else { data = undefined; } } } if (typeof data === 'string') { optionsf.headers['Content-Length'] = Buffer.byteLength(data); } else if (Buffer.isBuffer(data) === true) { optionsf.headers['Content-Length'] = data.length; } else if (optionsf.method === 'PUT' || options.hijack || options.openStdin) { optionsf.headers['Transfer-Encoding'] = 'chunked'; } if (options.hijack) { optionsf.headers.Connection = 'Upgrade'; optionsf.headers.Upgrade = 'tcp'; } if (this.socketPath) { optionsf.socketPath = this.socketPath; } else { var urlp = url.parse(address); optionsf.hostname = urlp.hostname; optionsf.port = urlp.port; optionsf.path = urlp.path; } this.buildRequest(optionsf, options, data, callback); }; Modem.prototype.buildRequest = function (options, context, data, callback) { var self = this; var connectionTimeoutTimer; var finished = false; var opts = self.protocol === 'ssh' ? Object.assign(options, { agent: ssh(Object.assign({}, self.sshOptions, { 'host': self.host, 'port': self.port, 'username': self.username, 'password': self.password, })), protocol: 'http:', }) : options; var req = http[self.protocol === 'ssh' ? 'http' : self.protocol].request(opts, function () { }); debug('Sending: %s', util.inspect(options, { showHidden: true, depth: null })); if (self.connectionTimeout) { connectionTimeoutTimer = setTimeout(function () { debug('Connection Timeout of %s ms exceeded', self.connectionTimeout); req.abort(); }, self.connectionTimeout); } if (self.timeout) { req.on('socket', function (socket) { socket.setTimeout(self.timeout); socket.on('timeout', function () { debug('Timeout of %s ms exceeded', self.timeout); req.abort(); }); }); } if (context.hijack === true) { clearTimeout(connectionTimeoutTimer); req.on('upgrade', function (res, sock, head) { if (finished === false) { finished = true; return callback(null, sock); } }); } req.on('connect', function () { clearTimeout(connectionTimeoutTimer); }); req.on('disconnect', function () { clearTimeout(connectionTimeoutTimer); }); req.on('response', function (res) { clearTimeout(connectionTimeoutTimer); if (context.isStream === true) { if (finished === false) { finished = true; self.buildPayload(null, context.isStream, context.statusCodes, context.openStdin, req, res, null, callback); } } else { // The native 'request' method only handles aborting during the request lifecycle not the response lifecycle. // We need to make the response stream abortable so that it's destroyed with an error on abort and then // it triggers the request 'error' event if (options.signal != null) { stream.addAbortSignal(options.signal, res) } var chunks = []; res.on('data', function (chunk) { chunks.push(chunk); }); res.on('end', function () { var buffer = Buffer.concat(chunks); var result = buffer.toString(); debug('Received: %s', result); var json = utils.parseJSON(result) || buffer; if (finished === false) { finished = true; self.buildPayload(null, context.isStream, context.statusCodes, false, req, res, json, callback); } }); } }); req.on('error', function (error) { clearTimeout(connectionTimeoutTimer); if (finished === false) { finished = true; self.buildPayload(error, context.isStream, context.statusCodes, false, {}, {}, null, callback); } }); if (typeof data === 'string' || Buffer.isBuffer(data)) { req.write(data); } else if (data) { data.on('error', function (error) { req.destroy(error); }); data.pipe(req); } if (!context.hijack && !context.openStdin && (typeof data === 'string' || data === undefined || Buffer.isBuffer(data))) { req.end(); } }; Modem.prototype.buildPayload = function (err, isStream, statusCodes, openStdin, req, res, json, cb) { if (err) return cb(err, null); if (statusCodes[res.statusCode] !== true) { getCause(isStream, res, json, function (err, cause) { var msg = new Error( '(HTTP code ' + res.statusCode + ') ' + (statusCodes[res.statusCode] || 'unexpected') + ' - ' + (cause.message || cause) + ' ' ); msg.reason = statusCodes[res.statusCode]; msg.statusCode = res.statusCode; msg.json = json; cb(msg, null); }); } else { if (openStdin) { cb(null, new HttpDuplex(req, res)); } else if (isStream) { cb(null, res); } else { cb(null, json); } } function getCause(isStream, res, json, callback) { var chunks = ''; if (isStream) { res.on('data', function (chunk) { chunks += chunk; }); res.on('end', function () { callback(null, utils.parseJSON(chunks) || chunks); }); } else { callback(null, json); } } }; Modem.prototype.demuxStream = function (streama, stdout, stderr) { var nextDataType = null; var nextDataLength = null; var buffer = Buffer.from(''); function processData(data) { if (data) { buffer = Buffer.concat([buffer, data]); } if (!nextDataType) { if (buffer.length >= 8) { var header = bufferSlice(8); nextDataType = header.readUInt8(0); nextDataLength = header.readUInt32BE(4); // It's possible we got a "data" that contains multiple messages // Process the next one processData(); } } else { if (buffer.length >= nextDataLength) { var content = bufferSlice(nextDataLength); if (nextDataType === 1) { stdout.write(content); } else { stderr.write(content); } nextDataType = null; // It's possible we got a "data" that contains multiple messages // Process the next one processData(); } } } function bufferSlice(end) { var out = buffer.slice(0, end); buffer = Buffer.from(buffer.slice(end, buffer.length)); return out; } streama.on('data', processData); }; Modem.prototype.followProgress = function (streama, onFinished, onProgress) { var buf = ''; var output = []; var finished = false; streama.on('data', onStreamEvent); streama.on('error', onStreamError); streama.on('end', onStreamEnd); streama.on('close', onStreamEnd); function onStreamEvent(data) { buf += data.toString(); pump(); function pump() { var pos; while ((pos = buf.indexOf('\n')) >= 0) { if (pos == 0) { buf = buf.slice(1); continue; } processLine(buf.slice(0, pos)); buf = buf.slice(pos + 1); } } function processLine(line) { if (line[line.length - 1] == '\r') line = line.substr(0, line.length - 1); if (line.length > 0) { var obj = JSON.parse(line); output.push(obj); if (onProgress) { onProgress(obj); } } } }; function onStreamError(err) { finished = true; streama.removeListener('data', onStreamEvent); streama.removeListener('error', onStreamError); streama.removeListener('end', onStreamEnd); streama.removeListener('close', onStreamEnd); onFinished(err, output); } function onStreamEnd() { if (!finished) onFinished(null, output); finished = true; } }; Modem.prototype.buildQuerystring = function (opts) { var clone = {}; // serialize map and array values as JSON strings, else querystring truncates. // 't' and 'extrahosts' can be arrays but need special treatment so that they're // passed as multiple qs parameters instead of JSON values. Object.keys(opts).map(function (key, i) { if (opts[key] && typeof opts[key] === 'object' && !['t', 'extrahosts'].includes(key) ) { clone[key] = JSON.stringify(opts[key]); } else { clone[key] = opts[key]; } }); return querystring.stringify(clone); }; module.exports = Modem; /***/ }), /***/ 44456: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var Client = __webpack_require__(29005).Client, http = __webpack_require__(13685); module.exports = function(opt) { var conn = new Client(); var agent = new http.Agent(); agent.createConnection = function(options, fn) { conn.once('ready', function() { conn.exec('docker system dial-stdio', function(err, stream) { if (err) { conn.end(); agent.destroy(); return; } fn(null, stream); stream.once('close', () => { conn.end(); agent.destroy(); }); }); }).connect(opt); conn.once('end', () => agent.destroy()); }; return agent; }; /***/ }), /***/ 76174: /***/ ((module) => { // https://github.com/HenrikJoreteg/extend-object/blob/v0.1.0/extend-object.js var arr = []; var each = arr.forEach; var slice = arr.slice; module.exports.extend = function(obj) { each.call(slice.call(arguments, 1), function(source) { if (source) { for (var prop in source) { obj[prop] = source[prop]; } } }); return obj; }; module.exports.parseJSON = function(s) { try { return JSON.parse(s); } catch (e) { return null; } }; /***/ }), /***/ 12447: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Argument = void 0; class Argument { constructor(value, range) { this.value = value; this.range = range; } toString() { return this.value; } getRange() { return this.range; } getValue() { return this.value; } isAfter(position) { if (this.range.end.line < position.line) { return false; } return this.range.start.line > position.line ? true : this.range.start.character > position.character; } isBefore(position) { if (this.range.start.line < position.line) { return true; } return this.range.end.line > position.line ? false : this.range.end.character < position.character; } } exports.Argument = Argument; /***/ }), /***/ 42179: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Comment = void 0; const vscode_languageserver_types_1 = __webpack_require__(8089); const line_1 = __webpack_require__(47119); const util_1 = __webpack_require__(98707); class Comment extends line_1.Line { constructor(document, range) { super(document, range); } toString() { const content = this.getContent(); if (content) { return "# " + content; } return "#"; } /** * Returns the content of this comment. This excludes leading and * trailing whitespace as well as the # symbol. If the comment only * consists of whitespace, the empty string will be returned. */ getContent() { let range = this.getContentRange(); if (range === null) { return ""; } return this.document.getText().substring(this.document.offsetAt(range.start), this.document.offsetAt(range.end)); } /** * Returns a range that includes the content of the comment * excluding any leading and trailing whitespace as well as the # * symbol. May return null if the comment only consists of whitespace * characters. */ getContentRange() { let range = this.getRange(); const startOffset = this.document.offsetAt(range.start); let raw = this.document.getText().substring(startOffset, this.document.offsetAt(range.end)); let start = -1; let end = -1; // skip the first # symbol for (let i = 1; i < raw.length; i++) { if (!util_1.Util.isWhitespace(raw.charAt(i))) { start = i; break; } } if (start === -1) { return null; } // go backwards up to the first # symbol for (let i = raw.length - 1; i >= 1; i--) { if (!util_1.Util.isWhitespace(raw.charAt(i))) { end = i + 1; break; } } return vscode_languageserver_types_1.Range.create(this.document.positionAt(startOffset + start), this.document.positionAt(startOffset + end)); } } exports.Comment = Comment; /***/ }), /***/ 71513: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Remy Suen. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Dockerfile = void 0; const vscode_languageserver_types_1 = __webpack_require__(8089); const ast = __webpack_require__(20871); const imageTemplate_1 = __webpack_require__(30791); const from_1 = __webpack_require__(98654); const util_1 = __webpack_require__(98707); const main_1 = __webpack_require__(20871); class Dockerfile extends imageTemplate_1.ImageTemplate { constructor(document) { super(); this.initialInstructions = new imageTemplate_1.ImageTemplate(); this.buildStages = []; this.directives = []; /** * Whether a FROM instruction has been added to this Dockerfile or not. */ this.foundFrom = false; this.document = document; } getEscapeCharacter() { for (const directive of this.directives) { if (directive.getDirective() === ast.Directive.escape) { const value = directive.getValue(); if (value === '\\' || value === '`') { return value; } } } return '\\'; } getInitialARGs() { return this.initialInstructions.getARGs(); } getContainingImage(position) { let range = vscode_languageserver_types_1.Range.create(vscode_languageserver_types_1.Position.create(0, 0), this.document.positionAt(this.document.getText().length)); if (!util_1.Util.isInsideRange(position, range)) { // not inside the document, invalid position return null; } if (this.initialInstructions.getComments().length > 0 || this.initialInstructions.getInstructions().length > 0) { if (util_1.Util.isInsideRange(position, this.initialInstructions.getRange())) { return this.initialInstructions; } } for (const buildStage of this.buildStages) { if (util_1.Util.isInsideRange(position, buildStage.getRange())) { return buildStage; } } return this; } addInstruction(instruction) { if (instruction.getKeyword() === main_1.Keyword.FROM) { this.currentBuildStage = new imageTemplate_1.ImageTemplate(); this.buildStages.push(this.currentBuildStage); this.foundFrom = true; } else if (!this.foundFrom) { this.initialInstructions.addInstruction(instruction); } if (this.foundFrom) { this.currentBuildStage.addInstruction(instruction); } super.addInstruction(instruction); } setDirectives(directives) { this.directives = directives; } getDirective() { return this.directives.length === 0 ? null : this.directives[0]; } getDirectives() { return this.directives; } resolveVariable(variable, line) { for (let from of this.getFROMs()) { let range = from.getRange(); if (range.start.line <= line && line <= range.end.line) { // resolve the FROM variable against the initial ARGs let initialARGs = new imageTemplate_1.ImageTemplate(); for (let instruction of this.initialInstructions.getARGs()) { initialARGs.addInstruction(instruction); } return initialARGs.resolveVariable(variable, line); } } let image = this.getContainingImage(vscode_languageserver_types_1.Position.create(line, 0)); if (image === null) { return undefined; } let resolvedVariable = image.resolveVariable(variable, line); if (resolvedVariable === null) { // refers to an uninitialized ARG variable, // try resolving it against the initial ARGs then let initialARGs = new imageTemplate_1.ImageTemplate(); for (let instruction of this.initialInstructions.getARGs()) { initialARGs.addInstruction(instruction); } return initialARGs.resolveVariable(variable, line); } return resolvedVariable; } getAvailableVariables(currentLine) { if (this.getInstructionAt(currentLine) instanceof from_1.From) { let variables = []; for (let arg of this.getInitialARGs()) { let property = arg.getProperty(); if (property) { variables.push(property.getName()); } } return variables; } let image = this.getContainingImage(vscode_languageserver_types_1.Position.create(currentLine, 0)); return image ? image.getAvailableVariables(currentLine) : []; } getParentStage(image) { const templateFrom = image.getFROM(); const imageName = templateFrom === null ? null : templateFrom.getImageName(); if (imageName === null) { return null; } for (const from of this.getFROMs()) { if (from.getBuildStage() === imageName) { const range = from.getRange(); // on the same line then it's an image that shares the name as the build stage if (range.start.line === templateFrom.getRange().start.line) { return null; } return this.getContainingImage(range.start); } } return null; } getStageHierarchy(line) { const image = this.getContainingImage(vscode_languageserver_types_1.Position.create(line, 0)); if (image === null) { return []; } const stages = [image]; let stage = this.getParentStage(image); while (stage !== null) { stages.splice(0, 0, stage); stage = this.getParentStage(stage); } return stages; } getAvailableWorkingDirectories(line) { const availableDirectories = new Set(); for (const image of this.getStageHierarchy(line)) { for (const workdir of image.getWORKDIRs()) { if (workdir.getRange().end.line < line) { let directory = workdir.getAbsolutePath(); if (directory !== undefined && directory !== null) { if (!directory.endsWith("/")) { directory += "/"; } availableDirectories.add(directory); } } } } return Array.from(availableDirectories); } /** * Internally reorganize the comments in the Dockerfile and allocate * them to the relevant build stages that they belong to. */ organizeComments() { const comments = this.getComments(); for (let i = 0; i < comments.length; i++) { if (util_1.Util.isInsideRange(comments[i].getRange().end, this.initialInstructions.getRange())) { this.initialInstructions.addComment(comments[i]); } else { for (const buildStage of this.buildStages) { if (util_1.Util.isInsideRange(comments[i].getRange().start, buildStage.getRange())) { buildStage.addComment(comments[i]); } } } } } getRange() { const comments = this.getComments(); const instructions = this.getInstructions(); let range = null; if (comments.length === 0) { if (instructions.length > 0) { range = vscode_languageserver_types_1.Range.create(instructions[0].getRange().start, instructions[instructions.length - 1].getRange().end); } } else if (instructions.length === 0) { range = vscode_languageserver_types_1.Range.create(comments[0].getRange().start, comments[comments.length - 1].getRange().end); } else { const commentStart = comments[0].getRange().start; const commentEnd = comments[comments.length - 1].getRange().end; const instructionStart = instructions[0].getRange().start; const instructionEnd = instructions[instructions.length - 1].getRange().end; if (commentStart.line < instructionStart.line) { if (commentEnd.line < instructionEnd.line) { range = vscode_languageserver_types_1.Range.create(commentStart, instructionEnd); } range = vscode_languageserver_types_1.Range.create(commentStart, commentEnd); } else if (commentEnd.line < instructionEnd.line) { range = vscode_languageserver_types_1.Range.create(instructionStart, instructionEnd); } else { range = vscode_languageserver_types_1.Range.create(instructionStart, commentEnd); } } if (range === null) { if (this.directives.length === 0) { return null; } return this.directives[0].getRange(); } else if (this.directives.length === 0) { return range; } return vscode_languageserver_types_1.Range.create(this.directives[0].getRange().start, range.end); } } exports.Dockerfile = Dockerfile; /***/ }), /***/ 11170: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Flag = void 0; const vscode_languageserver_types_1 = __webpack_require__(8089); const flagOption_1 = __webpack_require__(29571); class Flag { constructor(document, range, name, nameRange, value, valueRange) { this.options = []; this.range = range; this.name = name; this.nameRange = nameRange; this.value = value; this.valueRange = valueRange; if (this.value !== null) { let offset = document.offsetAt(valueRange.start); let nameStart = -1; let valueStart = -1; let hasOptions = false; for (let i = 0; i < value.length; i++) { switch (value.charAt(i)) { case '=': hasOptions = true; if (valueStart === -1) { valueStart = i + 1; break; } break; case ',': this.options.push(this.createFlagOption(document, value, offset, nameStart, valueStart, i)); nameStart = -1; valueStart = -1; break; default: if (nameStart === -1) { nameStart = i; } break; } } if (hasOptions && nameStart !== -1) { this.options.push(this.createFlagOption(document, value, offset, nameStart, valueStart, value.length)); } } } createFlagOption(document, content, documentOffset, nameStart, valueStart, valueEnd) { const optionRange = vscode_languageserver_types_1.Range.create(document.positionAt(documentOffset + nameStart), document.positionAt(documentOffset + valueEnd)); if (valueStart === -1) { return new flagOption_1.FlagOption(optionRange, content.substring(nameStart, valueEnd), optionRange, null, null); } return new flagOption_1.FlagOption(optionRange, content.substring(nameStart, valueStart - 1), vscode_languageserver_types_1.Range.create(document.positionAt(documentOffset + nameStart), document.positionAt(documentOffset + valueStart - 1)), content.substring(valueStart, valueEnd), vscode_languageserver_types_1.Range.create(document.positionAt(documentOffset + valueStart), document.positionAt(documentOffset + valueEnd))); } toString() { if (this.valueRange) { return "--" + this.name + "=" + this.value; } return "--" + this.name; } /** * Returns the range that encompasses this entire flag. This includes the * -- prefix in the beginning to the last character of the flag's value (if * it has been defined). * * @return the entire range of this flag */ getRange() { return this.range; } /** * Returns the name of this flag. The name does not include the -- prefix. * Thus, for HEALTHCHECK's --interval flag, interval is the flag's name and * not --interval. * * @return this flag's name */ getName() { return this.name; } /** * Returns the range that encompasses the flag's name * * @return the range containing the flag's name */ getNameRange() { return this.nameRange; } /** * Returns the value that has been set to this flag. May be null if the * flag is invalid and has no value set like a --start-period. If the flag * is instead a --start-period= with an equals sign then the flag's value * is the empty string. * * @return this flag's value if it has been defined, null otherwise */ getValue() { return this.value; } /** * Returns the range that encompasses this flag's value. If no value has * been set then null will be returned. * * @return the range containing this flag's value, or null if the flag * has no value defined */ getValueRange() { return this.valueRange; } getOption(name) { for (const option of this.options) { if (option.getName() === name) { return option; } } return null; } getOptions() { return this.options; } hasOptions() { return this.options.length > 0; } } exports.Flag = Flag; /***/ }), /***/ 29571: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FlagOption = void 0; class FlagOption { constructor(range, name, nameRange, value, valueRange) { this.range = range; this.name = name; this.nameRange = nameRange; this.value = value; this.valueRange = valueRange; } toString() { if (this.valueRange !== null) { return this.name + "=" + this.value; } return this.name; } getRange() { return this.range; } getName() { return this.name; } getNameRange() { return this.nameRange; } getValue() { return this.value; } getValueRange() { return this.valueRange; } } exports.FlagOption = FlagOption; /***/ }), /***/ 8701: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Heredoc = void 0; /** * Heredoc represents a here-document that has been embedded in a * Dockerfile. * * This API is experimental and subject to change. */ class Heredoc { constructor(startRange, name, nameRange, contentRange, endRange) { this.startRange = startRange; this.name = name; this.nameRange = nameRange; this.contentRange = contentRange; this.endRange = endRange; } /** * Returns the name of the here-document. * * This API is experimental and subject to change. */ getName() { return this.name; } /** * Returns the range of the start operator and the name. If the * here-document is initialized with < { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Remy Suen. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ImageTemplate = void 0; const vscode_languageserver_types_1 = __webpack_require__(8089); const arg_1 = __webpack_require__(60904); const cmd_1 = __webpack_require__(85450); const copy_1 = __webpack_require__(84361); const env_1 = __webpack_require__(22474); const entrypoint_1 = __webpack_require__(75822); const from_1 = __webpack_require__(98654); const healthcheck_1 = __webpack_require__(43355); const onbuild_1 = __webpack_require__(46319); const util_1 = __webpack_require__(98707); const workdir_1 = __webpack_require__(99377); class ImageTemplate { constructor() { this.comments = []; this.instructions = []; } addComment(comment) { this.comments.push(comment); } getComments() { return this.comments; } addInstruction(instruction) { this.instructions.push(instruction); } getInstructions() { return this.instructions; } getInstructionAt(line) { for (let instruction of this.instructions) { if (util_1.Util.isInsideRange(vscode_languageserver_types_1.Position.create(line, 0), instruction.getRange())) { return instruction; } } return null; } /** * Gets all the ARG instructions that are defined in this image. */ getARGs() { let args = []; for (let instruction of this.instructions) { if (instruction instanceof arg_1.Arg) { args.push(instruction); } } return args; } /** * Gets all the CMD instructions that are defined in this image. */ getCMDs() { let cmds = []; for (let instruction of this.instructions) { if (instruction instanceof cmd_1.Cmd) { cmds.push(instruction); } } return cmds; } /** * Gets all the COPY instructions that are defined in this image. */ getCOPYs() { let copies = []; for (let instruction of this.instructions) { if (instruction instanceof copy_1.Copy) { copies.push(instruction); } } return copies; } /** * Gets all the ENTRYPOINT instructions that are defined in this image. */ getENTRYPOINTs() { let froms = []; for (let instruction of this.instructions) { if (instruction instanceof entrypoint_1.Entrypoint) { froms.push(instruction); } } return froms; } /** * Gets all the ENV instructions that are defined in this image. */ getENVs() { let args = []; for (let instruction of this.instructions) { if (instruction instanceof env_1.Env) { args.push(instruction); } } return args; } getFROM() { for (const instruction of this.instructions) { if (instruction instanceof from_1.From) { return instruction; } } return null; } /** * Gets all the FROM instructions that are defined in this image. */ getFROMs() { let froms = []; for (let instruction of this.instructions) { if (instruction instanceof from_1.From) { froms.push(instruction); } } return froms; } /** * Gets all the HEALTHCHECK instructions that are defined in this image. */ getHEALTHCHECKs() { let froms = []; for (let instruction of this.instructions) { if (instruction instanceof healthcheck_1.Healthcheck) { froms.push(instruction); } } return froms; } getWORKDIRs() { const workdirs = []; for (const instruction of this.instructions) { if (instruction instanceof workdir_1.Workdir) { workdirs.push(instruction); } } return workdirs; } getOnbuildTriggers() { let triggers = []; for (let instruction of this.instructions) { if (instruction instanceof onbuild_1.Onbuild) { let trigger = instruction.getTriggerInstruction(); if (trigger) { triggers.push(trigger); } } } return triggers; } getAvailableVariables(currentLine) { const variables = []; for (const arg of this.getARGs()) { if (arg.isBefore(currentLine)) { const property = arg.getProperty(); if (property) { const variable = property.getName(); if (variables.indexOf(variable) === -1) { variables.push(variable); } } } } for (const env of this.getENVs()) { if (env.isBefore(currentLine)) { for (const property of env.getProperties()) { const variable = property.getName(); if (variables.indexOf(variable) === -1) { variables.push(variable); } } } } return variables; } /** * Resolves a variable with the given name at the specified line * to its value. If null is returned, then the variable has been * defined but no value was given. If undefined is returned, then * a variable with the given name has not been defined yet as of * the given line. * * @param variable the name of the variable to resolve * @param line the line number that the variable is on, zero-based * @return the value of the variable as defined by an ARG or ENV * instruction, or null if no value has been specified, or * undefined if a variable with the given name has not * been defined */ resolveVariable(variable, line) { let envs = this.getENVs(); for (let i = envs.length - 1; i >= 0; i--) { if (envs[i].isBefore(line)) { for (let property of envs[i].getProperties()) { if (property.getName() === variable) { return property.getValue(); } } } } let args = this.getARGs(); for (let i = args.length - 1; i >= 0; i--) { if (args[i].isBefore(line)) { let property = args[i].getProperty(); if (property && property.getName() === variable) { return property.getValue(); } } } return undefined; } getRange() { const instructions = this.getInstructions(); if (instructions.length === 0) { // all templates should have instructions, this only happens for // the initial set of instruction return vscode_languageserver_types_1.Range.create(0, 0, 0, 0); } const instructionStart = instructions[0].getRange().start; const instructionEnd = instructions[instructions.length - 1].getRange().end; return vscode_languageserver_types_1.Range.create(instructionStart, instructionEnd); } contains(position) { const range = this.getRange(); if (range === null) { return false; } return util_1.Util.isInsideRange(position, range); } } exports.ImageTemplate = ImageTemplate; /***/ }), /***/ 99311: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Instruction = void 0; const vscode_languageserver_types_1 = __webpack_require__(8089); const util_1 = __webpack_require__(98707); const line_1 = __webpack_require__(47119); const argument_1 = __webpack_require__(12447); const heredoc_1 = __webpack_require__(8701); const variable_1 = __webpack_require__(28155); const main_1 = __webpack_require__(20871); class Instruction extends line_1.Line { constructor(document, range, dockerfile, escapeChar, instruction, instructionRange) { super(document, range); this.dockerfile = dockerfile; this.escapeChar = escapeChar; this.instruction = instruction; this.instructionRange = instructionRange; } toString() { let value = this.getKeyword(); for (let arg of this.getRawArguments()) { value += ' '; value += arg.getValue(); } return value; } getRangeContent(range) { if (range === null) { return null; } return this.document.getText().substring(this.document.offsetAt(range.start), this.document.offsetAt(range.end)); } getInstructionRange() { return this.instructionRange; } getInstruction() { return this.instruction; } getKeyword() { return this.getInstruction().toUpperCase(); } getArgumentsRange() { let args = this.getArguments(); if (args.length === 0) { return null; } return vscode_languageserver_types_1.Range.create(args[0].getRange().start, args[args.length - 1].getRange().end); } getArgumentsRanges() { let args = this.getArguments(); if (args.length === 0) { return []; } if (args[0].getRange().start.line === args[args.length - 1].getRange().end.line) { return [vscode_languageserver_types_1.Range.create(args[0].getRange().start, args[args.length - 1].getRange().end)]; } let ranges = []; let end = -1; let startPosition = args[0].getRange().start; let range = this.getInstructionRange(); let extra = this.document.offsetAt(startPosition) - this.document.offsetAt(range.start); let content = this.getTextContent(); let fullArgs = content.substring(extra, this.document.offsetAt(args[args.length - 1].getRange().end) - this.document.offsetAt(range.start)); let offset = this.document.offsetAt(range.start) + extra; let start = false; let comment = false; for (let i = 0; i < fullArgs.length; i++) { let char = fullArgs.charAt(i); if (char === this.escapeChar) { let next = fullArgs.charAt(i + 1); if (next === ' ' || next === '\t') { whitespaceCheck: for (let j = i + 2; j < fullArgs.length; j++) { switch (fullArgs.charAt(j)) { case ' ': case '\t': continue; case '\r': j++; case '\n': if (startPosition !== null) { ranges.push(vscode_languageserver_types_1.Range.create(startPosition, this.document.positionAt(offset + end + 1))); } startPosition = null; start = true; comment = false; i = j; break whitespaceCheck; default: break whitespaceCheck; } } } else if (next === '\r') { if (startPosition !== null) { ranges.push(vscode_languageserver_types_1.Range.create(startPosition, this.document.positionAt(offset + end + 1))); startPosition = null; } start = true; comment = false; i += 2; } else if (next === '\n') { if (startPosition !== null) { ranges.push(vscode_languageserver_types_1.Range.create(startPosition, this.document.positionAt(offset + end + 1))); } startPosition = null; start = true; comment = false; i++; } else { i++; } } else if (util_1.Util.isNewline(char)) { if (comment) { startPosition = null; start = true; comment = false; } } else { if (!comment) { if (startPosition === null) { if (char === '#') { comment = true; continue; } let position = this.document.positionAt(offset + i); if (position.character !== 0) { startPosition = vscode_languageserver_types_1.Position.create(position.line, 0); } } end = i; } } } if (startPosition === null) { // should only happen if the last argument is on its own line with // no leading whitespace ranges.push(vscode_languageserver_types_1.Range.create(this.document.positionAt(offset + end), this.document.positionAt(offset + end + 1))); } else { ranges.push(vscode_languageserver_types_1.Range.create(startPosition, this.document.positionAt(offset + end + 1))); } return ranges; } getRawArgumentsContent() { let args = this.getArguments(); if (args.length === 0) { return null; } return this.getRangeContent(vscode_languageserver_types_1.Range.create(args[0].getRange().start, args[args.length - 1].getRange().end)); } getArgumentsContent() { let args = this.getArguments(); if (args.length === 0) { return null; } let content = ""; let ranges = this.getArgumentsRanges(); let documentText = this.document.getText(); for (let range of ranges) { content += documentText.substring(this.document.offsetAt(range.start), this.document.offsetAt(range.end)); } return content; } getArguments() { return this.getRawArguments(); } getRawArguments() { let args = []; let range = this.getInstructionRange(); let extra = this.document.offsetAt(range.end) - this.document.offsetAt(range.start); let content = this.getTextContent(); let fullArgs = content.substring(extra); let offset = this.document.offsetAt(range.start) + extra; let start = false; let comment = false; let found = -1; // determines whether the parser has found a space or tab // whitespace character that's a part of an escaped newline sequence let escapedWhitespaceDetected = false; // determines if the parser is currently in an escaped newline sequence let escaping = false; let escapeMarker = -1; let escapedArg = ""; for (let i = 0; i < fullArgs.length; i++) { let char = fullArgs.charAt(i); if (util_1.Util.isWhitespace(char)) { if (escaping) { escapedWhitespaceDetected = true; if (util_1.Util.isNewline(char)) { // reached a newline, any previously // detected whitespace should be ignored escapedWhitespaceDetected = false; if (comment) { // reached a newline, no longer in a comment comment = false; start = true; } } continue; } else if (found !== -1) { if (escapeMarker === -1) { args.push(new argument_1.Argument(escapedArg, vscode_languageserver_types_1.Range.create(this.document.positionAt(offset + found), this.document.positionAt(offset + i)))); } else { args.push(new argument_1.Argument(escapedArg, vscode_languageserver_types_1.Range.create(this.document.positionAt(offset + found), this.document.positionAt(offset + escapeMarker)))); } escapeMarker = -1; escapedArg = ""; found = -1; } } else if (char === this.escapeChar) { let next = fullArgs.charAt(i + 1); if (next === ' ' || next === '\t') { whitespaceCheck: for (let j = i + 2; j < fullArgs.length; j++) { let newlineCheck = fullArgs.charAt(j); switch (newlineCheck) { case ' ': case '\t': continue; case '\r': j++; case '\n': comment = false; escaping = true; start = true; if (found !== -1) { escapeMarker = i; } i = j; break whitespaceCheck; default: escapeMarker = i; if (found === -1) { i = j - 1; } break whitespaceCheck; } } } else if (next === '\r') { comment = false; escaping = true; start = true; if (found !== -1 && escapeMarker === -1) { escapeMarker = i; } i += 2; } else if (next === '\n') { comment = false; escaping = true; start = true; if (found !== -1 && escapeMarker === -1) { escapeMarker = i; } i++; } else { if (escapedWhitespaceDetected && escapeMarker !== -1) { args.push(new argument_1.Argument(escapedArg, vscode_languageserver_types_1.Range.create(this.document.positionAt(offset + found), this.document.positionAt(offset + escapeMarker)))); escapedArg = ""; found = -1; } escapeMarker = -1; escapedWhitespaceDetected = false; escaping = false; if (next === '$') { escapedArg = escapedArg + char + next; } else if (next === '') { // reached EOF, stop processing break; } else { escapedArg = escapedArg + next; } if (found === -1) { found = i; } i++; } } else if (!comment) { if (start && char === '#') { comment = true; } else { if (escapedWhitespaceDetected && escapeMarker !== -1) { args.push(new argument_1.Argument(escapedArg, vscode_languageserver_types_1.Range.create(this.document.positionAt(offset + found), this.document.positionAt(offset + escapeMarker)))); escapedArg = ""; found = -1; } escapedWhitespaceDetected = false; escaping = false; escapeMarker = -1; escapedArg = escapedArg + char; if (found === -1) { found = i; } } // non-whitespace character detected, reset start = false; } } if (found !== -1) { if (escapeMarker === -1) { args.push(new argument_1.Argument(escapedArg, vscode_languageserver_types_1.Range.create(this.document.positionAt(offset + found), this.document.positionAt(offset + fullArgs.length)))); } else { args.push(new argument_1.Argument(escapedArg, vscode_languageserver_types_1.Range.create(this.document.positionAt(offset + found), this.document.positionAt(offset + escapeMarker)))); } } return args; } getExpandedArguments() { let args = this.getArguments(); for (let i = 0; i < args.length; i++) { const argRange = args[i].getRange(); let offset = this.document.offsetAt(argRange.start); const variables = this.parseVariables(offset, args[i].getValue()); const swaps = []; let requiresExpansion = false; for (let variable of variables) { const value = this.dockerfile.resolveVariable(variable.getName(), variable.getNameRange().start.line); swaps.push(value); requiresExpansion = requiresExpansion || value !== undefined; } if (requiresExpansion) { let expanded = ""; for (let j = 0; j < swaps.length; j++) { const variableRange = variables[j].getRange(); const start = this.document.offsetAt(variableRange.start); const end = this.document.offsetAt(variableRange.end); if (swaps[j]) { // replace variable with its resolved value expanded += this.document.getText().substring(offset, start); expanded += swaps[j]; offset = end; } else { expanded += this.document.getText().substring(offset, end); offset = end; } } const argEnd = this.document.offsetAt(argRange.end); if (argEnd !== offset) { // if the variable's range doesn't match the argument, // append the remaining text expanded += this.document.getText().substring(offset, argEnd); } args[i] = new argument_1.Argument(expanded, argRange); } } return args; } getVariables() { const variables = []; const args = this.getRawArguments(); for (const arg of args) { let range = arg.getRange(); let rawValue = this.document.getText().substring(this.document.offsetAt(range.start), this.document.offsetAt(range.end)); const parsedVariables = this.parseVariables(this.document.offsetAt(arg.getRange().start), rawValue); for (const parsedVariable of parsedVariables) { variables.push(parsedVariable); } } return variables; } parseVariables(offset, arg) { let variables = []; variableLoop: for (let i = 0; i < arg.length; i++) { switch (arg.charAt(i)) { case this.escapeChar: if (arg.charAt(i + 1) === '$') { i++; } break; case '$': if (arg.charAt(i + 1) === '{') { let escapedString = "${"; let escapedName = ""; let nameEnd = -1; let escapedSubstitutionParameter = ""; let substitutionStart = -1; let substitutionEnd = -1; let modifierRead = -1; nameLoop: for (let j = i + 2; j < arg.length; j++) { let char = arg.charAt(j); switch (char) { case this.escapeChar: for (let k = j + 1; k < arg.length; k++) { switch (arg.charAt(k)) { case ' ': case '\t': case '\r': // ignore whitespace continue; case '\n': // escape this newline j = k; continue nameLoop; } } break; case '}': escapedString += '}'; let modifier = null; let modifierRange = null; let substitutionParameter = modifierRead !== -1 ? escapedSubstitutionParameter : null; let substitutionRange = null; if (nameEnd === -1) { nameEnd = j; } else if (nameEnd + 1 === j) { modifier = ""; modifierRange = vscode_languageserver_types_1.Range.create(this.document.positionAt(offset + nameEnd + 1), this.document.positionAt(offset + nameEnd + 1)); } else { if (substitutionStart === -1) { // no substitution parameter found, // but a modifier character existed, // just offset the range by 1 from // the modifier character substitutionStart = modifierRead + 1; substitutionEnd = modifierRead + 1; } else { // offset one more from the last // character found substitutionEnd = substitutionEnd + 1; } modifier = arg.substring(modifierRead, modifierRead + 1); modifierRange = vscode_languageserver_types_1.Range.create(this.document.positionAt(offset + modifierRead), this.document.positionAt(offset + modifierRead + 1)); substitutionRange = vscode_languageserver_types_1.Range.create(this.document.positionAt(offset + substitutionStart), this.document.positionAt(offset + substitutionEnd)); } let start = this.document.positionAt(offset + i); variables.push(new variable_1.Variable(escapedName, vscode_languageserver_types_1.Range.create(this.document.positionAt(offset + i + 2), this.document.positionAt(offset + nameEnd)), vscode_languageserver_types_1.Range.create(start, this.document.positionAt(offset + j + 1)), modifier, modifierRange, substitutionParameter, substitutionRange, this.dockerfile.resolveVariable(escapedName, start.line) !== undefined, this.isBuildVariable(escapedName, start.line), escapedString)); i = j; continue variableLoop; case ':': if (nameEnd === -1) { nameEnd = j; } else if (modifierRead !== -1) { if (substitutionStart === -1) { substitutionStart = j; substitutionEnd = j; } else { substitutionEnd = j; } escapedSubstitutionParameter += ':'; } else { modifierRead = j; } escapedString += ':'; break; case '\n': case '\r': case ' ': case '\t': break; default: if (nameEnd === -1) { escapedName += char; } else if (modifierRead !== -1) { if (substitutionStart === -1) { substitutionStart = j; substitutionEnd = j; } else { substitutionEnd = j; } escapedSubstitutionParameter += char; } else { modifierRead = j; } escapedString += char; break; } } // no } found, not a valid variable, stop processing break variableLoop; } else if (util_1.Util.isWhitespace(arg.charAt(i + 1)) || i === arg.length - 1) { // $ followed by whitespace or EOF, ignore this variable continue; } else { let escapedName = ""; nameLoop: for (let j = i + 1; j < arg.length; j++) { let char = arg.charAt(j); switch (char) { case '\r': case '\n': case ' ': case '\t': continue; case '$': case '\'': case '"': let varStart = this.document.positionAt(offset + i); variables.push(new variable_1.Variable(escapedName, vscode_languageserver_types_1.Range.create(this.document.positionAt(offset + i + 1), this.document.positionAt(offset + j)), vscode_languageserver_types_1.Range.create(varStart, this.document.positionAt(offset + j)), null, null, null, null, this.dockerfile.resolveVariable(escapedName, varStart.line) !== undefined, this.isBuildVariable(escapedName, varStart.line), '$' + escapedName)); i = j - 1; continue variableLoop; case this.escapeChar: for (let k = j + 1; k < arg.length; k++) { switch (arg.charAt(k)) { case ' ': case '\t': case '\r': // ignore whitespace continue; case '\n': // escape this newline j = k; continue nameLoop; } } // reached EOF after an escape character let start = this.document.positionAt(offset + i); variables.push(new variable_1.Variable(escapedName, vscode_languageserver_types_1.Range.create(this.document.positionAt(offset + i + 1), this.document.positionAt(offset + j)), vscode_languageserver_types_1.Range.create(start, this.document.positionAt(offset + j)), null, null, null, null, this.dockerfile.resolveVariable(escapedName, start.line) !== undefined, this.isBuildVariable(escapedName, start.line), '$' + escapedName)); break variableLoop; } if (char.match(/^[a-z0-9_]+$/i) === null) { let varStart = this.document.positionAt(offset + i); variables.push(new variable_1.Variable(escapedName, vscode_languageserver_types_1.Range.create(this.document.positionAt(offset + i + 1), this.document.positionAt(offset + j)), vscode_languageserver_types_1.Range.create(varStart, this.document.positionAt(offset + j)), null, null, null, null, this.dockerfile.resolveVariable(escapedName, varStart.line) !== undefined, this.isBuildVariable(escapedName, varStart.line), '$' + escapedName)); i = j - 1; continue variableLoop; } escapedName += char; } let start = this.document.positionAt(offset + i); variables.push(new variable_1.Variable(escapedName, vscode_languageserver_types_1.Range.create(this.document.positionAt(offset + i + 1), this.document.positionAt(offset + arg.length)), vscode_languageserver_types_1.Range.create(start, this.document.positionAt(offset + arg.length)), null, null, null, null, this.dockerfile.resolveVariable(escapedName, start.line) !== undefined, this.isBuildVariable(escapedName, start.line), '$' + escapedName)); } break variableLoop; } } return variables; } isBuildVariable(variable, line) { if (this.getKeyword() === main_1.Keyword.FROM) { for (const initialArg of this.dockerfile.getInitialARGs()) { const arg = initialArg; const property = arg.getProperty(); if (property && variable === property.getName()) { return true; } } return undefined; } let image = this.dockerfile.getContainingImage(vscode_languageserver_types_1.Position.create(line, 0)); let envs = image.getENVs(); for (let i = envs.length - 1; i >= 0; i--) { if (envs[i].isBefore(line)) { for (let property of envs[i].getProperties()) { if (property.getName() === variable) { return false; } } } } let args = image.getARGs(); for (let i = args.length - 1; i >= 0; i--) { if (args[i].isBefore(line)) { let property = args[i].getProperty(); if (property && property.getName() === variable) { return true; } } } return undefined; } createSingleLineHeredocs(args) { const heredocs = []; // instruction only on one line, if heredocs exist they would be incomplete for (const arg of args) { const value = arg.getValue(); if (value.startsWith("<<")) { const startRange = arg.getRange(); const nameRange = this.getNameRange(startRange); const name = this.getName(nameRange); heredocs.push(new heredoc_1.Heredoc(startRange, name, nameRange, null, null)); } } return heredocs; } getName(nameRange) { const content = this.document.getText(nameRange); let escaping = false; let name = ""; nameLoop: for (let i = 0; i < content.length; i++) { const ch = content.charAt(i); switch (ch) { case this.escapeChar: escaping = true; for (let j = i + 1; j < content.length; j++) { switch (content.charAt(j)) { case ' ': case '\t': break; case '\r': i = j + 1; continue nameLoop; case '\n': i = j; continue nameLoop; default: name += content.charAt(j); i = j; continue nameLoop; } } break; case '#': if (escaping) { for (let j = i + 1; j < content.length; j++) { switch (content.charAt(j)) { case '\n': i = j; continue nameLoop; } } } case ' ': case '\t': case '\r': case '\n': if (escaping) { break; } default: name += ch; break; } } return name; } getNameRange(startRange) { const content = this.document.getText(startRange); let endFound = false; let searchHyphen = false; let start = -1; let end = -1; let escaping = false; let quote = null; contentLoop: for (let i = 0; i < content.length; i++) { const ch = content.charAt(i); switch (ch) { case '"': case '\'': if (quote === ch) { break contentLoop; } quote = ch; continue; case this.escapeChar: for (let j = i + 1; j < content.length; j++) { switch (content.charAt(j)) { case '\n': escaping = true; j = i; continue contentLoop; } } break; case ' ': case '\t': case '\r': case '\n': break; case '<': if (endFound) { searchHyphen = true; } else { endFound = true; } break; case '-': if (searchHyphen) { searchHyphen = false; break; } case '#': if (escaping) { for (let j = i + 1; j < content.length; j++) { switch (content.charAt(j)) { case '\n': i = j; continue contentLoop; } } } default: if (start === -1) { start = i; } if (quote !== null) { end = i + 1; break; } break contentLoop; } } if (start === -1) { return vscode_languageserver_types_1.Range.create(startRange.end, startRange.end); } const nameStart = this.document.positionAt(this.document.offsetAt(startRange.start) + start); const nameEnd = quote !== null ? this.document.positionAt(this.document.offsetAt(startRange.start) + end) : startRange.end; return vscode_languageserver_types_1.Range.create(nameStart, nameEnd); } getHeredocs() { const args = this.getArguments(); if (args.length === 0) { return []; } const heredocs = []; const range = this.getRange(); if (range.start.line === range.end.line) { // instruction only on one line, if heredocs exist they would be incomplete return this.createSingleLineHeredocs(args); } const heredocDefinitions = []; let heredocsProcessed = false; let escaping = false; let contentStart = -1; let contentEnd = -1; let lineStart = -1; let currentHeredoc = 0; const startOffset = this.document.offsetAt(args[0].getRange().start); const content = this.getRangeContent(vscode_languageserver_types_1.Range.create(args[0].getRange().start, this.getRange().end)); contentLoop: for (let i = 0; i < content.length; i++) { switch (content.charAt(i)) { case this.escapeChar: escaping = true; for (let j = i + 1; j < content.length; j++) { switch (content.charAt(j)) { case ' ': case '\t': break; case '\r': j++; case '\n': i = j; continue contentLoop; default: i = j; continue contentLoop; } } break; case '\r': break; case '\n': if (escaping) { break; } if (heredocsProcessed) { if (contentStart === -1) { contentStart = i; } contentEnd = i; const arg = heredocDefinitions[currentHeredoc]; const startRange = arg.getRange(); const nameRange = this.getNameRange(startRange); const name = this.getName(nameRange); const delimiterRange = this.getDelimiterRange(arg, name, vscode_languageserver_types_1.Range.create(this.document.positionAt(startOffset + lineStart), this.document.positionAt(startOffset + i))); if (delimiterRange !== null) { const contentRange = vscode_languageserver_types_1.Range.create(this.document.positionAt(startOffset + contentStart), this.document.positionAt(startOffset + lineStart - 1)); heredocs.push(new heredoc_1.Heredoc(startRange, name, nameRange, contentRange, delimiterRange)); contentStart = -1; currentHeredoc++; } lineStart = -1; } else { // found a newline that hasn't been escaped, // must be in a heredoc const offsetLimit = startOffset + i; for (const arg of args) { // check if this argument is on the initial line of the instruction, // note that it may not all be on the same line due to escaped newlines, // because of that we need to use offset checks instead of line checks // as an argument being on a different line in the document does not // imply it is on a different line from the Dockerfile's point of view if (this.document.offsetAt(arg.getRange().start) < offsetLimit) { if (arg.getValue().startsWith("<<")) { heredocDefinitions.push(arg); } } else { break; } } heredocsProcessed = true; lineStart = -1; continue contentLoop; } break; case ' ': case '\t': if (escaping) { break; } case '#': if (escaping) { for (let j = i + 1; j < content.length; j++) { switch (content.charAt(j)) { case '\n': i = j; continue contentLoop; } } } default: if (escaping) { escaping = false; } if (heredocsProcessed) { if (contentStart === -1) { contentStart = i; } if (lineStart === -1) { lineStart = i; } } break; } } if (heredocsProcessed) { const arg = heredocDefinitions[currentHeredoc]; const startRange = arg.getRange(); const nameRange = this.getNameRange(startRange); const name = this.getName(nameRange); let contentRange = null; // check if the last line of this instruction matches the name of the last heredoc const delimiterRange = this.getDelimiterRange(arg, name, vscode_languageserver_types_1.Range.create(this.document.positionAt(startOffset + lineStart), range.end)); if (delimiterRange === null) { contentRange = vscode_languageserver_types_1.Range.create(this.document.positionAt(startOffset + contentStart), range.end); } else if (contentEnd !== -1) { contentRange = vscode_languageserver_types_1.Range.create(this.document.positionAt(startOffset + contentStart), this.document.positionAt(startOffset + contentEnd)); } heredocs.push(new heredoc_1.Heredoc(startRange, name, nameRange, contentRange, delimiterRange)); currentHeredoc++; for (let i = currentHeredoc; i < heredocDefinitions.length; i++) { const arg = heredocDefinitions[currentHeredoc]; const startRange = arg.getRange(); const nameRange = this.getNameRange(startRange); const name = this.getName(nameRange); heredocs.push(new heredoc_1.Heredoc(startRange, name, nameRange, null, null)); currentHeredoc++; } } else { // instruction only on one line, if heredocs exist they would be incomplete return this.createSingleLineHeredocs(args); } return heredocs; } getDelimiterRange(startArg, name, candidateRange) { const text = this.document.getText(candidateRange); if (startArg.getValue().startsWith("<<-")) { // remove tabs in the front let index = 0; while (text.charAt(index) === '\t') { index++; } if (text.substring(index) === name) { return vscode_languageserver_types_1.Range.create(vscode_languageserver_types_1.Position.create(candidateRange.start.line, index), candidateRange.end); } return null; } return text === name ? candidateRange : null; } } exports.Instruction = Instruction; /***/ }), /***/ 46581: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Add = void 0; const jsonInstruction_1 = __webpack_require__(24990); class Add extends jsonInstruction_1.JSONInstruction { constructor(document, range, dockerfile, escapeChar, instruction, instructionRange) { super(document, range, dockerfile, escapeChar, instruction, instructionRange); } stopSearchingForFlags(argument) { return argument.indexOf("--") === -1; } } exports.Add = Add; /***/ }), /***/ 60904: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Arg = void 0; const property_1 = __webpack_require__(38698); const propertyInstruction_1 = __webpack_require__(78535); class Arg extends propertyInstruction_1.PropertyInstruction { constructor(document, range, dockerfile, escapeChar, instruction, instructionRange) { super(document, range, dockerfile, escapeChar, instruction, instructionRange); this.property = null; const args = this.getPropertyArguments(); if (args.length === 1) { this.property = new property_1.Property(this.document, this.escapeChar, args[0]); } else { this.property = null; } } /** * Returns the variable defined by this ARG. This may be null if * this ARG instruction is malformed and has no variable * declaration. */ getProperty() { return this.property; } } exports.Arg = Arg; /***/ }), /***/ 85450: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Cmd = void 0; const jsonInstruction_1 = __webpack_require__(24990); class Cmd extends jsonInstruction_1.JSONInstruction { constructor(document, range, dockerfile, escapeChar, instruction, instructionRange) { super(document, range, dockerfile, escapeChar, instruction, instructionRange); } } exports.Cmd = Cmd; /***/ }), /***/ 84361: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Copy = void 0; const jsonInstruction_1 = __webpack_require__(24990); class Copy extends jsonInstruction_1.JSONInstruction { constructor(document, range, dockerfile, escapeChar, instruction, instructionRange) { super(document, range, dockerfile, escapeChar, instruction, instructionRange); } stopSearchingForFlags(argument) { return argument.indexOf("--") === -1; } getFromFlag() { let flags = super.getFlags(); return flags.length === 1 && flags[0].getName() === "from" ? flags[0] : null; } /** * Returns there here-documents that are defined in this RUN * instruction. * * This API is experimental and subject to change. */ getHeredocs() { return super.getHeredocs(); } } exports.Copy = Copy; /***/ }), /***/ 75822: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Entrypoint = void 0; const jsonInstruction_1 = __webpack_require__(24990); class Entrypoint extends jsonInstruction_1.JSONInstruction { constructor(document, range, dockerfile, escapeChar, instruction, instructionRange) { super(document, range, dockerfile, escapeChar, instruction, instructionRange); } } exports.Entrypoint = Entrypoint; /***/ }), /***/ 22474: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Env = void 0; const propertyInstruction_1 = __webpack_require__(78535); class Env extends propertyInstruction_1.PropertyInstruction { constructor(document, range, dockerfile, escapeChar, instruction, instructionRange) { super(document, range, dockerfile, escapeChar, instruction, instructionRange); } getProperties() { return super.getProperties(); } } exports.Env = Env; /***/ }), /***/ 98654: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.From = void 0; const vscode_languageserver_types_1 = __webpack_require__(8089); const modifiableInstruction_1 = __webpack_require__(78514); class From extends modifiableInstruction_1.ModifiableInstruction { constructor(document, range, dockerfile, escapeChar, instruction, instructionRange) { super(document, range, dockerfile, escapeChar, instruction, instructionRange); } stopSearchingForFlags(argument) { return argument.indexOf("--") === -1; } getImage() { return this.getRangeContent(this.getImageRange()); } /** * Returns the name of the image that will be used as the base image. * * @return the base image's name, or null if unspecified */ getImageName() { return this.getRangeContent(this.getImageNameRange()); } /** * Returns the range that covers the name of the image used by * this instruction. * * @return the range of the name of this instruction's argument, * or null if no image has been specified */ getImageNameRange() { let range = this.getImageRange(); if (range) { let registryRange = this.getRegistryRange(); if (registryRange) { range.start = this.document.positionAt(this.document.offsetAt(registryRange.end) + 1); } let tagRange = this.getImageTagRange(); let digestRange = this.getImageDigestRange(); if (tagRange === null) { if (digestRange !== null) { range.end = this.document.positionAt(this.document.offsetAt(digestRange.start) - 1); } } else { range.end = this.document.positionAt(this.document.offsetAt(tagRange.start) - 1); } return range; } return null; } /** * Returns the range that covers the image argument of this * instruction. This includes the tag or digest of the image if * it has been specified by the instruction. * * @return the range of the image argument, or null if no image * has been specified */ getImageRange() { let args = this.getArguments(); return args.length !== 0 ? args[0].getRange() : null; } getImageTag() { return this.getRangeContent(this.getImageTagRange()); } /** * Returns the range in the document that the tag of the base * image encompasses. * * @return the base image's tag's range in the document, or null * if no tag has been specified */ getImageTagRange() { const range = this.getImageRange(); if (range) { const rangeStartOffset = this.document.offsetAt(range.start); const content = this.getRangeContent(range); const atIndex = this.indexOf(rangeStartOffset, content, '@'); const slashIndex = content.indexOf('/'); if (atIndex === -1) { const colonIndex = this.lastIndexOf(rangeStartOffset, content, ':'); if (colonIndex > slashIndex) { return vscode_languageserver_types_1.Range.create(range.start.line, range.start.character + colonIndex + 1, range.end.line, range.end.character); } } const subcontent = content.substring(0, atIndex); const subcolonIndex = subcontent.indexOf(':'); if (subcolonIndex === -1) { return null; } if (slashIndex === -1) { // slash not found suggests no registry and no namespace defined return vscode_languageserver_types_1.Range.create(this.document.positionAt(rangeStartOffset + subcolonIndex + 1), this.document.positionAt(rangeStartOffset + atIndex)); } // both colon and slash found, check if it is a port if (subcolonIndex < slashIndex) { return null; } return vscode_languageserver_types_1.Range.create(this.document.positionAt(rangeStartOffset + subcolonIndex + 1), this.document.positionAt(rangeStartOffset + subcontent.length)); } return null; } getImageDigest() { return this.getRangeContent(this.getImageDigestRange()); } /** * Returns the range in the document that the digest of the base * image encompasses. * * @return the base image's digest's range in the document, or null * if no digest has been specified */ getImageDigestRange() { let range = this.getImageRange(); if (range) { let content = this.getRangeContent(range); let index = this.lastIndexOf(this.document.offsetAt(range.start), content, '@'); if (index !== -1) { return vscode_languageserver_types_1.Range.create(range.start.line, range.start.character + index + 1, range.end.line, range.end.character); } } return null; } indexOf(documentOffset, content, searchString) { let index = content.indexOf(searchString); const variables = this.getVariables(); for (let i = 0; i < variables.length; i++) { const position = documentOffset + index; const variableRange = variables[i].getRange(); if (this.document.offsetAt(variableRange.start) < position && position < this.document.offsetAt(variableRange.end)) { const offset = this.document.offsetAt(variableRange.end) - documentOffset; const substring = content.substring(offset); const subIndex = substring.indexOf(searchString); if (subIndex === -1) { return -1; } index = subIndex + offset; i = -1; continue; } } return index; } lastIndexOf(documentOffset, content, searchString) { let index = content.lastIndexOf(searchString); const variables = this.getVariables(); for (let i = 0; i < variables.length; i++) { const position = documentOffset + index; const variableRange = variables[i].getRange(); if (this.document.offsetAt(variableRange.start) < position && position < this.document.offsetAt(variableRange.end)) { index = content.substring(0, index).lastIndexOf(searchString); if (index === -1) { return -1; } i = -1; continue; } } return index; } getRegistry() { return this.getRangeContent(this.getRegistryRange()); } getRegistryRange() { const range = this.getImageRange(); if (range) { const tagRange = this.getImageTagRange(); const digestRange = this.getImageDigestRange(); if (tagRange === null) { if (digestRange !== null) { range.end = this.document.positionAt(this.document.offsetAt(digestRange.start) - 1); } } else { range.end = this.document.positionAt(this.document.offsetAt(tagRange.start) - 1); } const content = this.getRangeContent(range); const rangeStart = this.document.offsetAt(range.start); const startingSlashIndex = this.indexOf(rangeStart, content, '/'); if (startingSlashIndex === -1) { return null; } const portIndex = this.indexOf(rangeStart, content, ':'); const dotIndex = this.indexOf(rangeStart, content, '.'); // hostname detected if (portIndex !== -1 || dotIndex !== -1) { return vscode_languageserver_types_1.Range.create(range.start, this.document.positionAt(rangeStart + startingSlashIndex)); } const registry = content.substring(0, startingSlashIndex); // localhost registry detected if (registry === 'localhost') { return vscode_languageserver_types_1.Range.create(range.start, this.document.positionAt(rangeStart + startingSlashIndex)); } } return null; } getBuildStage() { let range = this.getBuildStageRange(); return range === null ? null : this.getRangeContent(range); } getBuildStageRange() { let args = this.getArguments(); if (args.length > 2 && args[1].getValue().toUpperCase() === "AS") { return args[2].getRange(); } return null; } getPlatformFlag() { let flags = super.getFlags(); return flags.length === 1 && flags[0].getName() === "platform" ? flags[0] : null; } } exports.From = From; /***/ }), /***/ 43355: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Healthcheck = void 0; const modifiableInstruction_1 = __webpack_require__(78514); class Healthcheck extends modifiableInstruction_1.ModifiableInstruction { constructor(document, range, dockerfile, escapeChar, instruction, instructionRange) { super(document, range, dockerfile, escapeChar, instruction, instructionRange); } stopSearchingForFlags(argument) { argument = argument.toUpperCase(); return argument === "CMD" || argument === "NONE"; } getSubcommand() { let args = this.getArguments(); return args.length !== 0 ? args[0] : null; } } exports.Healthcheck = Healthcheck; /***/ }), /***/ 30938: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Label = void 0; const propertyInstruction_1 = __webpack_require__(78535); const util_1 = __webpack_require__(98707); class Label extends propertyInstruction_1.PropertyInstruction { constructor(document, range, dockerfile, escapeChar, instruction, instructionRange) { super(document, range, dockerfile, escapeChar, instruction, instructionRange); } getVariables() { const variables = super.getVariables(); const properties = this.getProperties(); // iterate over all of this LABEL's properties for (const property of properties) { const value = property.getUnescapedValue(); // check if the value is contained in single quotes, // single quotes would indicate a literal value if (value !== null && value.length > 2 && value.charAt(0) === '\'' && value.charAt(value.length - 1) === '\'') { const range = property.getValueRange(); for (let i = 0; i < variables.length; i++) { // if a variable is in a single quote, remove it from the list if (util_1.Util.isInsideRange(variables[i].getRange().start, range)) { variables.splice(i, 1); i--; } } } } return variables; } getProperties() { return super.getProperties(); } } exports.Label = Label; /***/ }), /***/ 46319: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Onbuild = void 0; const vscode_languageserver_types_1 = __webpack_require__(8089); const parser_1 = __webpack_require__(50668); const instruction_1 = __webpack_require__(99311); class Onbuild extends instruction_1.Instruction { constructor(document, range, dockerfile, escapeChar, instruction, instructionRange) { super(document, range, dockerfile, escapeChar, instruction, instructionRange); } getTrigger() { let trigger = this.getTriggerWord(); return trigger === null ? null : trigger.toUpperCase(); } getTriggerWord() { return this.getRangeContent(this.getTriggerRange()); } getTriggerRange() { let args = this.getArguments(); return args.length > 0 ? args[0].getRange() : null; } getTriggerInstruction() { let triggerRange = this.getTriggerRange(); if (triggerRange === null) { return null; } let args = this.getArguments(); return parser_1.Parser.createInstruction(this.document, this.dockerfile, this.escapeChar, vscode_languageserver_types_1.Range.create(args[0].getRange().start, this.getRange().end), this.getTriggerWord(), triggerRange); } } exports.Onbuild = Onbuild; /***/ }), /***/ 3062: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Run = void 0; const jsonInstruction_1 = __webpack_require__(24990); class Run extends jsonInstruction_1.JSONInstruction { constructor(document, range, dockerfile, escapeChar, instruction, instructionRange) { super(document, range, dockerfile, escapeChar, instruction, instructionRange); } stopSearchingForFlags(argument) { return argument.indexOf("--") === -1; } /** * Returns there here-documents that are defined in this RUN * instruction. * * This API is experimental and subject to change. */ getHeredocs() { return super.getHeredocs(); } } exports.Run = Run; /***/ }), /***/ 40978: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Shell = void 0; const jsonInstruction_1 = __webpack_require__(24990); class Shell extends jsonInstruction_1.JSONInstruction { constructor(document, range, dockerfile, escapeChar, instruction, instructionRange) { super(document, range, dockerfile, escapeChar, instruction, instructionRange); } } exports.Shell = Shell; /***/ }), /***/ 62885: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Stopsignal = void 0; const instruction_1 = __webpack_require__(99311); class Stopsignal extends instruction_1.Instruction { constructor(document, range, dockerfile, escapeChar, instruction, instructionRange) { super(document, range, dockerfile, escapeChar, instruction, instructionRange); } } exports.Stopsignal = Stopsignal; /***/ }), /***/ 87372: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.User = void 0; const instruction_1 = __webpack_require__(99311); class User extends instruction_1.Instruction { constructor(document, range, dockerfile, escapeChar, instruction, instructionRange) { super(document, range, dockerfile, escapeChar, instruction, instructionRange); } } exports.User = User; /***/ }), /***/ 3951: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Volume = void 0; const jsonInstruction_1 = __webpack_require__(24990); class Volume extends jsonInstruction_1.JSONInstruction { constructor(document, range, dockerfile, escapeChar, instruction, instructionRange) { super(document, range, dockerfile, escapeChar, instruction, instructionRange); } } exports.Volume = Volume; /***/ }), /***/ 99377: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Workdir = void 0; const instruction_1 = __webpack_require__(99311); class Workdir extends instruction_1.Instruction { constructor(document, range, dockerfile, escapeChar, instruction, instructionRange) { super(document, range, dockerfile, escapeChar, instruction, instructionRange); } /** * Returns the path that has been defined. Note that this path may * be absolute or relative depending on what was written in the * instruction. * * @return the working directory's path, or null if this * instruction has no arguments */ getPath() { return this.getArgumentsContent(); } /** * Returns the absolute path that this instruction resolves to. The * function will inspect prior WORKDIR instructions in the current * image or another build stage in the Dockerfile to try to * determine this. * * @return the absolute path of the working directory, or null if * this instruction has no arguments, or undefined if it * cannot be determined because only relative paths could be * found */ getAbsolutePath() { const path = this.getPath(); if (path === null || path.startsWith("/")) { return path; } const startLine = this.getRange().start.line; const hierarchy = this.dockerfile.getStageHierarchy(startLine); for (let i = hierarchy.length - 1; i >= 0; i--) { const workdirs = hierarchy[i].getWORKDIRs(); for (let j = workdirs.length - 1; j >= 0; j--) { if (workdirs[j].getRange().start.line < startLine) { const parent = workdirs[j].getAbsolutePath(); if (parent === undefined || parent === null) { return undefined; } return parent.endsWith("/") ? parent + path : parent + "/" + path; } } } return undefined; } } exports.Workdir = Workdir; /***/ }), /***/ 24703: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JSONArgument = void 0; const argument_1 = __webpack_require__(12447); class JSONArgument extends argument_1.Argument { constructor(value, range, jsonRange) { super(value, range); this.jsonRange = jsonRange; } getJSONRange() { return this.jsonRange; } getJSONValue() { let value = super.getValue(); value = value.substring(1, value.length - 1); return value; } } exports.JSONArgument = JSONArgument; /***/ }), /***/ 24990: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JSONInstruction = void 0; const vscode_languageserver_types_1 = __webpack_require__(8089); const argument_1 = __webpack_require__(12447); const jsonArgument_1 = __webpack_require__(24703); const modifiableInstruction_1 = __webpack_require__(78514); class JSONInstruction extends modifiableInstruction_1.ModifiableInstruction { constructor(document, range, dockerfile, escapeChar, instruction, instructionRange) { super(document, range, dockerfile, escapeChar, instruction, instructionRange); this.openingBracket = null; this.closingBracket = null; this.jsonStrings = []; const argsContent = this.getRawArgumentsContent(); if (argsContent === null) { return; } const args = this.getArguments(); if (args.length === 1 && args[0].getValue() === "[]") { let argRange = args[0].getRange(); this.openingBracket = new argument_1.Argument("[", vscode_languageserver_types_1.Range.create(argRange.start.line, argRange.start.character, argRange.start.line, argRange.start.character + 1)); this.closingBracket = new argument_1.Argument("]", vscode_languageserver_types_1.Range.create(argRange.start.line, argRange.start.character + 1, argRange.end.line, argRange.end.character)); return; } else if (args.length === 2 && args[0].getValue() === '[' && args[1].getValue() === ']') { this.openingBracket = args[0]; this.closingBracket = args[1]; return; } const argsOffset = document.offsetAt(this.getArgumentsRange().start); let start = -1; let last = ""; let quoted = false; let escapedArg = ""; argsCheck: for (let i = 0; i < argsContent.length; i++) { let char = argsContent.charAt(i); switch (char) { case '[': if (last === "") { this.openingBracket = new argument_1.Argument("[", vscode_languageserver_types_1.Range.create(document.positionAt(argsOffset + i), document.positionAt(argsOffset + i + 1))); last = '['; } else if (quoted) { escapedArg = escapedArg + char; } else { break argsCheck; } break; case '"': if (last === '[' || last === ',') { start = i; quoted = true; last = '"'; escapedArg = escapedArg + char; continue; } else if (last === '"') { if (quoted) { escapedArg = escapedArg + char; // quoted string done quoted = false; this.jsonStrings.push(new jsonArgument_1.JSONArgument(escapedArg, vscode_languageserver_types_1.Range.create(document.positionAt(argsOffset + start), document.positionAt(argsOffset + i + 1)), vscode_languageserver_types_1.Range.create(document.positionAt(argsOffset + start + 1), document.positionAt(argsOffset + i)))); escapedArg = ""; } else { // should be a , or a ] break argsCheck; } } else { break argsCheck; } break; case ',': if (quoted) { escapedArg = escapedArg + char; } else { if (last === '"') { last = ','; } else { break argsCheck; } } break; case ']': if (quoted) { escapedArg = escapedArg + char; } else if (last !== "") { this.closingBracket = new argument_1.Argument("]", vscode_languageserver_types_1.Range.create(document.positionAt(argsOffset + i), document.positionAt(argsOffset + i + 1))); break argsCheck; } break; case ' ': case '\t': break; case '\\': if (quoted) { switch (argsContent.charAt(i + 1)) { case '"': case '\\': escapedArg = escapedArg + argsContent.charAt(i + 1); i++; continue; case ' ': case '\t': escapeCheck: for (let j = i + 2; j < argsContent.length; j++) { switch (argsContent.charAt(j)) { case '\r': // offset one more for \r\n j++; case '\n': i = j; continue argsCheck; case ' ': case '\t': break; default: break escapeCheck; } } break; case '\r': // offset one more for \r\n i++; default: i++; continue; } } else { escapeCheck: for (let j = i + 1; j < argsContent.length; j++) { switch (argsContent.charAt(j)) { case '\r': // offset one more for \r\n j++; case '\n': i = j; continue argsCheck; case ' ': case '\t': break; default: break escapeCheck; } } } break argsCheck; default: if (!quoted) { break argsCheck; } escapedArg = escapedArg + char; break; } } } stopSearchingForFlags(_value) { return true; } getOpeningBracket() { return this.openingBracket; } getJSONStrings() { return this.jsonStrings; } getClosingBracket() { return this.closingBracket; } } exports.JSONInstruction = JSONInstruction; /***/ }), /***/ 47119: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Line = void 0; class Line { constructor(document, range) { this.document = document; this.range = range; } getRange() { return this.range; } getTextContent() { return this.document.getText().substring(this.document.offsetAt(this.range.start), this.document.offsetAt(this.range.end)); } isAfter(line) { return this.range.start.line > line.range.start.line; } isBefore(line) { return this.range.start.line < line; } } exports.Line = Line; /***/ }), /***/ 20871: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DockerfileParser = exports.DefaultVariables = exports.Directive = exports.Keyword = exports.Workdir = exports.Volume = exports.User = exports.Stopsignal = exports.Shell = exports.Run = exports.PropertyInstruction = exports.Onbuild = exports.ModifiableInstruction = exports.Label = exports.JSONInstruction = exports.Heredoc = exports.Healthcheck = exports.From = exports.Env = exports.Entrypoint = exports.Copy = exports.Cmd = exports.Arg = exports.Add = exports.Variable = exports.Property = exports.ParserDirective = exports.Line = exports.Instruction = exports.Flag = exports.Comment = exports.JSONArgument = exports.Argument = void 0; var argument_1 = __webpack_require__(12447); Object.defineProperty(exports, "Argument", ({ enumerable: true, get: function () { return argument_1.Argument; } })); var jsonArgument_1 = __webpack_require__(24703); Object.defineProperty(exports, "JSONArgument", ({ enumerable: true, get: function () { return jsonArgument_1.JSONArgument; } })); const comment_1 = __webpack_require__(42179); Object.defineProperty(exports, "Comment", ({ enumerable: true, get: function () { return comment_1.Comment; } })); const parser_1 = __webpack_require__(50668); var flag_1 = __webpack_require__(11170); Object.defineProperty(exports, "Flag", ({ enumerable: true, get: function () { return flag_1.Flag; } })); const instruction_1 = __webpack_require__(99311); Object.defineProperty(exports, "Instruction", ({ enumerable: true, get: function () { return instruction_1.Instruction; } })); var line_1 = __webpack_require__(47119); Object.defineProperty(exports, "Line", ({ enumerable: true, get: function () { return line_1.Line; } })); const parserDirective_1 = __webpack_require__(41745); Object.defineProperty(exports, "ParserDirective", ({ enumerable: true, get: function () { return parserDirective_1.ParserDirective; } })); var property_1 = __webpack_require__(38698); Object.defineProperty(exports, "Property", ({ enumerable: true, get: function () { return property_1.Property; } })); var variable_1 = __webpack_require__(28155); Object.defineProperty(exports, "Variable", ({ enumerable: true, get: function () { return variable_1.Variable; } })); var add_1 = __webpack_require__(46581); Object.defineProperty(exports, "Add", ({ enumerable: true, get: function () { return add_1.Add; } })); const arg_1 = __webpack_require__(60904); Object.defineProperty(exports, "Arg", ({ enumerable: true, get: function () { return arg_1.Arg; } })); const cmd_1 = __webpack_require__(85450); Object.defineProperty(exports, "Cmd", ({ enumerable: true, get: function () { return cmd_1.Cmd; } })); const copy_1 = __webpack_require__(84361); Object.defineProperty(exports, "Copy", ({ enumerable: true, get: function () { return copy_1.Copy; } })); const entrypoint_1 = __webpack_require__(75822); Object.defineProperty(exports, "Entrypoint", ({ enumerable: true, get: function () { return entrypoint_1.Entrypoint; } })); const env_1 = __webpack_require__(22474); Object.defineProperty(exports, "Env", ({ enumerable: true, get: function () { return env_1.Env; } })); const from_1 = __webpack_require__(98654); Object.defineProperty(exports, "From", ({ enumerable: true, get: function () { return from_1.From; } })); const healthcheck_1 = __webpack_require__(43355); Object.defineProperty(exports, "Healthcheck", ({ enumerable: true, get: function () { return healthcheck_1.Healthcheck; } })); var heredoc_1 = __webpack_require__(8701); Object.defineProperty(exports, "Heredoc", ({ enumerable: true, get: function () { return heredoc_1.Heredoc; } })); var jsonInstruction_1 = __webpack_require__(24990); Object.defineProperty(exports, "JSONInstruction", ({ enumerable: true, get: function () { return jsonInstruction_1.JSONInstruction; } })); var label_1 = __webpack_require__(30938); Object.defineProperty(exports, "Label", ({ enumerable: true, get: function () { return label_1.Label; } })); var modifiableInstruction_1 = __webpack_require__(78514); Object.defineProperty(exports, "ModifiableInstruction", ({ enumerable: true, get: function () { return modifiableInstruction_1.ModifiableInstruction; } })); var onbuild_1 = __webpack_require__(46319); Object.defineProperty(exports, "Onbuild", ({ enumerable: true, get: function () { return onbuild_1.Onbuild; } })); var propertyInstruction_1 = __webpack_require__(78535); Object.defineProperty(exports, "PropertyInstruction", ({ enumerable: true, get: function () { return propertyInstruction_1.PropertyInstruction; } })); var run_1 = __webpack_require__(3062); Object.defineProperty(exports, "Run", ({ enumerable: true, get: function () { return run_1.Run; } })); var shell_1 = __webpack_require__(40978); Object.defineProperty(exports, "Shell", ({ enumerable: true, get: function () { return shell_1.Shell; } })); var stopsignal_1 = __webpack_require__(62885); Object.defineProperty(exports, "Stopsignal", ({ enumerable: true, get: function () { return stopsignal_1.Stopsignal; } })); var user_1 = __webpack_require__(87372); Object.defineProperty(exports, "User", ({ enumerable: true, get: function () { return user_1.User; } })); var volume_1 = __webpack_require__(3951); Object.defineProperty(exports, "Volume", ({ enumerable: true, get: function () { return volume_1.Volume; } })); const workdir_1 = __webpack_require__(99377); Object.defineProperty(exports, "Workdir", ({ enumerable: true, get: function () { return workdir_1.Workdir; } })); var Keyword; (function (Keyword) { Keyword["ADD"] = "ADD"; Keyword["ARG"] = "ARG"; Keyword["CMD"] = "CMD"; Keyword["COPY"] = "COPY"; Keyword["ENTRYPOINT"] = "ENTRYPOINT"; Keyword["ENV"] = "ENV"; Keyword["EXPOSE"] = "EXPOSE"; Keyword["FROM"] = "FROM"; Keyword["HEALTHCHECK"] = "HEALTHCHECK"; Keyword["LABEL"] = "LABEL"; Keyword["MAINTAINER"] = "MAINTAINER"; Keyword["ONBUILD"] = "ONBUILD"; Keyword["RUN"] = "RUN"; Keyword["SHELL"] = "SHELL"; Keyword["STOPSIGNAL"] = "STOPSIGNAL"; Keyword["USER"] = "USER"; Keyword["VOLUME"] = "VOLUME"; Keyword["WORKDIR"] = "WORKDIR"; })(Keyword || (exports.Keyword = Keyword = {})); var Directive; (function (Directive) { Directive["escape"] = "escape"; Directive["syntax"] = "syntax"; })(Directive || (exports.Directive = Directive = {})); exports.DefaultVariables = [ "FTP_PROXY", "ftp_proxy", "HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "NO_PROXY", "no_proxy" ]; var DockerfileParser; (function (DockerfileParser) { function parse(content) { let parser = new parser_1.Parser(); return parser.parse(content); } DockerfileParser.parse = parse; })(DockerfileParser || (exports.DockerfileParser = DockerfileParser = {})); /***/ }), /***/ 78514: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ModifiableInstruction = void 0; const vscode_languageserver_types_1 = __webpack_require__(8089); const flag_1 = __webpack_require__(11170); const instruction_1 = __webpack_require__(99311); class ModifiableInstruction extends instruction_1.Instruction { constructor(document, range, dockerfile, escapeChar, instruction, instructionRange) { super(document, range, dockerfile, escapeChar, instruction, instructionRange); } getFlags() { if (!this.flags) { this.flags = []; for (let arg of this.getArguments()) { let value = arg.getValue(); if (this.stopSearchingForFlags(value)) { return this.flags; } else if (value.indexOf("--") === 0) { let range = arg.getRange(); let rawValue = this.document.getText().substring(this.document.offsetAt(range.start), this.document.offsetAt(range.end)); let nameIndex = value.indexOf('='); let index = rawValue.indexOf('='); let firstMatch = false; let secondMatch = false; let startIndex = -1; nameSearchLoop: for (let i = 0; i < rawValue.length; i++) { switch (rawValue.charAt(i)) { case '\\': case ' ': case '\t': case '\r': case '\n': break; case '-': if (secondMatch) { startIndex = i; break nameSearchLoop; } else if (firstMatch) { secondMatch = true; } else { firstMatch = true; } break; default: startIndex = i; break nameSearchLoop; } } let nameStart = this.document.positionAt(this.document.offsetAt(range.start) + startIndex); if (index === -1) { this.flags.push(new flag_1.Flag(this.document, range, value.substring(2), vscode_languageserver_types_1.Range.create(nameStart, range.end), null, null)); } else if (index === value.length - 1) { let nameEnd = this.document.positionAt(this.document.offsetAt(range.start) + index); this.flags.push(new flag_1.Flag(this.document, range, value.substring(2, index), vscode_languageserver_types_1.Range.create(nameStart, nameEnd), "", vscode_languageserver_types_1.Range.create(range.end, range.end))); } else { let nameEnd = this.document.positionAt(this.document.offsetAt(range.start) + index); this.flags.push(new flag_1.Flag(this.document, range, value.substring(2, nameIndex), vscode_languageserver_types_1.Range.create(nameStart, nameEnd), value.substring(nameIndex + 1), vscode_languageserver_types_1.Range.create(this.document.positionAt(this.document.offsetAt(range.start) + index + 1), range.end))); } } } } return this.flags; } getArguments() { const args = super.getArguments(); const flags = this.getFlags(); if (flags.length === 0) { return args; } for (let i = 0; i < flags.length; i++) { args.shift(); } return args; } } exports.ModifiableInstruction = ModifiableInstruction; /***/ }), /***/ 50668: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Remy Suen. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Parser = void 0; const vscode_languageserver_textdocument_1 = __webpack_require__(46613); const vscode_languageserver_types_1 = __webpack_require__(8089); const comment_1 = __webpack_require__(42179); const parserDirective_1 = __webpack_require__(41745); const instruction_1 = __webpack_require__(99311); const add_1 = __webpack_require__(46581); const arg_1 = __webpack_require__(60904); const cmd_1 = __webpack_require__(85450); const copy_1 = __webpack_require__(84361); const env_1 = __webpack_require__(22474); const entrypoint_1 = __webpack_require__(75822); const from_1 = __webpack_require__(98654); const healthcheck_1 = __webpack_require__(43355); const label_1 = __webpack_require__(30938); const onbuild_1 = __webpack_require__(46319); const run_1 = __webpack_require__(3062); const shell_1 = __webpack_require__(40978); const stopsignal_1 = __webpack_require__(62885); const workdir_1 = __webpack_require__(99377); const user_1 = __webpack_require__(87372); const volume_1 = __webpack_require__(3951); const dockerfile_1 = __webpack_require__(71513); const util_1 = __webpack_require__(98707); const main_1 = __webpack_require__(20871); class Parser { constructor() { this.escapeChar = null; } static createInstruction(document, dockerfile, escapeChar, lineRange, instruction, instructionRange) { switch (instruction.toUpperCase()) { case "ADD": return new add_1.Add(document, lineRange, dockerfile, escapeChar, instruction, instructionRange); case "ARG": return new arg_1.Arg(document, lineRange, dockerfile, escapeChar, instruction, instructionRange); case "CMD": return new cmd_1.Cmd(document, lineRange, dockerfile, escapeChar, instruction, instructionRange); case "COPY": return new copy_1.Copy(document, lineRange, dockerfile, escapeChar, instruction, instructionRange); case "ENTRYPOINT": return new entrypoint_1.Entrypoint(document, lineRange, dockerfile, escapeChar, instruction, instructionRange); case "ENV": return new env_1.Env(document, lineRange, dockerfile, escapeChar, instruction, instructionRange); case "FROM": return new from_1.From(document, lineRange, dockerfile, escapeChar, instruction, instructionRange); case "HEALTHCHECK": return new healthcheck_1.Healthcheck(document, lineRange, dockerfile, escapeChar, instruction, instructionRange); case "LABEL": return new label_1.Label(document, lineRange, dockerfile, escapeChar, instruction, instructionRange); case "ONBUILD": return new onbuild_1.Onbuild(document, lineRange, dockerfile, escapeChar, instruction, instructionRange); case "RUN": return new run_1.Run(document, lineRange, dockerfile, escapeChar, instruction, instructionRange); case "SHELL": return new shell_1.Shell(document, lineRange, dockerfile, escapeChar, instruction, instructionRange); case "STOPSIGNAL": return new stopsignal_1.Stopsignal(document, lineRange, dockerfile, escapeChar, instruction, instructionRange); case "WORKDIR": return new workdir_1.Workdir(document, lineRange, dockerfile, escapeChar, instruction, instructionRange); case "USER": return new user_1.User(document, lineRange, dockerfile, escapeChar, instruction, instructionRange); case "VOLUME": return new volume_1.Volume(document, lineRange, dockerfile, escapeChar, instruction, instructionRange); } return new instruction_1.Instruction(document, lineRange, dockerfile, escapeChar, instruction, instructionRange); } getParserDirectives(document, buffer) { // reset the escape directive in between runs const directives = []; this.escapeChar = ''; const offset = util_1.Util.isUTF8BOM(buffer.substring(0, 1)) ? 1 : 0; directiveCheck: for (let i = offset; i < buffer.length; i++) { switch (buffer.charAt(i)) { case ' ': case '\t': break; case '\r': case '\n': // blank lines stop the parsing of directives immediately break directiveCheck; case '#': let directiveStart = -1; let directiveEnd = -1; for (let j = i + 1; j < buffer.length; j++) { let char = buffer.charAt(j); switch (char) { case ' ': case '\t': if (directiveStart !== -1 && directiveEnd === -1) { directiveEnd = j; } break; case '\r': case '\n': break directiveCheck; case '=': let valueStart = -1; let valueEnd = -1; if (directiveEnd === -1) { directiveEnd = j; } // assume the line ends with the file let lineEnd = buffer.length; directiveValue: for (let k = j + 1; k < buffer.length; k++) { char = buffer.charAt(k); switch (char) { case '\r': case '\n': if (valueStart !== -1 && valueEnd === -1) { valueEnd = k; } // line break found, reset lineEnd = k; break directiveValue; case '\t': case ' ': if (valueStart !== -1 && valueEnd === -1) { valueEnd = k; } continue; default: if (valueStart === -1) { valueStart = k; } break; } } if (directiveStart === -1) { // no directive, it's a regular comment break directiveCheck; } if (valueStart === -1) { // no non-whitespace characters found, highlight all the characters then valueStart = j + 1; valueEnd = lineEnd; } else if (valueEnd === -1) { // reached EOF valueEnd = buffer.length; } const lineRange = vscode_languageserver_types_1.Range.create(document.positionAt(i), document.positionAt(lineEnd)); const nameRange = vscode_languageserver_types_1.Range.create(document.positionAt(directiveStart), document.positionAt(directiveEnd)); const valueRange = vscode_languageserver_types_1.Range.create(document.positionAt(valueStart), document.positionAt(valueEnd)); directives.push(new parserDirective_1.ParserDirective(document, lineRange, nameRange, valueRange)); directiveStart = -1; if (buffer.charAt(valueEnd) === '\r') { // skip over the \r i = valueEnd + 1; } else { i = valueEnd; } continue directiveCheck; default: if (directiveStart === -1) { directiveStart = j; } break; } } break; default: break directiveCheck; } } return directives; } parse(buffer) { this.document = vscode_languageserver_textdocument_1.TextDocument.create("", "", 0, buffer); this.buffer = buffer; let dockerfile = new dockerfile_1.Dockerfile(this.document); let directives = this.getParserDirectives(this.document, this.buffer); let offset = 0; this.escapeChar = '\\'; if (directives.length > 0) { dockerfile.setDirectives(directives); this.escapeChar = dockerfile.getEscapeCharacter(); // start parsing after the directives offset = this.document.offsetAt(vscode_languageserver_types_1.Position.create(directives.length, 0)); } else if (util_1.Util.isUTF8BOM(buffer.substring(0, 1))) { offset = 1; } for (let i = offset; i < this.buffer.length; i++) { const char = this.buffer.charAt(i); switch (char) { case ' ': case '\t': case '\r': case '\n': break; case '#': i = this.processComment(dockerfile, i); break; default: i = this.processInstruction(dockerfile, char, i); break; } } dockerfile.organizeComments(); return dockerfile; } processInstruction(dockerfile, char, start) { let instruction = char; let instructionEnd = -1; let escapedInstruction = false; instructionCheck: for (let i = start + 1; i < this.buffer.length; i++) { char = this.buffer.charAt(i); switch (char) { case this.escapeChar: escapedInstruction = true; char = this.buffer.charAt(i + 1); if (char === '\r' || char === '\n') { if (instructionEnd === -1) { instructionEnd = i; } i++; } else if (char === ' ' || char === '\t') { for (let j = i + 2; j < this.buffer.length; j++) { switch (this.buffer.charAt(j)) { case ' ': case '\t': break; case '\r': case '\n': i = j; continue instructionCheck; default: // found an argument, mark end of instruction instructionEnd = i + 1; instruction = instruction + this.escapeChar; i = j - 2; continue instructionCheck; } } // reached EOF instructionEnd = i + 1; instruction = instruction + this.escapeChar; break instructionCheck; } else { instructionEnd = i + 1; instruction = instruction + this.escapeChar; // reset and consider it as one contiguous word escapedInstruction = false; } break; case ' ': case '\t': if (escapedInstruction) { // on an escaped newline, need to search for non-whitespace escapeCheck: for (let j = i + 1; j < this.buffer.length; j++) { switch (this.buffer.charAt(j)) { case ' ': case '\t': break; case '\r': case '\n': i = j; continue instructionCheck; default: break escapeCheck; } } escapedInstruction = false; } if (instructionEnd === -1) { instructionEnd = i; } i = this.processArguments(dockerfile, instruction, instructionEnd, start, i); dockerfile.addInstruction(this.createInstruction(dockerfile, instruction, start, instructionEnd, i)); return i; case '\r': case '\n': if (escapedInstruction) { continue; } if (instructionEnd === -1) { instructionEnd = i; } dockerfile.addInstruction(this.createInstruction(dockerfile, instruction, start, i, i)); return i; case '#': if (escapedInstruction) { continue; } default: instructionEnd = i + 1; instruction = instruction + char; escapedInstruction = false; break; } } // reached EOF if (instructionEnd === -1) { instructionEnd = this.buffer.length; } dockerfile.addInstruction(this.createInstruction(dockerfile, instruction, start, instructionEnd, this.buffer.length)); return this.buffer.length; } parseHeredocName(value) { value = value.substring(2); if (value.charAt(0) === '-') { value = value.substring(1); } if (value.charAt(0) === '"' || value.charAt(0) === '\'') { return value.substring(1, value.length - 1); } return value; } processHeredocs(instruction, offset) { let keyword = instruction.getKeyword(); if (keyword === main_1.Keyword.ONBUILD) { instruction = instruction.getTriggerInstruction(); if (instruction === null) { return offset; } keyword = instruction.getKeyword(); } if (keyword !== main_1.Keyword.ADD && keyword !== main_1.Keyword.COPY && keyword !== main_1.Keyword.RUN) { return offset; } const heredocs = []; for (const arg of instruction.getArguments()) { const value = arg.getValue(); if (value.startsWith("<<") && value.length > 2) { heredocs.push(this.parseHeredocName(value)); } } if (heredocs.length > 0) { for (const heredoc of heredocs) { offset = this.parseHeredoc(heredoc, offset); } } return offset; } processArguments(dockerfile, instruction, instructionEnd, start, offset) { let escaped = false; argumentsCheck: for (let i = offset + 1; i < this.buffer.length; i++) { switch (this.buffer.charAt(i)) { case '\r': case '\n': if (escaped) { continue; } return this.processHeredocs(this.createInstruction(dockerfile, instruction, start, instructionEnd, i), i); case this.escapeChar: const next = this.buffer.charAt(i + 1); if (next === '\n' || next === '\r') { escaped = true; i++; } else if (next === ' ' || next === '\t') { for (let j = i + 2; j < this.buffer.length; j++) { switch (this.buffer.charAt(j)) { case ' ': case '\t': break; case '\r': case '\n': escaped = true; default: i = j; continue argumentsCheck; } } // reached EOF return this.buffer.length; } continue; case '#': if (escaped) { i = this.processComment(dockerfile, i); continue argumentsCheck; } break; case ' ': case '\t': break; default: if (escaped) { escaped = false; } break; } } return this.buffer.length; } processComment(dockerfile, start) { let end = this.buffer.length; commentLoop: for (let i = start + 1; i < this.buffer.length; i++) { switch (this.buffer.charAt(i)) { case '\r': case '\n': end = i; break commentLoop; } } const range = vscode_languageserver_types_1.Range.create(this.document.positionAt(start), this.document.positionAt(end)); dockerfile.addComment(new comment_1.Comment(this.document, range)); return end; } parseHeredoc(heredocName, offset) { let startWord = -1; let lineStart = true; for (let i = offset; i < this.buffer.length; i++) { switch (this.buffer.charAt(i)) { case ' ': case '\t': lineStart = false; break; case '\r': case '\n': if (startWord !== -1 && heredocName === this.buffer.substring(startWord, i)) { return i; } startWord = -1; lineStart = true; break; default: if (lineStart) { startWord = i; lineStart = false; } break; } } return this.buffer.length; } createInstruction(dockerfile, instruction, start, instructionEnd, end) { const startPosition = this.document.positionAt(start); const instructionRange = vscode_languageserver_types_1.Range.create(startPosition, this.document.positionAt(instructionEnd)); const lineRange = vscode_languageserver_types_1.Range.create(startPosition, this.document.positionAt(end)); return Parser.createInstruction(this.document, dockerfile, this.escapeChar, lineRange, instruction, instructionRange); } } exports.Parser = Parser; /***/ }), /***/ 41745: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ParserDirective = void 0; const main_1 = __webpack_require__(20871); const line_1 = __webpack_require__(47119); class ParserDirective extends line_1.Line { constructor(document, range, nameRange, valueRange) { super(document, range); this.nameRange = nameRange; this.valueRange = valueRange; } toString() { return "# " + this.getName() + '=' + this.getValue(); } getNameRange() { return this.nameRange; } getValueRange() { return this.valueRange; } getName() { return this.document.getText().substring(this.document.offsetAt(this.nameRange.start), this.document.offsetAt(this.nameRange.end)); } getValue() { return this.document.getText().substring(this.document.offsetAt(this.valueRange.start), this.document.offsetAt(this.valueRange.end)); } getDirective() { const directive = main_1.Directive[this.getName().toLowerCase()]; return directive === undefined ? null : directive; } } exports.ParserDirective = ParserDirective; /***/ }), /***/ 38698: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Property = void 0; const vscode_languageserver_types_1 = __webpack_require__(8089); const util_1 = __webpack_require__(98707); class Property { constructor(document, escapeChar, arg, arg2) { this.assignmentOperatorRange = null; this.assignmentOperator = null; this.valueRange = null; this.value = null; this.document = document; this.escapeChar = escapeChar; this.nameRange = Property.getNameRange(document, arg); let value = document.getText().substring(document.offsetAt(this.nameRange.start), document.offsetAt(this.nameRange.end)); this.name = Property.getValue(value, escapeChar); if (arg2) { this.valueRange = arg2.getRange(); value = document.getText().substring(document.offsetAt(this.valueRange.start), document.offsetAt(this.valueRange.end)); this.value = Property.getValue(value, escapeChar); this.range = vscode_languageserver_types_1.Range.create(this.nameRange.start, this.valueRange.end); } else { let argRange = arg.getRange(); if (this.nameRange.start.line === argRange.start.line && this.nameRange.start.character === argRange.start.character && this.nameRange.end.line === argRange.end.line && this.nameRange.end.character === argRange.end.character) { } else { this.valueRange = Property.getValueRange(document, arg); value = document.getText().substring(document.offsetAt(this.valueRange.start), document.offsetAt(this.valueRange.end)); this.value = Property.getValue(value, escapeChar); this.assignmentOperatorRange = vscode_languageserver_types_1.Range.create(this.nameRange.end, this.valueRange.start); this.assignmentOperator = "="; } this.range = argRange; } } getRange() { return this.range; } getName() { return this.name; } getNameRange() { return this.nameRange; } getValue() { return this.value; } getValueRange() { return this.valueRange; } /** * Retrieves the operator used for delimiting between the name and * value of this property. This will either be the "=" character * or null if a character was not used or if this property has no * value defined. */ getAssignmentOperator() { return this.assignmentOperator; } getAssignmentOperatorRange() { return this.assignmentOperatorRange; } /** * Returns the value of this property including any enclosing * single or double quotes and relevant escape characters. * Escaped newlines and its associated contiguous whitespace * characters however will not be returned as they are deemed to * be uninteresting to clients trying to return a Dockerfile. * * @return the unescaped value of this property or null if this * property has no associated value */ getUnescapedValue() { if (this.valueRange === null) { return null; } let escaped = false; let rawValue = ""; let value = this.document.getText().substring(this.document.offsetAt(this.valueRange.start), this.document.offsetAt(this.valueRange.end)); rawLoop: for (let i = 0; i < value.length; i++) { let char = value.charAt(i); switch (char) { case this.escapeChar: for (let j = i + 1; j < value.length; j++) { switch (value.charAt(j)) { case '\r': j++; case '\n': escaped = true; i = j; continue rawLoop; case ' ': case '\t': break; default: rawValue = rawValue + char; continue rawLoop; } } // this happens if there's only whitespace after the escape character rawValue = rawValue + char; break; case '\r': case '\n': break; case ' ': case '\t': if (!escaped) { rawValue = rawValue + char; } break; case '#': if (escaped) { for (let j = i + 1; j < value.length; j++) { switch (value.charAt(j)) { case '\r': j++; case '\n': i = j; continue rawLoop; } } } else { rawValue = rawValue + char; } break; default: rawValue = rawValue + char; escaped = false; break; } } return rawValue; } static getNameRange(document, arg) { let value = arg.getValue(); let index = value.indexOf('='); if (index !== -1) { let initial = value.charAt(0); let before = value.charAt(index - 1); // check if content before the equals sign are in quotes // "var"=value // 'var'=value // otherwise, just assume it's a standard definition // var=value if ((initial === '"' && before === '"') || (initial === '\'' && before === '\'') || (initial !== '"' && initial !== '\'')) { return vscode_languageserver_types_1.Range.create(arg.getRange().start, document.positionAt(document.offsetAt(arg.getRange().start) + index)); } } // no '=' found, just defined the property's name return arg.getRange(); } static getValueRange(document, arg) { return vscode_languageserver_types_1.Range.create(document.positionAt(document.offsetAt(arg.getRange().start) + arg.getValue().indexOf('=') + 1), document.positionAt(document.offsetAt(arg.getRange().end))); } /** * Returns the actual value of this key-value pair. The value will * have its escape characters removed if applicable. If the value * spans multiple lines and there are comments nested within the * lines, they too will be removed. * * @return the value that this key-value pair will actually be, may * be null if no value is defined, may be the empty string * if the value only consists of whitespace */ static getValue(value, escapeChar) { let escaped = false; const skip = util_1.Util.findLeadingNonWhitespace(value, escapeChar); if (skip !== 0 && value.charAt(skip) === '#') { // need to skip over comments escaped = true; } value = value.substring(skip); let first = value.charAt(0); let last = value.charAt(value.length - 1); let literal = first === '\'' || first === '"'; let inSingle = (first === '\'' && last === '\''); let inDouble = false; if (first === '"') { for (let i = 1; i < value.length; i++) { if (value.charAt(i) === escapeChar) { i++; } else if (value.charAt(i) === '"' && i === value.length - 1) { inDouble = true; } } } if (inSingle || inDouble) { value = value.substring(1, value.length - 1); } let commentCheck = -1; let escapedValue = ""; let start = 0; parseValue: for (let i = 0; i < value.length; i++) { let char = value.charAt(i); switch (char) { case escapeChar: if (i + 1 === value.length) { escapedValue = escapedValue + escapeChar; break parseValue; } char = value.charAt(i + 1); if (char === ' ' || char === '\t') { whitespaceCheck: for (let j = i + 2; j < value.length; j++) { let char2 = value.charAt(j); switch (char2) { case ' ': case '\t': break; case '\r': j++; case '\n': escaped = true; i = j; continue parseValue; default: if (!inDouble && !inSingle && !literal) { if (char2 === escapeChar) { // add the escaped character escapedValue = escapedValue + char; // now start parsing from the next escape character i = i + 1; } else { // the expectation is that this j = i + 2 here escapedValue = escapedValue + char + char2; i = j; } continue parseValue; } break whitespaceCheck; } } } if (inDouble) { if (char === '\r') { escaped = true; i = i + 2; } else if (char === '\n') { escaped = true; i++; } else if (char !== '"') { if (char === escapeChar) { i++; } escapedValue = escapedValue + escapeChar; } continue parseValue; } else if (inSingle || literal) { if (char === '\r') { escaped = true; i = i + 2; } else if (char === '\n') { escaped = true; i++; } else { escapedValue = escapedValue + escapeChar; } continue parseValue; } else if (char === escapeChar) { // double escape, append one and move on escapedValue = escapedValue + escapeChar; i++; } else if (char === '\r') { escaped = true; // offset one more for \r\n i = i + 2; } else if (char === '\n') { escaped = true; i++; start = i; } else { // any other escapes are simply ignored escapedValue = escapedValue + char; i++; } break; case ' ': case '\t': if (escaped && commentCheck === -1) { commentCheck = i; } escapedValue = escapedValue + char; break; case '\r': i++; case '\n': if (escaped && commentCheck !== -1) { // rollback and remove the whitespace that was previously appended escapedValue = escapedValue.substring(0, escapedValue.length - (i - commentCheck - 1)); commentCheck = -1; } break; case '#': // a newline was escaped and now there's a comment if (escaped) { if (commentCheck !== -1) { // rollback and remove the whitespace that was previously appended escapedValue = escapedValue.substring(0, escapedValue.length - (i - commentCheck)); commentCheck = -1; } newlineCheck: for (let j = i + 1; j < value.length; j++) { switch (value.charAt(j)) { case '\r': j++; case '\n': i = j; break newlineCheck; } } continue parseValue; } default: if (escaped) { escaped = false; commentCheck = -1; } escapedValue = escapedValue + char; break; } } return escapedValue; } } exports.Property = Property; /***/ }), /***/ 78535: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PropertyInstruction = void 0; const vscode_languageserver_types_1 = __webpack_require__(8089); const instruction_1 = __webpack_require__(99311); const property_1 = __webpack_require__(38698); const argument_1 = __webpack_require__(12447); const util_1 = __webpack_require__(98707); class PropertyInstruction extends instruction_1.Instruction { constructor(document, range, dockerfile, escapeChar, instruction, instructionRange) { super(document, range, dockerfile, escapeChar, instruction, instructionRange); this.properties = undefined; } getProperties() { if (this.properties === undefined) { let args = this.getPropertyArguments(); if (args.length === 0) { this.properties = []; } else if (args.length === 1) { this.properties = [new property_1.Property(this.document, this.escapeChar, args[0])]; } else if (args.length === 2) { if (args[0].getValue().indexOf('=') === -1) { this.properties = [new property_1.Property(this.document, this.escapeChar, args[0], args[1])]; } else { this.properties = [ new property_1.Property(this.document, this.escapeChar, args[0]), new property_1.Property(this.document, this.escapeChar, args[1]) ]; } } else if (args[0].getValue().indexOf('=') === -1) { let text = this.document.getText(); let start = args[1].getRange().start; let end = args[args.length - 1].getRange().end; text = text.substring(this.document.offsetAt(start), this.document.offsetAt(end)); this.properties = [new property_1.Property(this.document, this.escapeChar, args[0], new argument_1.Argument(text, vscode_languageserver_types_1.Range.create(args[1].getRange().start, args[args.length - 1].getRange().end)))]; } else { this.properties = []; for (let i = 0; i < args.length; i++) { this.properties.push(new property_1.Property(this.document, this.escapeChar, args[i])); } } } return this.properties; } /** * Goes from the back of the string and returns the first * non-whitespace character that is found. If an escape character * is found with newline characters, the escape character will * not be considered a non-whitespace character and its index in * the string will not be returned. * * @param content the string to search through * @return the index in the string for the first non-whitespace * character when searching from the end of the string */ findTrailingNonWhitespace(content) { // loop back to find the first non-whitespace character let index = content.length; whitespaceCheck: for (let i = content.length - 1; i >= 0; i--) { switch (content.charAt(i)) { case ' ': case '\t': continue; case '\n': if (content.charAt(i - 1) === '\r') { i = i - 1; } case '\r': newlineCheck: for (let j = i - 1; j >= 0; j--) { switch (content.charAt(j)) { case ' ': case '\t': case '\r': case '\n': case this.escapeChar: continue; default: index = j; break newlineCheck; } } break whitespaceCheck; default: index = i; break whitespaceCheck; } } return index; } getPropertyArguments() { const args = []; let range = this.getInstructionRange(); let instructionNameEndOffset = this.document.offsetAt(range.end); let extra = instructionNameEndOffset - this.document.offsetAt(range.start); let content = this.getTextContent(); let fullArgs = content.substring(extra); let start = util_1.Util.findLeadingNonWhitespace(fullArgs, this.escapeChar); if (start === -1) { // only whitespace found, no arguments return []; } const startPosition = this.document.positionAt(instructionNameEndOffset + start); // records whether the parser has just processed an escaped newline or not, // if our starting position is not on the same line as the instruction then // the start of the content is already on an escaped line let escaped = range.start.line !== startPosition.line; // flag to track if the last character was an escape character let endingEscape = false; // position before the first escape character was hit let mark = -1; let end = this.findTrailingNonWhitespace(fullArgs); content = fullArgs.substring(start, end + 1); let argStart = escaped ? -1 : 0; let spaced = false; argumentLoop: for (let i = 0; i < content.length; i++) { let char = content.charAt(i); switch (char) { case this.escapeChar: if (i + 1 === content.length) { endingEscape = true; break argumentLoop; } if (!escaped) { mark = i; } switch (content.charAt(i + 1)) { case ' ': case '\t': if (!util_1.Util.isWhitespace(content.charAt(i + 2))) { // space was escaped, continue as normal i = i + 1; continue argumentLoop; } // whitespace encountered, need to figure out if it extends to EOL whitespaceCheck: for (let j = i + 2; j < content.length; j++) { switch (content.charAt(j)) { case '\r': // offset one more for \r\n j++; case '\n': // whitespace only, safe to skip escaped = true; i = j; continue argumentLoop; case ' ': case '\t': // ignore whitespace break; default: // whitespace doesn't extend to EOL, create an argument args.push(new argument_1.Argument(content.substring(argStart, i), vscode_languageserver_types_1.Range.create(this.document.positionAt(instructionNameEndOffset + start + argStart), this.document.positionAt(instructionNameEndOffset + start + i + 2)))); argStart = j; break whitespaceCheck; } } // go back and start processing the encountered non-whitespace character i = argStart - 1; continue argumentLoop; case '\r': // offset one more for \r\n i++; case '\n': // immediately followed by a newline, skip the newline escaped = true; i = i + 1; continue argumentLoop; case this.escapeChar: // double escape found, skip it and move on if (argStart === -1) { argStart = i; } i = i + 1; continue argumentLoop; default: if (argStart === -1) { argStart = i; } // non-whitespace encountered, skip the escape and process the // character normally continue argumentLoop; } case '\'': case '"': if (spaced) { this.createSpacedArgument(argStart, args, content, mark, instructionNameEndOffset, start); // reset to start a new argument argStart = i; spaced = false; } if (argStart === -1) { argStart = i; } for (let j = i + 1; j < content.length; j++) { switch (content.charAt(j)) { case char: if (content.charAt(j + 1) !== ' ' && content.charAt(j + 1) !== '') { // there is more content after this quote, // continue so that it is all processed as // one single argument i = j; continue argumentLoop; } args.push(new argument_1.Argument(content.substring(argStart, j + 1), vscode_languageserver_types_1.Range.create(this.document.positionAt(instructionNameEndOffset + start + argStart), this.document.positionAt(instructionNameEndOffset + start + j + 1)))); i = j; argStart = -1; continue argumentLoop; case this.escapeChar: j++; break; } } break argumentLoop; case ' ': case '\t': if (escaped) { // consider there to be a space only if an argument // is not spanning multiple lines if (argStart !== -1) { spaced = true; } } else if (argStart !== -1) { args.push(new argument_1.Argument(content.substring(argStart, i), vscode_languageserver_types_1.Range.create(this.document.positionAt(instructionNameEndOffset + start + argStart), this.document.positionAt(instructionNameEndOffset + start + i)))); argStart = -1; } break; case '\r': // offset one more for \r\n i++; case '\n': spaced = false; break; case '#': if (escaped) { // a newline was escaped and now there's a comment for (let j = i + 1; j < content.length; j++) { switch (content.charAt(j)) { case '\r': j++; case '\n': i = j; spaced = false; continue argumentLoop; } } // went to the end without finding a newline, // the comment was the last line in the instruction, // just stop parsing, create an argument if needed if (argStart !== -1) { let value = content.substring(argStart, mark); args.push(new argument_1.Argument(value, vscode_languageserver_types_1.Range.create(this.document.positionAt(instructionNameEndOffset + start + argStart), this.document.positionAt(instructionNameEndOffset + start + mark)))); argStart = -1; } break argumentLoop; } else if (argStart === -1) { argStart = i; } break; default: if (spaced) { this.createSpacedArgument(argStart, args, content, mark, instructionNameEndOffset, start); // reset to start a new argument argStart = i; spaced = false; } escaped = false; if (argStart === -1) { argStart = i; } // variable detected if (char === '$' && content.charAt(i + 1) === '{') { let singleQuotes = false; let doubleQuotes = false; let escaped = false; for (let j = i + 1; j < content.length; j++) { switch (content.charAt(j)) { case this.escapeChar: escaped = true; break; case '\r': case '\n': break; case '\'': singleQuotes = !singleQuotes; escaped = false; break; case '"': doubleQuotes = !doubleQuotes; escaped = false; break; case ' ': case '\t': if (escaped || singleQuotes || doubleQuotes) { break; } i = j - 1; continue argumentLoop; case '}': i = j; continue argumentLoop; default: escaped = false; break; } } break argumentLoop; } break; } } if (argStart !== -1 && argStart !== content.length) { let end = endingEscape ? content.length - 1 : content.length; let value = content.substring(argStart, end); args.push(new argument_1.Argument(value, vscode_languageserver_types_1.Range.create(this.document.positionAt(instructionNameEndOffset + start + argStart), this.document.positionAt(instructionNameEndOffset + start + end)))); } return args; } createSpacedArgument(argStart, args, content, mark, instructionNameEndOffset, start) { if (argStart !== -1) { args.push(new argument_1.Argument(content.substring(argStart, mark), vscode_languageserver_types_1.Range.create(this.document.positionAt(instructionNameEndOffset + start + argStart), this.document.positionAt(instructionNameEndOffset + start + mark)))); } } } exports.PropertyInstruction = PropertyInstruction; /***/ }), /***/ 98707: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Remy Suen. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Util = void 0; class Util { static isUTF8BOM(char) { const uintArray = Uint8Array.from(Buffer.from(char, "UTF-8")); return uintArray[0] === 0xEF && uintArray[1] == 0xBB && uintArray[2] == 0xBF; } static isWhitespace(char) { return char === ' ' || char === '\t' || Util.isNewline(char); } static isNewline(char) { return char === '\r' || char === '\n'; } static findLeadingNonWhitespace(content, escapeChar) { whitespaceCheck: for (let i = 0; i < content.length; i++) { switch (content.charAt(i)) { case ' ': case '\t': continue; case escapeChar: escapeCheck: for (let j = i + 1; j < content.length; j++) { switch (content.charAt(j)) { case ' ': case '\t': continue; case '\r': // offset one more for \r\n i = j + 1; continue whitespaceCheck; case '\n': i = j; continue whitespaceCheck; default: break escapeCheck; } } // found an escape character and then reached EOF return -1; default: return i; } } // only possible if the content is the empty string return -1; } /** * Determines if the given position is contained within the given range. * * @param position the position to check * @param range the range to see if the position is inside of */ static isInsideRange(position, range) { if (range.start.line === range.end.line) { return range.start.line === position.line && range.start.character <= position.character && position.character <= range.end.character; } else if (range.start.line === position.line) { return range.start.character <= position.character; } else if (range.end.line === position.line) { return position.character <= range.end.character; } return range.start.line < position.line && position.line < range.end.line; } } exports.Util = Util; /***/ }), /***/ 28155: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Variable = void 0; class Variable { constructor(name, nameRange, range, modifier, modifierRange, substitutionParameter, substitutionRange, defined, buildVariable, stringValue) { this.name = name; this.nameRange = nameRange; this.range = range; this.modifier = modifier; this.modifierRange = modifierRange; this.substitutionParameter = substitutionParameter; this.substitutionRange = substitutionRange; this.defined = defined; this.buildVariable = buildVariable; this.stringValue = stringValue; } toString() { return this.stringValue; } getName() { return this.name; } getNameRange() { return this.nameRange; } /** * Returns the range of the entire variable. This includes the symbols for * the declaration of the variable such as the $, {, and } symbols. * * @return the range in the document that this variable encompasses in its * entirety */ getRange() { return this.range; } /** * Returns the modifier character that has been set for * specifying how this variable should be expanded and resolved. * If this variable is ${variable:+value} then the modifier * character is '+'. Will be the empty string if the variable is * declared as ${variable:}. Otherwise, will be null if this * variable will not use variable substitution at all (such as * ${variable} or $variable). * * @return this variable's modifier character, or the empty * string if it does not have one, or null if this * variable will not use variable substitution */ getModifier() { return this.modifier; } getModifierRange() { return this.modifierRange; } /** * Returns the parameter that will be used for substitution if * this variable uses modifiers to define how its value should be * resolved. If this variable is ${variable:+value} then the * substitution value will be 'value'. Will be the empty string * if the variable is declared as ${variable:+} or some other * variant where the only thing that follows the modifier * character (excluding considerations of escape characters and * so on) is the variable's closing bracket. May be null if this * variable does not have a modifier character defined (such as * ${variable} or $variable). * * @return this variable's substitution parameter, or the empty * string if it does not have one, or null if there is * not one defined */ getSubstitutionParameter() { return this.substitutionParameter; } getSubstitutionRange() { return this.substitutionRange; } /** * Returns whether this variable has been defined or not. * * @return true if this variable has been defined, false otherwise */ isDefined() { return this.defined; } isBuildVariable() { return this.buildVariable === true; } isEnvironmentVariable() { return this.buildVariable === false; } } exports.Variable = Variable; /***/ }), /***/ 91885: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DepType = exports.isSupportedByV2GraphGeneration = exports.extractProps = exports.extractTargetSdkFromGlobalJson = exports.extractTargetFrameworksFromProjectAssetsJson = exports.extractTargetFrameworksFromProjectJson = exports.extractTargetFrameworksFromProjectConfig = exports.extractTargetFrameworksFromProjectFile = exports.extractTargetFrameworksFromFiles = exports.containsPackageReference = exports.buildDepTreeFromFiles = exports.buildDepTreeFromProjectAssetsJson = exports.buildDepTreeFromProjectJson = exports.buildDepTreeFromProjectFile = exports.buildDepTreeFromPackagesConfig = void 0; __webpack_require__(20406); const fs = __webpack_require__(57147); const path = __webpack_require__(71017); const error_catalog_nodejs_public_1 = __webpack_require__(46171); const parsers_1 = __webpack_require__(68963); Object.defineProperty(exports, "DepType", ({ enumerable: true, get: function () { return parsers_1.DepType; } })); const project_assets_json_parser_1 = __webpack_require__(41039); const PROJ_FILE_EXTENSIONS = ['.csproj', '.vbproj', '.fsproj']; function buildDepTreeFromProjectJson(manifestFileContents, includeDev = false) { // trimming required to address files with UTF-8 with BOM encoding const manifestFile = JSON.parse(manifestFileContents.trim()); return (0, parsers_1.getDependencyTreeFromProjectJson)(manifestFile, includeDev); } exports.buildDepTreeFromProjectJson = buildDepTreeFromProjectJson; // TODO: Figure out what to do about devDeps function buildDepTreeFromProjectAssetsJson(manifestFileContents, targetFramework) { if (!targetFramework) { throw new error_catalog_nodejs_public_1.OpenSourceEcosystems.MissingPayloadError('Missing targetFramework for project.assets.json'); } // trimming required to address files with UTF-8 with BOM encoding const manifestFile = JSON.parse(manifestFileContents.trim()); return (0, project_assets_json_parser_1.getDependencyTreeFromProjectAssetsJson)(manifestFile, targetFramework); } exports.buildDepTreeFromProjectAssetsJson = buildDepTreeFromProjectAssetsJson; async function buildDepTreeFromPackagesConfig(manifestFileContents, includeDev = false) { const manifestFile = await (0, parsers_1.parseXmlFile)(manifestFileContents); return (0, parsers_1.getDependencyTreeFromPackagesConfig)(manifestFile, includeDev); } exports.buildDepTreeFromPackagesConfig = buildDepTreeFromPackagesConfig; async function buildDepTreeFromProjectFile(manifestFileContents, includeDev = false, propsMap = {}) { const manifestFile = await (0, parsers_1.parseXmlFile)(manifestFileContents); return (0, parsers_1.getDependencyTreeFromProjectFile)(manifestFile, includeDev, propsMap); } exports.buildDepTreeFromProjectFile = buildDepTreeFromProjectFile; function buildDepTreeFromFiles(root, manifestFilePath, includeDev = false, targetFramework) { if (!root || !manifestFilePath) { throw new error_catalog_nodejs_public_1.OpenSourceEcosystems.MissingPayloadError('Missing required parameters for building dependency tree from files'); } const manifestFileFullPath = path.resolve(root, manifestFilePath); if (!fs.existsSync(manifestFileFullPath)) { throw new error_catalog_nodejs_public_1.OpenSourceEcosystems.CannotGetFileFromSourceError('No packages.config, project.json or project file found', { location: manifestFileFullPath, }); } const manifestFileContents = fs.readFileSync(manifestFileFullPath, 'utf-8'); const manifestFileExtension = path.extname(manifestFileFullPath); if (PROJ_FILE_EXTENSIONS.includes(manifestFileExtension)) { return buildDepTreeFromProjectFile(manifestFileContents, includeDev); } else if (manifestFilePath.endsWith('packages.config')) { return buildDepTreeFromPackagesConfig(manifestFileContents, includeDev); } else if (manifestFilePath.endsWith('project.json')) { return buildDepTreeFromProjectJson(manifestFileContents, includeDev); } else if (manifestFilePath.endsWith('project.assets.json')) { return buildDepTreeFromProjectAssetsJson(manifestFileContents, targetFramework); } else { throw new error_catalog_nodejs_public_1.OpenSourceEcosystems.UnsupportedManifestFileError('Unsupported file, please provide ' + 'either packages.config or project file.', { location: manifestFilePath, }); } } exports.buildDepTreeFromFiles = buildDepTreeFromFiles; // The V2 project aimed at removing virtually all of this reinvention of the wheel logic in favor of utilization of // the `dotnet` cli itself, publicly referred to as just 'V2', is done iteratively. Since this package is shared with // both internal and external packages that all make up parts of the V2 project, we add the shared logic here. // Further, at least to keep project development iterative, don't support needle and haystack'ing dependency JSON // for target frameworks other than .NET 5+ and .NET Core, as other frameworks generates vastly other types of // .json graphs, requiring a whole other parsing strategy to extract tne runtime dependencies. // For a list of version naming currently available, see // https://learn.microsoft.com/en-us/dotnet/standard/frameworks#supported-target-frameworks function isSupportedByV2GraphGeneration(targetFramework) { // Everything that does not start with 'net' is already game over. E.g. Windows Phone (wp) or silverlight (sl) etc. if (!targetFramework.startsWith('net')) { return false; } // - .NET Core: netcoreappN.N, - EOL from Microsoft if (targetFramework.startsWith('netcoreapp')) { return false; } // What's left is: // - .NET 5+ netN.N, (supported) // - .NET Standard: netstandardN.N (supported) and // - .NET Framework: netNNN (unsupported) // So if there's a dot, we're good. if (targetFramework.includes('.')) { return true; } // Otherwise it's something before .NET 5 and we're out return false; } exports.isSupportedByV2GraphGeneration = isSupportedByV2GraphGeneration; function extractTargetFrameworksFromFiles(root, manifestFilePath, includeDev = false) { if (!root || !manifestFilePath) { throw new error_catalog_nodejs_public_1.OpenSourceEcosystems.MissingPayloadError('Missing required parameters for extractTargetFrameworksFromFiles()'); } const manifestFileFullPath = path.resolve(root, manifestFilePath); if (!fs.existsSync(manifestFileFullPath)) { throw new error_catalog_nodejs_public_1.OpenSourceEcosystems.CannotGetFileFromSourceError('No project file found', { location: manifestFileFullPath, }); } const manifestFileContents = fs.readFileSync(manifestFileFullPath, 'utf-8'); const manifestFileExtension = path.extname(manifestFileFullPath); if (PROJ_FILE_EXTENSIONS.includes(manifestFileExtension)) { return extractTargetFrameworksFromProjectFile(manifestFileContents); } else if (manifestFilePath.endsWith('packages.config')) { return extractTargetFrameworksFromProjectConfig(manifestFileContents); } else if (manifestFilePath.endsWith('project.json')) { return extractTargetFrameworksFromProjectJson(manifestFileContents); } else if (manifestFilePath.endsWith('project.assets.json')) { return extractTargetFrameworksFromProjectAssetsJson(manifestFileContents); } else { throw new error_catalog_nodejs_public_1.OpenSourceEcosystems.UnsupportedManifestFileError('Unsupported file, please provide ' + 'a project *.csproj, *.vbproj, *.fsproj or packages.config file.', { location: manifestFilePath, }); } } exports.extractTargetFrameworksFromFiles = extractTargetFrameworksFromFiles; async function extractTargetFrameworksFromProjectFile(manifestFileContents) { const manifestFile = await (0, parsers_1.parseXmlFile)(manifestFileContents); return (0, parsers_1.getTargetFrameworksFromProjectFile)(manifestFile); } exports.extractTargetFrameworksFromProjectFile = extractTargetFrameworksFromProjectFile; async function extractTargetFrameworksFromProjectConfig(manifestFileContents) { const manifestFile = await (0, parsers_1.parseXmlFile)(manifestFileContents); return (0, parsers_1.getTargetFrameworksFromProjectConfig)(manifestFile); } exports.extractTargetFrameworksFromProjectConfig = extractTargetFrameworksFromProjectConfig; async function containsPackageReference(manifestFileContents) { var _a, _b; const manifestFile = await (0, parsers_1.parseXmlFile)(manifestFileContents); const projectItems = (_b = (_a = manifestFile === null || manifestFile === void 0 ? void 0 : manifestFile.Project) === null || _a === void 0 ? void 0 : _a.ItemGroup) !== null && _b !== void 0 ? _b : []; const referenceIndex = projectItems.findIndex((itemGroup) => typeof itemGroup === 'object' && 'PackageReference' in itemGroup); return referenceIndex !== -1; } exports.containsPackageReference = containsPackageReference; async function extractTargetFrameworksFromProjectJson(manifestFileContents) { let manifestFile; try { // trimming required to address files with UTF-8 with BOM encoding manifestFile = JSON.parse(manifestFileContents.trim()); } catch (err) { throw new error_catalog_nodejs_public_1.OpenSourceEcosystems.UnparseableManifestError('Failed to parse manifest file'); } return (0, parsers_1.getTargetFrameworksFromProjectJson)(manifestFile); } exports.extractTargetFrameworksFromProjectJson = extractTargetFrameworksFromProjectJson; async function extractTargetFrameworksFromProjectAssetsJson(manifestFileContents) { let manifestFile; try { // trimming required to address files with UTF-8 with BOM encoding manifestFile = JSON.parse(manifestFileContents.trim()); } catch (err) { throw new error_catalog_nodejs_public_1.OpenSourceEcosystems.UnparseableManifestError('Failed to parse manifest file'); } return (0, parsers_1.getTargetFrameworksFromProjectAssetsJson)(manifestFile); } exports.extractTargetFrameworksFromProjectAssetsJson = extractTargetFrameworksFromProjectAssetsJson; function extractTargetSdkFromGlobalJson(manifestFileContents) { var _a; try { // Remove /* */ comments from the JSON string (if any) // It's allowed: https://learn.microsoft.com/en-us/dotnet/core/tools/global-json#comments-in-globaljson const jsonWithoutComments = manifestFileContents.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, ''); const globalJsonAsObj = JSON.parse(jsonWithoutComments); return (_a = globalJsonAsObj === null || globalJsonAsObj === void 0 ? void 0 : globalJsonAsObj.sdk) === null || _a === void 0 ? void 0 : _a.version; } catch (err) { throw new Error(`Extracting target framework failed with error ${err.message}`); } } exports.extractTargetSdkFromGlobalJson = extractTargetSdkFromGlobalJson; async function extractProps(propsFileContents) { const propsFile = await (0, parsers_1.parseXmlFile)(propsFileContents); if (!propsFile) { throw new error_catalog_nodejs_public_1.OpenSourceEcosystems.MissingPayloadError('Empty xml file'); } return (0, parsers_1.getPropertiesMap)(propsFile); } exports.extractProps = extractProps; //# sourceMappingURL=index.js.map /***/ }), /***/ 68963: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getTargetFrameworksFromProjectAssetsJson = exports.getTargetFrameworksFromProjectJson = exports.getTargetFrameworksFromProjectConfig = exports.getTargetFrameworksFromProjectFile = exports.getPropertiesMap = exports.parseXmlFile = exports.getDependenciesFromPackageReference = exports.getDependencyTreeFromProjectFile = exports.getDependencyTreeFromPackagesConfig = exports.getDependencyTreeFromProjectJson = exports.ProjectJsonDepType = exports.DepType = void 0; const parseXML = __webpack_require__(5055); const lodash_1 = __webpack_require__(96486); const error_catalog_nodejs_public_1 = __webpack_require__(46171); var DepType; (function (DepType) { DepType["prod"] = "prod"; DepType["dev"] = "dev"; })(DepType || (exports.DepType = DepType = {})); var ProjectJsonDepType; (function (ProjectJsonDepType) { ProjectJsonDepType["build"] = "build"; ProjectJsonDepType["project"] = "project"; ProjectJsonDepType["platform"] = "platform"; ProjectJsonDepType["default"] = "default"; })(ProjectJsonDepType || (exports.ProjectJsonDepType = ProjectJsonDepType = {})); function getDependencyTreeFromProjectJson(manifestFile, includeDev = false) { const depTree = { dependencies: {}, hasDevDependencies: false, name: '', version: '', }; for (const depName in manifestFile.dependencies) { if (!manifestFile.dependencies.hasOwnProperty(depName)) { continue; } const depValue = manifestFile.dependencies[depName]; const version = depValue.version || depValue; const isDev = depValue.type === 'build'; depTree.hasDevDependencies = depTree.hasDevDependencies || isDev; if (isDev && !includeDev) { continue; } depTree.dependencies[depName] = buildSubTreeFromProjectJson(depName, version, isDev); } return depTree; } exports.getDependencyTreeFromProjectJson = getDependencyTreeFromProjectJson; function buildSubTreeFromProjectJson(name, version, isDev) { const depSubTree = { depType: isDev ? DepType.dev : DepType.prod, dependencies: {}, name, version, }; return depSubTree; } async function getDependencyTreeFromPackagesConfig(manifestFile, includeDev = false) { var _a, _b; const depTree = { dependencies: {}, hasDevDependencies: false, name: '', version: '', }; const packageList = (_b = (_a = manifestFile === null || manifestFile === void 0 ? void 0 : manifestFile.packages) === null || _a === void 0 ? void 0 : _a.package) !== null && _b !== void 0 ? _b : []; for (const dep of packageList) { const depName = dep.$.id; const isDev = !!dep.$.developmentDependency; depTree.hasDevDependencies = depTree.hasDevDependencies || isDev; if (isDev && !includeDev) { continue; } depTree.dependencies[depName] = buildSubTreeFromPackagesConfig(dep, isDev); } return depTree; } exports.getDependencyTreeFromPackagesConfig = getDependencyTreeFromPackagesConfig; function buildSubTreeFromPackagesConfig(dep, isDev) { const depSubTree = { depType: isDev ? DepType.dev : DepType.prod, dependencies: {}, name: dep.$.id, version: dep.$.version, }; if (dep.$.targetFramework) { depSubTree.targetFrameworks = [dep.$.targetFramework]; } return depSubTree; } async function getDependencyTreeFromProjectFile(manifestFile, includeDev = false, propsMap = {}) { var _a, _b, _c, _d; const nameProperty = ((_b = (_a = manifestFile === null || manifestFile === void 0 ? void 0 : manifestFile.Project) === null || _a === void 0 ? void 0 : _a.PropertyGroup) !== null && _b !== void 0 ? _b : []) .filter((propertyGroup) => typeof propertyGroup !== 'string') .find((propertyGroup) => { return 'PackageId' in propertyGroup || 'AssemblyName' in propertyGroup; }) || {}; const name = ((_c = nameProperty.PackageId) === null || _c === void 0 ? void 0 : _c[0]) || ((_d = nameProperty.AssemblyName) === null || _d === void 0 ? void 0 : _d[0]) || ''; const packageReferenceDeps = await getDependenciesFromPackageReference(manifestFile, includeDev, propsMap); // order matters, the order deps are parsed in needs to be preserved and first seen kept // so applying the packageReferenceDeps last to override the second parsed const depTree = { dependencies: Object.assign({}, packageReferenceDeps.dependencies), hasDevDependencies: packageReferenceDeps.hasDevDependencies, name, version: '', }; if (packageReferenceDeps.dependenciesWithUnknownVersions) { depTree.dependenciesWithUnknownVersions = packageReferenceDeps.dependenciesWithUnknownVersions; } return depTree; } exports.getDependencyTreeFromProjectFile = getDependencyTreeFromProjectFile; async function getDependenciesFromPackageReference(manifestFile, includeDev = false, propsMap) { var _a, _b; let dependenciesResult = { dependencies: {}, hasDevDependencies: false, }; const packageGroups = ((_b = (_a = manifestFile === null || manifestFile === void 0 ? void 0 : manifestFile.Project) === null || _a === void 0 ? void 0 : _a.ItemGroup) !== null && _b !== void 0 ? _b : []).filter((itemGroup) => typeof itemGroup === 'object' && 'PackageReference' in itemGroup); if (!packageGroups.length) { return dependenciesResult; } for (const packageList of packageGroups) { dependenciesResult = processItemGroupForPackageReference(packageList, manifestFile, includeDev, dependenciesResult, propsMap); } return dependenciesResult; } exports.getDependenciesFromPackageReference = getDependenciesFromPackageReference; function processItemGroupForPackageReference(packageList, manifestFile, includeDev, dependenciesResult, propsMap) { var _a, _b; const targetFrameworks = ((_b = (_a = packageList === null || packageList === void 0 ? void 0 : packageList.$) === null || _a === void 0 ? void 0 : _a.Condition) !== null && _b !== void 0 ? _b : false) ? getConditionalFrameworks(packageList.$.Condition) : []; for (const dep of packageList.PackageReference) { const depName = dep.$.Include; if (!depName) { // PackageReference Update is not yet supported continue; } const isDev = !!dep.$.developmentDependency; dependenciesResult.hasDevDependencies = dependenciesResult.hasDevDependencies || isDev; if (isDev && !includeDev) { continue; } const subDep = buildSubTreeFromPackageReference(dep, isDev, manifestFile, targetFrameworks, propsMap); if (subDep.withoutVersion) { dependenciesResult.dependenciesWithUnknownVersions = dependenciesResult.dependenciesWithUnknownVersions || []; dependenciesResult.dependenciesWithUnknownVersions.push(subDep.name); } else { dependenciesResult.dependencies[depName] = subDep; } } return dependenciesResult; } function buildSubTreeFromPackageReference(dep, isDev, manifestFile, targetFrameworks, propsMap) { const version = extractDependencyVersion(dep, manifestFile, propsMap) || ''; if (!(0, lodash_1.isEmpty)(version)) { const depSubTree = { depType: isDev ? DepType.dev : DepType.prod, dependencies: {}, name: dep.$.Include, // Version could be in attributes or as child node. version, }; if (targetFrameworks.length) { depSubTree.targetFrameworks = targetFrameworks; } return depSubTree; } else { return { name: dep.$.Include, withoutVersion: true }; } } function extractDependencyVersion(dep, manifestFile, propsMap) { var _a, _b; const VARS_MATCHER = /^\$\((.*?)\)/; let version = ((_a = dep === null || dep === void 0 ? void 0 : dep.$) === null || _a === void 0 ? void 0 : _a.Version) || (dep === null || dep === void 0 ? void 0 : dep.Version); if (Array.isArray(version)) { version = version[0]; } const variableVersion = version && version.match(VARS_MATCHER); if (!variableVersion) { return version; } // version is a variable, extract it from manifest or props lookup const propertyName = variableVersion[1]; const propertyMap = Object.assign(Object.assign({}, propsMap), getPropertiesMap(manifestFile)); return (_b = propertyMap === null || propertyMap === void 0 ? void 0 : propertyMap[propertyName]) !== null && _b !== void 0 ? _b : null; } function getConditionalFrameworks(condition) { const regexp = /\(TargetFramework\)'\s?==\s? '((\w|\d|\.)*)'/g; const frameworks = []; let match = regexp.exec(condition); while (match !== null) { frameworks.push(match[1]); match = regexp.exec(condition); } return frameworks; } async function parseXmlFile(manifestFileContents) { return new Promise((resolve, reject) => { parseXML.parseString(manifestFileContents, (err, result) => { if (err) { const e = new error_catalog_nodejs_public_1.OpenSourceEcosystems.UnparseableManifestError('Manifest xml file parsing failed'); return reject(e); } return resolve(result); }); }); } exports.parseXmlFile = parseXmlFile; function getPropertiesMap(propsContents) { var _a, _b; const projectPropertyGroup = (_b = (_a = propsContents === null || propsContents === void 0 ? void 0 : propsContents.Project) === null || _a === void 0 ? void 0 : _a.PropertyGroup) !== null && _b !== void 0 ? _b : []; const props = {}; if (!projectPropertyGroup.length) { return props; } for (const group of projectPropertyGroup) { for (const key of Object.keys(group)) { (0, lodash_1.set)(props, key, group[key][0]); } } return props; } exports.getPropertiesMap = getPropertiesMap; function getTargetFrameworksFromProjectFile(manifestFile) { var _a, _b; let targetFrameworksResult = []; const projectPropertyGroup = (_b = (_a = manifestFile === null || manifestFile === void 0 ? void 0 : manifestFile.Project) === null || _a === void 0 ? void 0 : _a.PropertyGroup) !== null && _b !== void 0 ? _b : []; if (!projectPropertyGroup) { return targetFrameworksResult; } const propertyList = projectPropertyGroup.find((propertyGroup) => { return ('TargetFramework' in propertyGroup || 'TargetFrameworks' in propertyGroup || 'TargetFrameworkVersion' in propertyGroup); }) || {}; if ((0, lodash_1.isEmpty)(propertyList)) { return targetFrameworksResult; } // TargetFrameworks is expected to be a list ; separated if (propertyList.TargetFrameworks) { for (const item of propertyList.TargetFrameworks) { targetFrameworksResult = [ ...targetFrameworksResult, ...getTargetFrameworks(item), ]; } } // TargetFrameworkVersion is expected to be a string containing only one item // TargetFrameworkVersion also implies .NETFramework, for convenience // return longer version if (propertyList.TargetFrameworkVersion) { targetFrameworksResult.push(`.NETFramework,Version=${propertyList.TargetFrameworkVersion[0]}`); } // TargetFrameworks is expected to be a string if (propertyList.TargetFramework) { // sanity check if (Array.isArray(propertyList.TargetFramework)) { // mutate the array to effectively "ignore" conditions propertyList.TargetFramework = propertyList.TargetFramework.map((framework) => { if (framework && typeof framework === 'object' && Object.hasOwnProperty.call(framework, '_')) { return framework._; } return framework; }); } targetFrameworksResult = [ ...targetFrameworksResult, ...propertyList.TargetFramework, ]; } return (0, lodash_1.uniq)(targetFrameworksResult); } exports.getTargetFrameworksFromProjectFile = getTargetFrameworksFromProjectFile; function getTargetFrameworks(item) { if (typeof item === 'object' && Object.hasOwnProperty.call(item, '_')) { item = item._; } return item.split(';').filter((x) => !(0, lodash_1.isEmpty)(x)); } function getTargetFrameworksFromProjectConfig(manifestFile) { var _a, _b; const targetFrameworksResult = []; const packages = (_b = (_a = manifestFile === null || manifestFile === void 0 ? void 0 : manifestFile.packages) === null || _a === void 0 ? void 0 : _a.package) !== null && _b !== void 0 ? _b : []; for (const item of packages) { const targetFramework = item.$.targetFramework; if (!targetFramework) { continue; } if (!targetFrameworksResult.includes(targetFramework)) { targetFrameworksResult.push(targetFramework); } } return targetFrameworksResult; } exports.getTargetFrameworksFromProjectConfig = getTargetFrameworksFromProjectConfig; function getTargetFrameworksFromProjectJson(manifestFile) { var _a; return Object.keys((_a = manifestFile === null || manifestFile === void 0 ? void 0 : manifestFile.frameworks) !== null && _a !== void 0 ? _a : {}); } exports.getTargetFrameworksFromProjectJson = getTargetFrameworksFromProjectJson; function getTargetFrameworksFromProjectAssetsJson(manifestFile) { var _a; return Object.keys((_a = manifestFile === null || manifestFile === void 0 ? void 0 : manifestFile.targets) !== null && _a !== void 0 ? _a : {}); } exports.getTargetFrameworksFromProjectAssetsJson = getTargetFrameworksFromProjectAssetsJson; //# sourceMappingURL=index.js.map /***/ }), /***/ 41039: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getDependencyTreeFromProjectAssetsJson = void 0; function getProjectNameForProjectAssetsJson(manifestFile) { var _a, _b, _c; return (_c = (_b = (_a = manifestFile === null || manifestFile === void 0 ? void 0 : manifestFile.project) === null || _a === void 0 ? void 0 : _a.restore) === null || _b === void 0 ? void 0 : _b.projectName) !== null && _c !== void 0 ? _c : {}; } function getProjectVersionForProjectAssetsJson(manifestFile) { var _a, _b; return (_b = (_a = manifestFile === null || manifestFile === void 0 ? void 0 : manifestFile.project) === null || _a === void 0 ? void 0 : _a.version) !== null && _b !== void 0 ? _b : {}; } function buildPackageTree(name, version) { const depTree = { dependencies: {}, name, version, }; return depTree; } // Currently the function getDependencyTreeFromProjectAssetsJson returns // a two level deep flat list of 100% of dependencies. // TODO: Get full tree function getDependencyTreeFromProjectAssetsJson(manifestFile, targetFrameWork) { var _a, _b, _c, _d, _e, _f; const projectName = getProjectNameForProjectAssetsJson(manifestFile); const projectVersion = getProjectVersionForProjectAssetsJson(manifestFile); const depTree = buildPackageTree(projectName, projectVersion); const topLevelDeps = Object.keys((_b = (_a = manifestFile === null || manifestFile === void 0 ? void 0 : manifestFile.targets) === null || _a === void 0 ? void 0 : _a[targetFrameWork]) !== null && _b !== void 0 ? _b : {}); for (const topLevelDep of topLevelDeps) { const [topLevelDepName, topLevelDepVersion] = topLevelDep.split('/'); const topLevelDepTree = buildPackageTree(topLevelDepName, topLevelDepVersion); const transitiveDeps = (_f = (_e = (_d = (_c = manifestFile === null || manifestFile === void 0 ? void 0 : manifestFile.targets) === null || _c === void 0 ? void 0 : _c[targetFrameWork]) === null || _d === void 0 ? void 0 : _d[topLevelDep]) === null || _e === void 0 ? void 0 : _e.dependencies) !== null && _f !== void 0 ? _f : {}; for (const transitiveDep of Object.keys(transitiveDeps)) { const transitiveDepVersion = transitiveDeps[transitiveDep]; const transitiveDepTree = buildPackageTree(transitiveDep, transitiveDepVersion); topLevelDepTree.dependencies[transitiveDep] = transitiveDepTree; } depTree.dependencies[topLevelDepName] = topLevelDepTree; } return depTree; } exports.getDependencyTreeFromProjectAssetsJson = getDependencyTreeFromProjectAssetsJson; //# sourceMappingURL=project-assets-json-parser.js.map /***/ }), /***/ 70077: /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; // ESM COMPAT FLAG __webpack_require__.r(__webpack_exports__); // EXPORTS __webpack_require__.d(__webpack_exports__, { "NIL": () => (/* reexport */ nil), "parse": () => (/* reexport */ esm_node_parse), "stringify": () => (/* reexport */ esm_node_stringify), "v1": () => (/* reexport */ esm_node_v1), "v3": () => (/* reexport */ esm_node_v3), "v4": () => (/* reexport */ esm_node_v4), "v5": () => (/* reexport */ esm_node_v5), "validate": () => (/* reexport */ esm_node_validate), "version": () => (/* reexport */ esm_node_version) }); // EXTERNAL MODULE: external "crypto" var external_crypto_ = __webpack_require__(6113); var external_crypto_default = /*#__PURE__*/__webpack_require__.n(external_crypto_); ;// CONCATENATED MODULE: ./node_modules/dotnet-deps-parser/node_modules/uuid/dist/esm-node/rng.js const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate let poolPtr = rnds8Pool.length; function rng() { if (poolPtr > rnds8Pool.length - 16) { external_crypto_default().randomFillSync(rnds8Pool); poolPtr = 0; } return rnds8Pool.slice(poolPtr, poolPtr += 16); } ;// CONCATENATED MODULE: ./node_modules/dotnet-deps-parser/node_modules/uuid/dist/esm-node/regex.js /* harmony default export */ const regex = (/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i); ;// CONCATENATED MODULE: ./node_modules/dotnet-deps-parser/node_modules/uuid/dist/esm-node/validate.js function validate(uuid) { return typeof uuid === 'string' && regex.test(uuid); } /* harmony default export */ const esm_node_validate = (validate); ;// CONCATENATED MODULE: ./node_modules/dotnet-deps-parser/node_modules/uuid/dist/esm-node/stringify.js /** * 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]]; } function stringify(arr, offset = 0) { const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one // of the following: // - One or more input array values don't map to a hex octet (leading to // "undefined" in the uuid) // - Invalid input values for the RFC `version` or `variant` fields if (!esm_node_validate(uuid)) { throw TypeError('Stringified UUID is invalid'); } return uuid; } /* harmony default export */ const esm_node_stringify = (stringify); ;// CONCATENATED MODULE: ./node_modules/dotnet-deps-parser/node_modules/uuid/dist/esm-node/v1.js // **`v1()` - Generate time-based UUID** // // Inspired by https://github.com/LiosK/UUID.js // and http://docs.python.org/library/uuid.html let _nodeId; let _clockseq; // Previous uuid creation time let _lastMSecs = 0; let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details function v1(options, buf, offset) { let i = buf && offset || 0; const b = buf || new Array(16); options = options || {}; let node = options.node || _nodeId; let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not // specified. We do this lazily to minimize issues related to insufficient // system entropy. See #189 if (node == null || clockseq == null) { const seedBytes = options.random || (options.rng || rng)(); if (node == null) { // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; } if (clockseq == null) { // Per 4.2.2, randomize (14 bit) clockseq clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; } } // UUID timestamps are 100 nano-second units since the Gregorian epoch, // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock // cycle to simulate higher resolution clock let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression if (dt < 0 && options.clockseq === undefined) { clockseq = clockseq + 1 & 0x3fff; } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new // time interval if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { nsecs = 0; } // Per 4.2.1.2 Throw error if too many uuids are requested if (nsecs >= 10000) { throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); } _lastMSecs = msecs; _lastNSecs = nsecs; _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch msecs += 12219292800000; // `time_low` const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; b[i++] = tl >>> 24 & 0xff; b[i++] = tl >>> 16 & 0xff; b[i++] = tl >>> 8 & 0xff; b[i++] = tl & 0xff; // `time_mid` const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; b[i++] = tmh >>> 8 & 0xff; b[i++] = tmh & 0xff; // `time_high_and_version` b[i++] = tmh >>> 24 & 0xf | 0x10; // include version b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` b[i++] = clockseq & 0xff; // `node` for (let n = 0; n < 6; ++n) { b[i + n] = node[n]; } return buf || unsafeStringify(b); } /* harmony default export */ const esm_node_v1 = (v1); ;// CONCATENATED MODULE: ./node_modules/dotnet-deps-parser/node_modules/uuid/dist/esm-node/parse.js function parse(uuid) { if (!esm_node_validate(uuid)) { throw TypeError('Invalid UUID'); } let v; const arr = new Uint8Array(16); // Parse ########-....-....-....-............ arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; arr[1] = v >>> 16 & 0xff; arr[2] = v >>> 8 & 0xff; arr[3] = v & 0xff; // Parse ........-####-....-....-............ arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; arr[5] = v & 0xff; // Parse ........-....-####-....-............ arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; arr[7] = v & 0xff; // Parse ........-....-....-####-............ arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; arr[9] = v & 0xff; // Parse ........-....-....-....-############ // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; arr[11] = v / 0x100000000 & 0xff; arr[12] = v >>> 24 & 0xff; arr[13] = v >>> 16 & 0xff; arr[14] = v >>> 8 & 0xff; arr[15] = v & 0xff; return arr; } /* harmony default export */ const esm_node_parse = (parse); ;// CONCATENATED MODULE: ./node_modules/dotnet-deps-parser/node_modules/uuid/dist/esm-node/v35.js function stringToBytes(str) { str = unescape(encodeURIComponent(str)); // UTF8 escape const bytes = []; for (let i = 0; i < str.length; ++i) { bytes.push(str.charCodeAt(i)); } return bytes; } const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; function v35(name, version, hashfunc) { function generateUUID(value, namespace, buf, offset) { var _namespace; if (typeof value === 'string') { value = stringToBytes(value); } if (typeof namespace === 'string') { namespace = esm_node_parse(namespace); } if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); } // Compute hash of namespace and value, Per 4.3 // Future: Use spread syntax when supported on all platforms, e.g. `bytes = // hashfunc([...namespace, ... value])` let bytes = new Uint8Array(16 + value.length); bytes.set(namespace); bytes.set(value, namespace.length); bytes = hashfunc(bytes); bytes[6] = bytes[6] & 0x0f | version; bytes[8] = bytes[8] & 0x3f | 0x80; if (buf) { offset = offset || 0; for (let i = 0; i < 16; ++i) { buf[offset + i] = bytes[i]; } return buf; } return unsafeStringify(bytes); } // Function#name is not settable on some platforms (#270) try { generateUUID.name = name; // eslint-disable-next-line no-empty } catch (err) {} // For CommonJS default export support generateUUID.DNS = DNS; generateUUID.URL = URL; return generateUUID; } ;// CONCATENATED MODULE: ./node_modules/dotnet-deps-parser/node_modules/uuid/dist/esm-node/md5.js function md5(bytes) { if (Array.isArray(bytes)) { bytes = Buffer.from(bytes); } else if (typeof bytes === 'string') { bytes = Buffer.from(bytes, 'utf8'); } return external_crypto_default().createHash('md5').update(bytes).digest(); } /* harmony default export */ const esm_node_md5 = (md5); ;// CONCATENATED MODULE: ./node_modules/dotnet-deps-parser/node_modules/uuid/dist/esm-node/v3.js const v3 = v35('v3', 0x30, esm_node_md5); /* harmony default export */ const esm_node_v3 = (v3); ;// CONCATENATED MODULE: ./node_modules/dotnet-deps-parser/node_modules/uuid/dist/esm-node/native.js /* harmony default export */ const esm_node_native = ({ randomUUID: (external_crypto_default()).randomUUID }); ;// CONCATENATED MODULE: ./node_modules/dotnet-deps-parser/node_modules/uuid/dist/esm-node/v4.js function v4(options, buf, offset) { if (esm_node_native.randomUUID && !buf && !options) { return esm_node_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); } /* harmony default export */ const esm_node_v4 = (v4); ;// CONCATENATED MODULE: ./node_modules/dotnet-deps-parser/node_modules/uuid/dist/esm-node/sha1.js function sha1(bytes) { if (Array.isArray(bytes)) { bytes = Buffer.from(bytes); } else if (typeof bytes === 'string') { bytes = Buffer.from(bytes, 'utf8'); } return external_crypto_default().createHash('sha1').update(bytes).digest(); } /* harmony default export */ const esm_node_sha1 = (sha1); ;// CONCATENATED MODULE: ./node_modules/dotnet-deps-parser/node_modules/uuid/dist/esm-node/v5.js const v5 = v35('v5', 0x50, esm_node_sha1); /* harmony default export */ const esm_node_v5 = (v5); ;// CONCATENATED MODULE: ./node_modules/dotnet-deps-parser/node_modules/uuid/dist/esm-node/nil.js /* harmony default export */ const nil = ('00000000-0000-0000-0000-000000000000'); ;// CONCATENATED MODULE: ./node_modules/dotnet-deps-parser/node_modules/uuid/dist/esm-node/version.js function version(uuid) { if (!esm_node_validate(uuid)) { throw TypeError('Invalid UUID'); } return parseInt(uuid.slice(14, 15), 16); } /* harmony default export */ const esm_node_version = (version); ;// CONCATENATED MODULE: ./node_modules/dotnet-deps-parser/node_modules/uuid/dist/esm-node/index.js /***/ }), /***/ 25981: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var stream = __webpack_require__(79349) var eos = __webpack_require__(12840) var inherits = __webpack_require__(94378) var shift = __webpack_require__(31852) var SIGNAL_FLUSH = (Buffer.from && Buffer.from !== Uint8Array.from) ? Buffer.from([0]) : new Buffer([0]) var onuncork = function(self, fn) { if (self._corked) self.once('uncork', fn) else fn() } var autoDestroy = function (self, err) { if (self._autoDestroy) self.destroy(err) } var destroyer = function(self, end) { return function(err) { if (err) autoDestroy(self, err.message === 'premature close' ? null : err) else if (end && !self._ended) self.end() } } var end = function(ws, fn) { if (!ws) return fn() if (ws._writableState && ws._writableState.finished) return fn() if (ws._writableState) return ws.end(fn) ws.end() fn() } var toStreams2 = function(rs) { return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs) } var Duplexify = function(writable, readable, opts) { if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts) stream.Duplex.call(this, opts) this._writable = null this._readable = null this._readable2 = null this._autoDestroy = !opts || opts.autoDestroy !== false this._forwardDestroy = !opts || opts.destroy !== false this._forwardEnd = !opts || opts.end !== false this._corked = 1 // start corked this._ondrain = null this._drained = false this._forwarding = false this._unwrite = null this._unread = null this._ended = false this.destroyed = false if (writable) this.setWritable(writable) if (readable) this.setReadable(readable) } inherits(Duplexify, stream.Duplex) Duplexify.obj = function(writable, readable, opts) { if (!opts) opts = {} opts.objectMode = true opts.highWaterMark = 16 return new Duplexify(writable, readable, opts) } Duplexify.prototype.cork = function() { if (++this._corked === 1) this.emit('cork') } Duplexify.prototype.uncork = function() { if (this._corked && --this._corked === 0) this.emit('uncork') } Duplexify.prototype.setWritable = function(writable) { if (this._unwrite) this._unwrite() if (this.destroyed) { if (writable && writable.destroy) writable.destroy() return } if (writable === null || writable === false) { this.end() return } var self = this var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd)) var ondrain = function() { var ondrain = self._ondrain self._ondrain = null if (ondrain) ondrain() } var clear = function() { self._writable.removeListener('drain', ondrain) unend() } if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks this._writable = writable this._writable.on('drain', ondrain) this._unwrite = clear this.uncork() // always uncork setWritable } Duplexify.prototype.setReadable = function(readable) { if (this._unread) this._unread() if (this.destroyed) { if (readable && readable.destroy) readable.destroy() return } if (readable === null || readable === false) { this.push(null) this.resume() return } var self = this var unend = eos(readable, {writable:false, readable:true}, destroyer(this)) var onreadable = function() { self._forward() } var onend = function() { self.push(null) } var clear = function() { self._readable2.removeListener('readable', onreadable) self._readable2.removeListener('end', onend) unend() } this._drained = true this._readable = readable this._readable2 = readable._readableState ? readable : toStreams2(readable) this._readable2.on('readable', onreadable) this._readable2.on('end', onend) this._unread = clear this._forward() } Duplexify.prototype._read = function() { this._drained = true this._forward() } Duplexify.prototype._forward = function() { if (this._forwarding || !this._readable2 || !this._drained) return this._forwarding = true var data while (this._drained && (data = shift(this._readable2)) !== null) { if (this.destroyed) continue this._drained = this.push(data) } this._forwarding = false } Duplexify.prototype.destroy = function(err) { if (this.destroyed) return this.destroyed = true var self = this process.nextTick(function() { self._destroy(err) }) } Duplexify.prototype._destroy = function(err) { if (err) { var ondrain = this._ondrain this._ondrain = null if (ondrain) ondrain(err) else this.emit('error', err) } if (this._forwardDestroy) { if (this._readable && this._readable.destroy) this._readable.destroy() if (this._writable && this._writable.destroy) this._writable.destroy() } this.emit('close') } Duplexify.prototype._write = function(data, enc, cb) { if (this.destroyed) return cb() if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb)) if (data === SIGNAL_FLUSH) return this._finish(cb) if (!this._writable) return cb() if (this._writable.write(data) === false) this._ondrain = cb else cb() } Duplexify.prototype._finish = function(cb) { var self = this this.emit('preend') onuncork(this, function() { end(self._forwardEnd && self._writable, function() { // haxx to not emit prefinish twice if (self._writableState.prefinished === false) self._writableState.prefinished = true self.emit('prefinish') onuncork(self, cb) }) }) } Duplexify.prototype.end = function(data, enc, cb) { if (typeof data === 'function') return this.end(null, null, data) if (typeof enc === 'function') return this.end(data, null, enc) this._ended = true if (data) this.write(data) if (!this._writableState.ending) this.write(SIGNAL_FLUSH) return stream.Writable.prototype.end.call(this, cb) } module.exports = Duplexify /***/ }), /***/ 64191: /***/ ((module) => { var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; /***/ }), /***/ 15227: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from // Writable. /**/ var pna = __webpack_require__(88212); /**/ /**/ var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { keys.push(key); }return keys; }; /**/ module.exports = Duplex; /**/ var util = Object.create(__webpack_require__(16497)); util.inherits = __webpack_require__(94378); /**/ var Readable = __webpack_require__(1372); var Writable = __webpack_require__(89083); util.inherits(Duplex, Readable); { // avoid scope creep, the keys array can then be collected var keys = objectKeys(Writable.prototype); for (var v = 0; v < keys.length; v++) { var method = keys[v]; if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } } function Duplex(options) { if (!(this instanceof Duplex)) return new Duplex(options); Readable.call(this, options); Writable.call(this, options); if (options && options.readable === false) this.readable = false; if (options && options.writable === false) this.writable = false; this.allowHalfOpen = true; if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; this.once('end', onend); } Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function () { return this._writableState.highWaterMark; } }); // the no-half-open enforcer function onend() { // if we allow half-open state, or if the writable side ended, // then we're ok. if (this.allowHalfOpen || this._writableState.ended) return; // no more data can be written. // But allow more writes to happen in this tick. pna.nextTick(onEndNT, this); } function onEndNT(self) { self.end(); } Object.defineProperty(Duplex.prototype, 'destroyed', { get: function () { if (this._readableState === undefined || this._writableState === undefined) { return false; } return this._readableState.destroyed && this._writableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (this._readableState === undefined || this._writableState === undefined) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; this._writableState.destroyed = value; } }); Duplex.prototype._destroy = function (err, cb) { this.push(null); this.end(); pna.nextTick(cb, err); }; /***/ }), /***/ 95688: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. module.exports = PassThrough; var Transform = __webpack_require__(34670); /**/ var util = Object.create(__webpack_require__(16497)); util.inherits = __webpack_require__(94378); /**/ util.inherits(PassThrough, Transform); function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options); Transform.call(this, options); } PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; /***/ }), /***/ 1372: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /**/ var pna = __webpack_require__(88212); /**/ module.exports = Readable; /**/ var isArray = __webpack_require__(64191); /**/ /**/ var Duplex; /**/ Readable.ReadableState = ReadableState; /**/ var EE = __webpack_require__(82361).EventEmitter; var EElistenerCount = function (emitter, type) { return emitter.listeners(type).length; }; /**/ /**/ var Stream = __webpack_require__(73754); /**/ /**/ var Buffer = __webpack_require__(89509).Buffer; var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } /**/ /**/ var util = Object.create(__webpack_require__(16497)); util.inherits = __webpack_require__(94378); /**/ /**/ var debugUtil = __webpack_require__(73837); var debug = void 0; if (debugUtil && debugUtil.debuglog) { debug = debugUtil.debuglog('stream'); } else { debug = function () {}; } /**/ var BufferList = __webpack_require__(26528); var destroyImpl = __webpack_require__(35296); var StringDecoder; util.inherits(Readable, Stream); var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; function prependListener(emitter, event, fn) { // Sadly this is not cacheable as some libraries bundle their own // event emitter implementation with them. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any // userland ones. NEVER DO THIS. This is here only because this code needs // to continue to work with older versions of Node.js that do not include // the prependListener() method. The goal is to eventually remove this hack. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; } function ReadableState(options, stream) { Duplex = Duplex || __webpack_require__(15227); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. var isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to // make all the buffer merging and length checks go away this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer // Note: 0 is a valid value, means "don't call _read preemptively ever" var hwm = options.highWaterMark; var readableHwm = options.readableHighWaterMark; var defaultHwm = this.objectMode ? 16 : 16 * 1024; if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; // cast to ints. this.highWaterMark = Math.floor(this.highWaterMark); // A linked list is used to store data chunks instead of an array because the // linked list can remove elements from the beginning faster than // array.shift() this.buffer = new BufferList(); this.length = 0; this.pipes = null; this.pipesCount = 0; this.flowing = null; this.ended = false; this.endEmitted = false; this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted // immediately, or on a later tick. We set this to true at first, because // any actions that shouldn't happen until "later" should generally also // not happen before the first read call. this.sync = true; // whenever we return null, then we set a flag to say // that we're awaiting a 'readable' event emission. this.needReadable = false; this.emittedReadable = false; this.readableListening = false; this.resumeScheduled = false; // has it been destroyed this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled this.readingMore = false; this.decoder = null; this.encoding = null; if (options.encoding) { if (!StringDecoder) StringDecoder = __webpack_require__(71785)/* .StringDecoder */ .s; this.decoder = new StringDecoder(options.encoding); this.encoding = options.encoding; } } function Readable(options) { Duplex = Duplex || __webpack_require__(15227); if (!(this instanceof Readable)) return new Readable(options); this._readableState = new ReadableState(options, this); // legacy this.readable = true; if (options) { if (typeof options.read === 'function') this._read = options.read; if (typeof options.destroy === 'function') this._destroy = options.destroy; } Stream.call(this); } Object.defineProperty(Readable.prototype, 'destroyed', { get: function () { if (this._readableState === undefined) { return false; } return this._readableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (!this._readableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; } }); Readable.prototype.destroy = destroyImpl.destroy; Readable.prototype._undestroy = destroyImpl.undestroy; Readable.prototype._destroy = function (err, cb) { this.push(null); cb(err); }; // Manually shove something into the read() buffer. // This returns true if the highWaterMark has not been hit yet, // similar to how Writable.write() returns true if you should // write() some more. Readable.prototype.push = function (chunk, encoding) { var state = this._readableState; var skipChunkCheck; if (!state.objectMode) { if (typeof chunk === 'string') { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { chunk = Buffer.from(chunk, encoding); encoding = ''; } skipChunkCheck = true; } } else { skipChunkCheck = true; } return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); }; // Unshift should *always* be something directly out of read() Readable.prototype.unshift = function (chunk) { return readableAddChunk(this, chunk, null, true, false); }; function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { var state = stream._readableState; if (chunk === null) { state.reading = false; onEofChunk(stream, state); } else { var er; if (!skipChunkCheck) er = chunkInvalid(state, chunk); if (er) { stream.emit('error', er); } else if (state.objectMode || chunk && chunk.length > 0) { if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { chunk = _uint8ArrayToBuffer(chunk); } if (addToFront) { if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); } else if (state.ended) { stream.emit('error', new Error('stream.push() after EOF')); } else { state.reading = false; if (state.decoder && !encoding) { chunk = state.decoder.write(chunk); if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); } else { addChunk(stream, state, chunk, false); } } } else if (!addToFront) { state.reading = false; } } return needMoreData(state); } function addChunk(stream, state, chunk, addToFront) { if (state.flowing && state.length === 0 && !state.sync) { stream.emit('data', chunk); stream.read(0); } else { // update the buffer info. state.length += state.objectMode ? 1 : chunk.length; if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); if (state.needReadable) emitReadable(stream); } maybeReadMore(stream, state); } function chunkInvalid(state, chunk) { var er; if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } return er; } // if it's past the high water mark, we can push in some more. // Also, if we have no data yet, we can stand some // more bytes. This is to work around cases where hwm=0, // such as the repl. Also, if the push() triggered a // readable event, and the user called read(largeNumber) such that // needReadable was set, then we ought to push more, so that another // 'readable' event will be triggered. function needMoreData(state) { return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); } Readable.prototype.isPaused = function () { return this._readableState.flowing === false; }; // backwards compatibility. Readable.prototype.setEncoding = function (enc) { if (!StringDecoder) StringDecoder = __webpack_require__(71785)/* .StringDecoder */ .s; this._readableState.decoder = new StringDecoder(enc); this._readableState.encoding = enc; return this; }; // Don't raise the hwm > 8MB var MAX_HWM = 0x800000; function computeNewHighWaterMark(n) { if (n >= MAX_HWM) { n = MAX_HWM; } else { // Get the next highest power of 2 to prevent increasing hwm excessively in // tiny amounts n--; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; n++; } return n; } // This function is designed to be inlinable, so please take care when making // changes to the function body. function howMuchToRead(n, state) { if (n <= 0 || state.length === 0 && state.ended) return 0; if (state.objectMode) return 1; if (n !== n) { // Only flow one buffer at a time if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; } // If we're asking for more than the current hwm, then raise the hwm. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); if (n <= state.length) return n; // Don't have enough if (!state.ended) { state.needReadable = true; return 0; } return state.length; } // you can override either this method, or the async _read(n) below. Readable.prototype.read = function (n) { debug('read', n); n = parseInt(n, 10); var state = this._readableState; var nOrig = n; if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we // already have a bunch of data in the buffer, then just trigger // the 'readable' event and move on. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { debug('read: emitReadable', state.length, state.ended); if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); return null; } n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. if (n === 0 && state.ended) { if (state.length === 0) endReadable(this); return null; } // All the actual chunk generation logic needs to be // *below* the call to _read. The reason is that in certain // synthetic stream cases, such as passthrough streams, _read // may be a completely synchronous operation which may change // the state of the read buffer, providing enough data when // before there was *not* enough. // // So, the steps are: // 1. Figure out what the state of things will be after we do // a read from the buffer. // // 2. If that resulting state will trigger a _read, then call _read. // Note that this may be asynchronous, or synchronous. Yes, it is // deeply ugly to write APIs this way, but that still doesn't mean // that the Readable class should behave improperly, as streams are // designed to be sync/async agnostic. // Take note if the _read call is sync or async (ie, if the read call // has returned yet), so that we know whether or not it's safe to emit // 'readable' etc. // // 3. Actually pull the requested chunks out of the buffer and return. // if we need a readable event, then we need to do some reading. var doRead = state.needReadable; debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; debug('length less than watermark', doRead); } // however, if we've ended, then there's no point, and if we're already // reading, then it's unnecessary. if (state.ended || state.reading) { doRead = false; debug('reading or ended', doRead); } else if (doRead) { debug('do read'); state.reading = true; state.sync = true; // if the length is currently zero, then we *need* a readable event. if (state.length === 0) state.needReadable = true; // call internal read method this._read(state.highWaterMark); state.sync = false; // If _read pushed data synchronously, then `reading` will be false, // and we need to re-evaluate how much data we can return to the user. if (!state.reading) n = howMuchToRead(nOrig, state); } var ret; if (n > 0) ret = fromList(n, state);else ret = null; if (ret === null) { state.needReadable = true; n = 0; } else { state.length -= n; } if (state.length === 0) { // If we have nothing in the buffer, then we want to know // as soon as we *do* get something into the buffer. if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. if (nOrig !== n && state.ended) endReadable(this); } if (ret !== null) this.emit('data', ret); return ret; }; function onEofChunk(stream, state) { if (state.ended) return; if (state.decoder) { var chunk = state.decoder.end(); if (chunk && chunk.length) { state.buffer.push(chunk); state.length += state.objectMode ? 1 : chunk.length; } } state.ended = true; // emit 'readable' now to make sure it gets picked up. emitReadable(stream); } // Don't emit readable right away in sync mode, because this can trigger // another read() call => stack overflow. This way, it might trigger // a nextTick recursion warning, but that's not so bad. function emitReadable(stream) { var state = stream._readableState; state.needReadable = false; if (!state.emittedReadable) { debug('emitReadable', state.flowing); state.emittedReadable = true; if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); } } function emitReadable_(stream) { debug('emit readable'); stream.emit('readable'); flow(stream); } // at this point, the user has presumably seen the 'readable' event, // and called read() to consume some data. that may have triggered // in turn another _read(n) call, in which case reading = true if // it's in progress. // However, if we're not ended, or reading, and the length < hwm, // then go ahead and try to read some more preemptively. function maybeReadMore(stream, state) { if (!state.readingMore) { state.readingMore = true; pna.nextTick(maybeReadMore_, stream, state); } } function maybeReadMore_(stream, state) { var len = state.length; while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { debug('maybeReadMore read 0'); stream.read(0); if (len === state.length) // didn't get any data, stop spinning. break;else len = state.length; } state.readingMore = false; } // abstract method. to be overridden in specific implementation classes. // call cb(er, data) where data is <= n in length. // for virtual (non-string, non-buffer) streams, "length" is somewhat // arbitrary, and perhaps not very meaningful. Readable.prototype._read = function (n) { this.emit('error', new Error('_read() is not implemented')); }; Readable.prototype.pipe = function (dest, pipeOpts) { var src = this; var state = this._readableState; switch (state.pipesCount) { case 0: state.pipes = dest; break; case 1: state.pipes = [state.pipes, dest]; break; default: state.pipes.push(dest); break; } state.pipesCount += 1; debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; var endFn = doEnd ? onend : unpipe; if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); dest.on('unpipe', onunpipe); function onunpipe(readable, unpipeInfo) { debug('onunpipe'); if (readable === src) { if (unpipeInfo && unpipeInfo.hasUnpiped === false) { unpipeInfo.hasUnpiped = true; cleanup(); } } } function onend() { debug('onend'); dest.end(); } // when the dest drains, it reduces the awaitDrain counter // on the source. This would be more elegant with a .once() // handler in flow(), but adding and removing repeatedly is // too slow. var ondrain = pipeOnDrain(src); dest.on('drain', ondrain); var cleanedUp = false; function cleanup() { debug('cleanup'); // cleanup event handlers once the pipe is broken dest.removeListener('close', onclose); dest.removeListener('finish', onfinish); dest.removeListener('drain', ondrain); dest.removeListener('error', onerror); dest.removeListener('unpipe', onunpipe); src.removeListener('end', onend); src.removeListener('end', unpipe); src.removeListener('data', ondata); cleanedUp = true; // if the reader is waiting for a drain event from this // specific writer, then it would cause it to never start // flowing again. // So, if this is awaiting a drain, then we just call it now. // If we don't know, then assume that we are waiting for one. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } // If the user pushes more data while we're writing to dest then we'll end up // in ondata again. However, we only want to increase awaitDrain once because // dest will only emit one 'drain' event for the multiple writes. // => Introduce a guard on increasing awaitDrain. var increasedAwaitDrain = false; src.on('data', ondata); function ondata(chunk) { debug('ondata'); increasedAwaitDrain = false; var ret = dest.write(chunk); if (false === ret && !increasedAwaitDrain) { // If the user unpiped during `dest.write()`, it is possible // to get stuck in a permanently paused state if that write // also returned false. // => Check whether `dest` is still a piping destination. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { debug('false write response, pause', state.awaitDrain); state.awaitDrain++; increasedAwaitDrain = true; } src.pause(); } } // if the dest has an error, then stop piping into it. // however, don't suppress the throwing behavior for this. function onerror(er) { debug('onerror', er); unpipe(); dest.removeListener('error', onerror); if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); } // Make sure our error handler is attached before userland ones. prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. function onclose() { dest.removeListener('finish', onfinish); unpipe(); } dest.once('close', onclose); function onfinish() { debug('onfinish'); dest.removeListener('close', onclose); unpipe(); } dest.once('finish', onfinish); function unpipe() { debug('unpipe'); src.unpipe(dest); } // tell the dest that it's being piped to dest.emit('pipe', src); // start the flow if it hasn't been started already. if (!state.flowing) { debug('pipe resume'); src.resume(); } return dest; }; function pipeOnDrain(src) { return function () { var state = src._readableState; debug('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { state.flowing = true; flow(src); } }; } Readable.prototype.unpipe = function (dest) { var state = this._readableState; var unpipeInfo = { hasUnpiped: false }; // if we're not piping anywhere, then do nothing. if (state.pipesCount === 0) return this; // just one destination. most common case. if (state.pipesCount === 1) { // passed in one, but it's not the right one. if (dest && dest !== state.pipes) return this; if (!dest) dest = state.pipes; // got a match. state.pipes = null; state.pipesCount = 0; state.flowing = false; if (dest) dest.emit('unpipe', this, unpipeInfo); return this; } // slow case. multiple pipe destinations. if (!dest) { // remove all. var dests = state.pipes; var len = state.pipesCount; state.pipes = null; state.pipesCount = 0; state.flowing = false; for (var i = 0; i < len; i++) { dests[i].emit('unpipe', this, { hasUnpiped: false }); }return this; } // try to find the right one. var index = indexOf(state.pipes, dest); if (index === -1) return this; state.pipes.splice(index, 1); state.pipesCount -= 1; if (state.pipesCount === 1) state.pipes = state.pipes[0]; dest.emit('unpipe', this, unpipeInfo); return this; }; // set up data events if they are asked for // Ensure readable listeners eventually get something Readable.prototype.on = function (ev, fn) { var res = Stream.prototype.on.call(this, ev, fn); if (ev === 'data') { // Start flowing on next tick if stream isn't explicitly paused if (this._readableState.flowing !== false) this.resume(); } else if (ev === 'readable') { var state = this._readableState; if (!state.endEmitted && !state.readableListening) { state.readableListening = state.needReadable = true; state.emittedReadable = false; if (!state.reading) { pna.nextTick(nReadingNextTick, this); } else if (state.length) { emitReadable(this); } } } return res; }; Readable.prototype.addListener = Readable.prototype.on; function nReadingNextTick(self) { debug('readable nexttick read 0'); self.read(0); } // pause() and resume() are remnants of the legacy readable stream API // If the user uses them, then switch into old mode. Readable.prototype.resume = function () { var state = this._readableState; if (!state.flowing) { debug('resume'); state.flowing = true; resume(this, state); } return this; }; function resume(stream, state) { if (!state.resumeScheduled) { state.resumeScheduled = true; pna.nextTick(resume_, stream, state); } } function resume_(stream, state) { if (!state.reading) { debug('resume read 0'); stream.read(0); } state.resumeScheduled = false; state.awaitDrain = 0; stream.emit('resume'); flow(stream); if (state.flowing && !state.reading) stream.read(0); } Readable.prototype.pause = function () { debug('call pause flowing=%j', this._readableState.flowing); if (false !== this._readableState.flowing) { debug('pause'); this._readableState.flowing = false; this.emit('pause'); } return this; }; function flow(stream) { var state = stream._readableState; debug('flow', state.flowing); while (state.flowing && stream.read() !== null) {} } // wrap an old-style stream as the async data source. // This is *not* part of the readable stream interface. // It is an ugly unfortunate mess of history. Readable.prototype.wrap = function (stream) { var _this = this; var state = this._readableState; var paused = false; stream.on('end', function () { debug('wrapped end'); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) _this.push(chunk); } _this.push(null); }); stream.on('data', function (chunk) { debug('wrapped data'); if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; var ret = _this.push(chunk); if (!ret) { paused = true; stream.pause(); } }); // proxy all the other methods. // important when wrapping filters and duplexes. for (var i in stream) { if (this[i] === undefined && typeof stream[i] === 'function') { this[i] = function (method) { return function () { return stream[method].apply(stream, arguments); }; }(i); } } // proxy certain important events. for (var n = 0; n < kProxyEvents.length; n++) { stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); } // when we try to consume some more bytes, simply unpause the // underlying stream. this._read = function (n) { debug('wrapped _read', n); if (paused) { paused = false; stream.resume(); } }; return this; }; Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function () { return this._readableState.highWaterMark; } }); // exposed for testing purposes only. Readable._fromList = fromList; // Pluck off n bytes from an array of buffers. // Length is the combined lengths of all the buffers in the list. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromList(n, state) { // nothing buffered if (state.length === 0) return null; var ret; if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { // read it all, truncate the list if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); state.buffer.clear(); } else { // read part of list ret = fromListPartial(n, state.buffer, state.decoder); } return ret; } // Extracts only enough buffered data to satisfy the amount requested. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromListPartial(n, list, hasStrings) { var ret; if (n < list.head.data.length) { // slice is the same for buffers and strings ret = list.head.data.slice(0, n); list.head.data = list.head.data.slice(n); } else if (n === list.head.data.length) { // first chunk is a perfect match ret = list.shift(); } else { // result spans more than one buffer ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); } return ret; } // Copies a specified amount of characters from the list of buffered data // chunks. // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBufferString(n, list) { var p = list.head; var c = 1; var ret = p.data; n -= ret.length; while (p = p.next) { var str = p.data; var nb = n > str.length ? str.length : n; if (nb === str.length) ret += str;else ret += str.slice(0, n); n -= nb; if (n === 0) { if (nb === str.length) { ++c; if (p.next) list.head = p.next;else list.head = list.tail = null; } else { list.head = p; p.data = str.slice(nb); } break; } ++c; } list.length -= c; return ret; } // Copies a specified amount of bytes from the list of buffered data chunks. // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBuffer(n, list) { var ret = Buffer.allocUnsafe(n); var p = list.head; var c = 1; p.data.copy(ret); n -= p.data.length; while (p = p.next) { var buf = p.data; var nb = n > buf.length ? buf.length : n; buf.copy(ret, ret.length - n, 0, nb); n -= nb; if (n === 0) { if (nb === buf.length) { ++c; if (p.next) list.head = p.next;else list.head = list.tail = null; } else { list.head = p; p.data = buf.slice(nb); } break; } ++c; } list.length -= c; return ret; } function endReadable(stream) { var state = stream._readableState; // If we get here before consuming all the bytes, then that is a // bug in node. Should never happen. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); if (!state.endEmitted) { state.ended = true; pna.nextTick(endReadableNT, state, stream); } } function endReadableNT(state, stream) { // Check that we didn't get one last unshift. if (!state.endEmitted && state.length === 0) { state.endEmitted = true; stream.readable = false; stream.emit('end'); } } function indexOf(xs, x) { for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) return i; } return -1; } /***/ }), /***/ 34670: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where // some bits pass through, and others are simply ignored. (That would // be a valid example of a transform, of course.) // // While the output is causally related to the input, it's not a // necessarily symmetric or synchronous transformation. For example, // a zlib stream might take multiple plain-text writes(), and then // emit a single compressed chunk some time in the future. // // Here's how this works: // // The Transform stream has all the aspects of the readable and writable // stream classes. When you write(chunk), that calls _write(chunk,cb) // internally, and returns false if there's a lot of pending writes // buffered up. When you call read(), that calls _read(n) until // there's enough pending readable data buffered up. // // In a transform stream, the written data is placed in a buffer. When // _read(n) is called, it transforms the queued up data, calling the // buffered _write cb's as it consumes chunks. If consuming a single // written chunk would result in multiple output chunks, then the first // outputted bit calls the readcb, and subsequent chunks just go into // the read buffer, and will cause it to emit 'readable' if necessary. // // This way, back-pressure is actually determined by the reading side, // since _read has to be called to start processing a new chunk. However, // a pathological inflate type of transform can cause excessive buffering // here. For example, imagine a stream where every byte of input is // interpreted as an integer from 0-255, and then results in that many // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in // 1kb of data being output. In this case, you could write a very small // amount of input, and end up with a very large amount of output. In // such a pathological inflating mechanism, there'd be no way to tell // the system to stop doing the transform. A single 4MB write could // cause the system to run out of memory. // // However, even in such a pathological case, only a single written chunk // would be consumed, and then the rest would wait (un-transformed) until // the results of the previous transformed chunk were consumed. module.exports = Transform; var Duplex = __webpack_require__(15227); /**/ var util = Object.create(__webpack_require__(16497)); util.inherits = __webpack_require__(94378); /**/ util.inherits(Transform, Duplex); function afterTransform(er, data) { var ts = this._transformState; ts.transforming = false; var cb = ts.writecb; if (!cb) { return this.emit('error', new Error('write callback called multiple times')); } ts.writechunk = null; ts.writecb = null; if (data != null) // single equals check for both `null` and `undefined` this.push(data); cb(er); var rs = this._readableState; rs.reading = false; if (rs.needReadable || rs.length < rs.highWaterMark) { this._read(rs.highWaterMark); } } function Transform(options) { if (!(this instanceof Transform)) return new Transform(options); Duplex.call(this, options); this._transformState = { afterTransform: afterTransform.bind(this), needTransform: false, transforming: false, writecb: null, writechunk: null, writeencoding: null }; // start out asking for a readable event once data is transformed. this._readableState.needReadable = true; // we have implemented the _read method, and done the other things // that Readable wants before the first _read call, so unset the // sync guard flag. this._readableState.sync = false; if (options) { if (typeof options.transform === 'function') this._transform = options.transform; if (typeof options.flush === 'function') this._flush = options.flush; } // When the writable side finishes, then flush out anything remaining. this.on('prefinish', prefinish); } function prefinish() { var _this = this; if (typeof this._flush === 'function') { this._flush(function (er, data) { done(_this, er, data); }); } else { done(this, null, null); } } Transform.prototype.push = function (chunk, encoding) { this._transformState.needTransform = false; return Duplex.prototype.push.call(this, chunk, encoding); }; // This is the part where you do stuff! // override this function in implementation classes. // 'chunk' is an input chunk. // // Call `push(newChunk)` to pass along transformed output // to the readable side. You may call 'push' zero or more times. // // Call `cb(err)` when you are done with this chunk. If you pass // an error, then that'll put the hurt on the whole operation. If you // never call cb(), then you'll never get another chunk. Transform.prototype._transform = function (chunk, encoding, cb) { throw new Error('_transform() is not implemented'); }; Transform.prototype._write = function (chunk, encoding, cb) { var ts = this._transformState; ts.writecb = cb; ts.writechunk = chunk; ts.writeencoding = encoding; if (!ts.transforming) { var rs = this._readableState; if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } }; // Doesn't matter what the args are here. // _transform does all the work. // That we got here means that the readable side wants more data. Transform.prototype._read = function (n) { var ts = this._transformState; if (ts.writechunk !== null && ts.writecb && !ts.transforming) { ts.transforming = true; this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { // mark that we need a transform, so that any data that comes in // will get processed, now that we've asked for it. ts.needTransform = true; } }; Transform.prototype._destroy = function (err, cb) { var _this2 = this; Duplex.prototype._destroy.call(this, err, function (err2) { cb(err2); _this2.emit('close'); }); }; function done(stream, er, data) { if (er) return stream.emit('error', er); if (data != null) // single equals check for both `null` and `undefined` stream.push(data); // if there's nothing in the write buffer, then that means // that nothing more will ever be provided if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); return stream.push(null); } /***/ }), /***/ 89083: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // A bit simpler than readable streams. // Implement an async ._write(chunk, encoding, cb), and it'll handle all // the drain event emission and buffering. /**/ var pna = __webpack_require__(88212); /**/ module.exports = Writable; /* */ function WriteReq(chunk, encoding, cb) { this.chunk = chunk; this.encoding = encoding; this.callback = cb; this.next = null; } // It seems a linked list but it is not // there will be only 2 of these for each stream function CorkedRequest(state) { var _this = this; this.next = null; this.entry = null; this.finish = function () { onCorkedFinish(_this, state); }; } /* */ /**/ var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; /**/ /**/ var Duplex; /**/ Writable.WritableState = WritableState; /**/ var util = Object.create(__webpack_require__(16497)); util.inherits = __webpack_require__(94378); /**/ /**/ var internalUtil = { deprecate: __webpack_require__(41159) }; /**/ /**/ var Stream = __webpack_require__(73754); /**/ /**/ var Buffer = __webpack_require__(89509).Buffer; var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } /**/ var destroyImpl = __webpack_require__(35296); util.inherits(Writable, Stream); function nop() {} function WritableState(options, stream) { Duplex = Duplex || __webpack_require__(15227); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. var isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream // contains buffers or objects. this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false // Note: 0 is a valid value, means that we always return false if // the entire buffer is not flushed immediately on write() var hwm = options.highWaterMark; var writableHwm = options.writableHighWaterMark; var defaultHwm = this.objectMode ? 16 : 16 * 1024; if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; // cast to ints. this.highWaterMark = Math.floor(this.highWaterMark); // if _final has been called this.finalCalled = false; // drain event flag. this.needDrain = false; // at the start of calling end() this.ending = false; // when end() has been called, and returned this.ended = false; // when 'finish' is emitted this.finished = false; // has it been destroyed this.destroyed = false; // should we decode strings into buffers before passing to _write? // this is here so that some node-core streams can optimize string // handling at a lower level. var noDecode = options.decodeStrings === false; this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement // of how much we're waiting to get pushed to some underlying // socket or file. this.length = 0; // a flag to see when we're in the middle of a write. this.writing = false; // when true all writes will be buffered until .uncork() call this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, because any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. this.sync = true; // a flag to know if we're processing previously buffered items, which // may call the _write() callback in the same tick, so that we don't // end up in an overlapped onwrite situation. this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) this.onwrite = function (er) { onwrite(stream, er); }; // the callback that the user supplies to write(chunk,encoding,cb) this.writecb = null; // the amount that is being written when _write is called. this.writelen = 0; this.bufferedRequest = null; this.lastBufferedRequest = null; // number of pending user-supplied write callbacks // this must be 0 before 'finish' can be emitted this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs // This is relevant for synchronous Transform streams this.prefinished = false; // True if the error was already emitted and should not be thrown again this.errorEmitted = false; // count buffered requests this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always // one allocated and free to use, and we maintain at most two this.corkedRequestsFree = new CorkedRequest(this); } WritableState.prototype.getBuffer = function getBuffer() { var current = this.bufferedRequest; var out = []; while (current) { out.push(current); current = current.next; } return out; }; (function () { try { Object.defineProperty(WritableState.prototype, 'buffer', { get: internalUtil.deprecate(function () { return this.getBuffer(); }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') }); } catch (_) {} })(); // Test _writableState for inheritance to account for Duplex streams, // whose prototype chain only points to Readable. var realHasInstance; if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { realHasInstance = Function.prototype[Symbol.hasInstance]; Object.defineProperty(Writable, Symbol.hasInstance, { value: function (object) { if (realHasInstance.call(this, object)) return true; if (this !== Writable) return false; return object && object._writableState instanceof WritableState; } }); } else { realHasInstance = function (object) { return object instanceof this; }; } function Writable(options) { Duplex = Duplex || __webpack_require__(15227); // Writable ctor is applied to Duplexes, too. // `realHasInstance` is necessary because using plain `instanceof` // would return false, as no `_writableState` property is attached. // Trying to use the custom `instanceof` for Writable here will also break the // Node.js LazyTransform implementation, which has a non-trivial getter for // `_writableState` that would lead to infinite recursion. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { return new Writable(options); } this._writableState = new WritableState(options, this); // legacy. this.writable = true; if (options) { if (typeof options.write === 'function') this._write = options.write; if (typeof options.writev === 'function') this._writev = options.writev; if (typeof options.destroy === 'function') this._destroy = options.destroy; if (typeof options.final === 'function') this._final = options.final; } Stream.call(this); } // Otherwise people can pipe Writable streams, which is just wrong. Writable.prototype.pipe = function () { this.emit('error', new Error('Cannot pipe, not readable')); }; function writeAfterEnd(stream, cb) { var er = new Error('write after end'); // TODO: defer error events consistently everywhere, not just the cb stream.emit('error', er); pna.nextTick(cb, er); } // Checks that a user-supplied chunk is valid, especially for the particular // mode the stream is in. Currently this means that `null` is never accepted // and undefined/non-string values are only allowed in object mode. function validChunk(stream, state, chunk, cb) { var valid = true; var er = false; if (chunk === null) { er = new TypeError('May not write null values to stream'); } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } if (er) { stream.emit('error', er); pna.nextTick(cb, er); valid = false; } return valid; } Writable.prototype.write = function (chunk, encoding, cb) { var state = this._writableState; var ret = false; var isBuf = !state.objectMode && _isUint8Array(chunk); if (isBuf && !Buffer.isBuffer(chunk)) { chunk = _uint8ArrayToBuffer(chunk); } if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; if (typeof cb !== 'function') cb = nop; if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { state.pendingcb++; ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); } return ret; }; Writable.prototype.cork = function () { var state = this._writableState; state.corked++; }; Writable.prototype.uncork = function () { var state = this._writableState; if (state.corked) { state.corked--; if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); } }; Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { // node::ParseEncoding() requires lower case. if (typeof encoding === 'string') encoding = encoding.toLowerCase(); if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); this._writableState.defaultEncoding = encoding; return this; }; function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { chunk = Buffer.from(chunk, encoding); } return chunk; } Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function () { return this._writableState.highWaterMark; } }); // if we're already writing something, then just put this // in the queue, and wait our turn. Otherwise, call _write // If we return false, then we need a drain event, so set that flag. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { if (!isBuf) { var newChunk = decodeChunk(state, chunk, encoding); if (chunk !== newChunk) { isBuf = true; encoding = 'buffer'; chunk = newChunk; } } var len = state.objectMode ? 1 : chunk.length; state.length += len; var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. if (!ret) state.needDrain = true; if (state.writing || state.corked) { var last = state.lastBufferedRequest; state.lastBufferedRequest = { chunk: chunk, encoding: encoding, isBuf: isBuf, callback: cb, next: null }; if (last) { last.next = state.lastBufferedRequest; } else { state.bufferedRequest = state.lastBufferedRequest; } state.bufferedRequestCount += 1; } else { doWrite(stream, state, false, len, chunk, encoding, cb); } return ret; } function doWrite(stream, state, writev, len, chunk, encoding, cb) { state.writelen = len; state.writecb = cb; state.writing = true; state.sync = true; if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); state.sync = false; } function onwriteError(stream, state, sync, er, cb) { --state.pendingcb; if (sync) { // defer the callback if we are being called synchronously // to avoid piling up things on the stack pna.nextTick(cb, er); // this can emit finish, and it will always happen // after error pna.nextTick(finishMaybe, stream, state); stream._writableState.errorEmitted = true; stream.emit('error', er); } else { // the caller expect this to happen before if // it is async cb(er); stream._writableState.errorEmitted = true; stream.emit('error', er); // this can emit finish, but finish must // always follow error finishMaybe(stream, state); } } function onwriteStateUpdate(state) { state.writing = false; state.writecb = null; state.length -= state.writelen; state.writelen = 0; } function onwrite(stream, er) { var state = stream._writableState; var sync = state.sync; var cb = state.writecb; onwriteStateUpdate(state); if (er) onwriteError(stream, state, sync, er, cb);else { // Check if we're actually ready to finish, but don't emit yet var finished = needFinish(state); if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { clearBuffer(stream, state); } if (sync) { /**/ asyncWrite(afterWrite, stream, state, finished, cb); /**/ } else { afterWrite(stream, state, finished, cb); } } } function afterWrite(stream, state, finished, cb) { if (!finished) onwriteDrain(stream, state); state.pendingcb--; cb(); finishMaybe(stream, state); } // Must force callback to be called on nextTick, so that we don't // emit 'drain' before the write() consumer gets the 'false' return // value, and has a chance to attach a 'drain' listener. function onwriteDrain(stream, state) { if (state.length === 0 && state.needDrain) { state.needDrain = false; stream.emit('drain'); } } // if there's something in the buffer waiting, then process it function clearBuffer(stream, state) { state.bufferProcessing = true; var entry = state.bufferedRequest; if (stream._writev && entry && entry.next) { // Fast case, write everything using _writev() var l = state.bufferedRequestCount; var buffer = new Array(l); var holder = state.corkedRequestsFree; holder.entry = entry; var count = 0; var allBuffers = true; while (entry) { buffer[count] = entry; if (!entry.isBuf) allBuffers = false; entry = entry.next; count += 1; } buffer.allBuffers = allBuffers; doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time // as the hot path ends with doWrite state.pendingcb++; state.lastBufferedRequest = null; if (holder.next) { state.corkedRequestsFree = holder.next; holder.next = null; } else { state.corkedRequestsFree = new CorkedRequest(state); } state.bufferedRequestCount = 0; } else { // Slow case, write chunks one-by-one while (entry) { var chunk = entry.chunk; var encoding = entry.encoding; var cb = entry.callback; var len = state.objectMode ? 1 : chunk.length; doWrite(stream, state, false, len, chunk, encoding, cb); entry = entry.next; state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then // it means that we need to wait until it does. // also, that means that the chunk and cb are currently // being processed, so move the buffer counter past them. if (state.writing) { break; } } if (entry === null) state.lastBufferedRequest = null; } state.bufferedRequest = entry; state.bufferProcessing = false; } Writable.prototype._write = function (chunk, encoding, cb) { cb(new Error('_write() is not implemented')); }; Writable.prototype._writev = null; Writable.prototype.end = function (chunk, encoding, cb) { var state = this._writableState; if (typeof chunk === 'function') { cb = chunk; chunk = null; encoding = null; } else if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks if (state.corked) { state.corked = 1; this.uncork(); } // ignore unnecessary end() calls. if (!state.ending) endWritable(this, state, cb); }; function needFinish(state) { return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; } function callFinal(stream, state) { stream._final(function (err) { state.pendingcb--; if (err) { stream.emit('error', err); } state.prefinished = true; stream.emit('prefinish'); finishMaybe(stream, state); }); } function prefinish(stream, state) { if (!state.prefinished && !state.finalCalled) { if (typeof stream._final === 'function') { state.pendingcb++; state.finalCalled = true; pna.nextTick(callFinal, stream, state); } else { state.prefinished = true; stream.emit('prefinish'); } } } function finishMaybe(stream, state) { var need = needFinish(state); if (need) { prefinish(stream, state); if (state.pendingcb === 0) { state.finished = true; stream.emit('finish'); } } return need; } function endWritable(stream, state, cb) { state.ending = true; finishMaybe(stream, state); if (cb) { if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); } state.ended = true; stream.writable = false; } function onCorkedFinish(corkReq, state, err) { var entry = corkReq.entry; corkReq.entry = null; while (entry) { var cb = entry.callback; state.pendingcb--; cb(err); entry = entry.next; } // reuse the free corkReq. state.corkedRequestsFree.next = corkReq; } Object.defineProperty(Writable.prototype, 'destroyed', { get: function () { if (this._writableState === undefined) { return false; } return this._writableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (!this._writableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._writableState.destroyed = value; } }); Writable.prototype.destroy = destroyImpl.destroy; Writable.prototype._undestroy = destroyImpl.undestroy; Writable.prototype._destroy = function (err, cb) { this.end(); cb(err); }; /***/ }), /***/ 26528: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Buffer = __webpack_require__(89509).Buffer; var util = __webpack_require__(73837); function copyBuffer(src, target, offset) { src.copy(target, offset); } module.exports = function () { function BufferList() { _classCallCheck(this, BufferList); this.head = null; this.tail = null; this.length = 0; } BufferList.prototype.push = function push(v) { var entry = { data: v, next: null }; if (this.length > 0) this.tail.next = entry;else this.head = entry; this.tail = entry; ++this.length; }; BufferList.prototype.unshift = function unshift(v) { var entry = { data: v, next: this.head }; if (this.length === 0) this.tail = entry; this.head = entry; ++this.length; }; BufferList.prototype.shift = function shift() { if (this.length === 0) return; var ret = this.head.data; if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; --this.length; return ret; }; BufferList.prototype.clear = function clear() { this.head = this.tail = null; this.length = 0; }; BufferList.prototype.join = function join(s) { if (this.length === 0) return ''; var p = this.head; var ret = '' + p.data; while (p = p.next) { ret += s + p.data; }return ret; }; BufferList.prototype.concat = function concat(n) { if (this.length === 0) return Buffer.alloc(0); var ret = Buffer.allocUnsafe(n >>> 0); var p = this.head; var i = 0; while (p) { copyBuffer(p.data, ret, i); i += p.data.length; p = p.next; } return ret; }; return BufferList; }(); if (util && util.inspect && util.inspect.custom) { module.exports.prototype[util.inspect.custom] = function () { var obj = util.inspect({ length: this.length }); return this.constructor.name + ' ' + obj; }; } /***/ }), /***/ 35296: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /**/ var pna = __webpack_require__(88212); /**/ // undocumented cb() API, needed for core, not for public API function destroy(err, cb) { var _this = this; var readableDestroyed = this._readableState && this._readableState.destroyed; var writableDestroyed = this._writableState && this._writableState.destroyed; if (readableDestroyed || writableDestroyed) { if (cb) { cb(err); } else if (err) { if (!this._writableState) { pna.nextTick(emitErrorNT, this, err); } else if (!this._writableState.errorEmitted) { this._writableState.errorEmitted = true; pna.nextTick(emitErrorNT, this, err); } } return this; } // we set destroyed to true before firing error callbacks in order // to make it re-entrance safe in case destroy() is called within callbacks if (this._readableState) { this._readableState.destroyed = true; } // if this is a duplex stream mark the writable part as destroyed as well if (this._writableState) { this._writableState.destroyed = true; } this._destroy(err || null, function (err) { if (!cb && err) { if (!_this._writableState) { pna.nextTick(emitErrorNT, _this, err); } else if (!_this._writableState.errorEmitted) { _this._writableState.errorEmitted = true; pna.nextTick(emitErrorNT, _this, err); } } else if (cb) { cb(err); } }); return this; } function undestroy() { if (this._readableState) { this._readableState.destroyed = false; this._readableState.reading = false; this._readableState.ended = false; this._readableState.endEmitted = false; } if (this._writableState) { this._writableState.destroyed = false; this._writableState.ended = false; this._writableState.ending = false; this._writableState.finalCalled = false; this._writableState.prefinished = false; this._writableState.finished = false; this._writableState.errorEmitted = false; } } function emitErrorNT(self, err) { self.emit('error', err); } module.exports = { destroy: destroy, undestroy: undestroy }; /***/ }), /***/ 73754: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = __webpack_require__(12781); /***/ }), /***/ 79349: /***/ ((module, exports, __webpack_require__) => { var Stream = __webpack_require__(12781); if (process.env.READABLE_STREAM === 'disable' && Stream) { module.exports = Stream; exports = module.exports = Stream.Readable; exports.Readable = Stream.Readable; exports.Writable = Stream.Writable; exports.Duplex = Stream.Duplex; exports.Transform = Stream.Transform; exports.PassThrough = Stream.PassThrough; exports.Stream = Stream; } else { exports = module.exports = __webpack_require__(1372); exports.Stream = Stream || exports; exports.Readable = exports; exports.Writable = __webpack_require__(89083); exports.Duplex = __webpack_require__(15227); exports.Transform = __webpack_require__(34670); exports.PassThrough = __webpack_require__(95688); } /***/ }), /***/ 71785: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /**/ var Buffer = __webpack_require__(89509).Buffer; /**/ var isEncoding = Buffer.isEncoding || function (encoding) { encoding = '' + encoding; switch (encoding && encoding.toLowerCase()) { case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': return true; default: return false; } }; function _normalizeEncoding(enc) { if (!enc) return 'utf8'; var retried; while (true) { switch (enc) { case 'utf8': case 'utf-8': return 'utf8'; case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return 'utf16le'; case 'latin1': case 'binary': return 'latin1'; case 'base64': case 'ascii': case 'hex': return enc; default: if (retried) return; // undefined enc = ('' + enc).toLowerCase(); retried = true; } } }; // Do not cache `Buffer.isEncoding` when checking encoding names as some // modules monkey-patch it to support additional encodings function normalizeEncoding(enc) { var nenc = _normalizeEncoding(enc); if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); return nenc || enc; } // StringDecoder provides an interface for efficiently splitting a series of // buffers into a series of JS strings without breaking apart multi-byte // characters. exports.s = StringDecoder; function StringDecoder(encoding) { this.encoding = normalizeEncoding(encoding); var nb; switch (this.encoding) { case 'utf16le': this.text = utf16Text; this.end = utf16End; nb = 4; break; case 'utf8': this.fillLast = utf8FillLast; nb = 4; break; case 'base64': this.text = base64Text; this.end = base64End; nb = 3; break; default: this.write = simpleWrite; this.end = simpleEnd; return; } this.lastNeed = 0; this.lastTotal = 0; this.lastChar = Buffer.allocUnsafe(nb); } StringDecoder.prototype.write = function (buf) { if (buf.length === 0) return ''; var r; var i; if (this.lastNeed) { r = this.fillLast(buf); if (r === undefined) return ''; i = this.lastNeed; this.lastNeed = 0; } else { i = 0; } if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); return r || ''; }; StringDecoder.prototype.end = utf8End; // Returns only complete characters in a Buffer StringDecoder.prototype.text = utf8Text; // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer StringDecoder.prototype.fillLast = function (buf) { if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); this.lastNeed -= buf.length; }; // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a // continuation byte. If an invalid byte is detected, -2 is returned. function utf8CheckByte(byte) { if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; return byte >> 6 === 0x02 ? -1 : -2; } // Checks at most 3 bytes at the end of a Buffer in order to detect an // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) // needed to complete the UTF-8 character (if applicable) are returned. function utf8CheckIncomplete(self, buf, i) { var j = buf.length - 1; if (j < i) return 0; var nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 1; return nb; } if (--j < i || nb === -2) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 2; return nb; } if (--j < i || nb === -2) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) { if (nb === 2) nb = 0;else self.lastNeed = nb - 3; } return nb; } return 0; } // Validates as many continuation bytes for a multi-byte UTF-8 character as // needed or are available. If we see a non-continuation byte where we expect // one, we "replace" the validated continuation bytes we've seen so far with // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding // behavior. The continuation byte check is included three times in the case // where all of the continuation bytes for a character exist in the same buffer. // It is also done this way as a slight performance increase instead of using a // loop. function utf8CheckExtraBytes(self, buf, p) { if ((buf[0] & 0xC0) !== 0x80) { self.lastNeed = 0; return '\ufffd'; } if (self.lastNeed > 1 && buf.length > 1) { if ((buf[1] & 0xC0) !== 0x80) { self.lastNeed = 1; return '\ufffd'; } if (self.lastNeed > 2 && buf.length > 2) { if ((buf[2] & 0xC0) !== 0x80) { self.lastNeed = 2; return '\ufffd'; } } } } // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. function utf8FillLast(buf) { var p = this.lastTotal - this.lastNeed; var r = utf8CheckExtraBytes(this, buf, p); if (r !== undefined) return r; if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, p, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, p, 0, buf.length); this.lastNeed -= buf.length; } // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a // partial character, the character's bytes are buffered until the required // number of bytes are available. function utf8Text(buf, i) { var total = utf8CheckIncomplete(this, buf, i); if (!this.lastNeed) return buf.toString('utf8', i); this.lastTotal = total; var end = buf.length - (total - this.lastNeed); buf.copy(this.lastChar, 0, end); return buf.toString('utf8', i, end); } // For UTF-8, a replacement character is added when ending on a partial // character. function utf8End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + '\ufffd'; return r; } // UTF-16LE typically needs two bytes per character, but even if we have an even // number of bytes available, we need to check if we end on a leading/high // surrogate. In that case, we need to wait for the next two bytes in order to // decode the last character properly. function utf16Text(buf, i) { if ((buf.length - i) % 2 === 0) { var r = buf.toString('utf16le', i); if (r) { var c = r.charCodeAt(r.length - 1); if (c >= 0xD800 && c <= 0xDBFF) { this.lastNeed = 2; this.lastTotal = 4; this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; return r.slice(0, -1); } } return r; } this.lastNeed = 1; this.lastTotal = 2; this.lastChar[0] = buf[buf.length - 1]; return buf.toString('utf16le', i, buf.length - 1); } // For UTF-16LE we do not explicitly append special replacement characters if we // end on a partial character, we simply let v8 handle that. function utf16End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) { var end = this.lastTotal - this.lastNeed; return r + this.lastChar.toString('utf16le', 0, end); } return r; } function base64Text(buf, i) { var n = (buf.length - i) % 3; if (n === 0) return buf.toString('base64', i); this.lastNeed = 3 - n; this.lastTotal = 3; if (n === 1) { this.lastChar[0] = buf[buf.length - 1]; } else { this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; } return buf.toString('base64', i, buf.length - n); } function base64End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); return r; } // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) function simpleWrite(buf) { return buf.toString(this.encoding); } function simpleEnd(buf) { return buf && buf.length ? this.write(buf) : ''; } /***/ }), /***/ 18: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { var elfy = exports; elfy.constants = __webpack_require__(36600); elfy.Parser = __webpack_require__(29154); elfy.parse = function parse(buf) { return new elfy.Parser().execute(buf); }; /***/ }), /***/ 36600: /***/ ((__unused_webpack_module, exports) => { var constants = exports; constants.class = { 0: 'none', 1: '32', 2: '64', 3: 'num' }; constants.endian = { 0: 'none', 1: 'lsb', 2: 'msb', 3: 'num' }; constants.version = { 0: 'none', 1: 'current', 2: 'num' }; constants.osabi = { 0: 'sysv', 1: 'hpux', 2: 'netbsd', 3: 'linux', 4: 'unknown4', 5: 'unknown5', 6: 'solaris', 7: 'aix', 8: 'irix', 9: 'freebsd', 10: 'tru64', 11: 'modesto', 12: 'openbsd', 13: 'openvms', 14: 'nsk', 15: 'aros', 97: 'arm', 255: 'standalone' }; constants.abiversion = { 0: 'none', 1: 'current', 2: 'num' }; constants.machine = { 0: 'none', 1: 'm32', 2: 'sparc', 3: '386', 4: '68k', 5: '88k', 6: '486', 7: '860', 8: 'mips', 9: 's370', 10: 'mips_rs3_le', 11: 'rs6000', 12: 'unknown12', 13: 'unknown13', 14: 'unknown14', 15: 'pa_risc', 16: 'ncube', 17: 'vpp500', 18: 'sparc32plus', 19: '960', 20: 'ppc', 21: 'ppc64', 22: 's390', 23: 'unknown23', 24: 'unknown24', 25: 'unknown25', 26: 'unknown26', 27: 'unknown27', 28: 'unknown28', 29: 'unknown29', 30: 'unknown30', 31: 'unknown31', 32: 'unknown32', 33: 'unknown33', 34: 'unknown34', 35: 'unknown35', 36: 'v800', 37: 'fr20', 38: 'rh32', 39: 'rce', 40: 'arm', 41: 'alpha', 42: 'sh', 43: 'sparcv9', 44: 'tricore', 45: 'arc', 46: 'h8_300', 47: 'h8_300h', 48: 'h8s', 49: 'h8_500', 50: 'ia_64', 51: 'mips_x', 52: 'coldfire', 53: '68hc12', 54: 'mma', 55: 'pcp', 56: 'ncpu', 57: 'ndr1', 58: 'starcore', 59: 'me16', 60: 'st100', 61: 'tinyj', 62: 'amd64', 63: 'pdsp', 64: 'unknown64', 65: 'unknown65', 66: 'fx66', 67: 'st9plus', 68: 'st7', 69: '68hc16', 70: '68hc11', 71: '68hc08', 72: '68hc05', 73: 'svx', 74: 'st19', 75: 'vax', 76: 'cris', 77: 'javelin', 78: 'firepath', 79: 'zsp', 80: 'mmix', 81: 'huany', 82: 'prism', 83: 'avr', 84: 'fr30', 85: 'd10v', 86: 'd30v', 87: 'v850', 88: 'm32r', 89: 'mn10300', 90: 'mn10200', 91: 'pj', 92: 'openrisc', 93: 'arc_a5', 94: 'xtensa', 95: 'num', 183: 'AArch64' }; constants.type = { 0: 'none', 1: 'rel', 2: 'exec', 3: 'dyn', 4: 'core', 5: 'num' }; constants.entryType = { 0: 'null', 1: 'load', 2: 'dynamic', 3: 'interp', 4: 'note', 5: 'shlib', 6: 'phdr', 7: 'tls', 0x6464e550: 'sunw_unwind', 0x6474e550: 'sunw_eh_frame', 0x6474e551: 'gnu_stack', 0x6474e552: 'gnu_relro', 0x6ffffffa: 'losunw', 0x6ffffffa: 'sunwbss', 0x6ffffffb: 'sunwstack', 0x6ffffffc: 'sunwdtrace', 0x6ffffffd: 'sunwcap' }; constants.entryFlags = { 4: 'r', 2: 'w', 1: 'x', 0x00100000: 'sunw_failure', 0x00200000: 'sunw_killed', 0x00400000: 'sunw_siginfo' }; constants.sectType = { 0: 'undef', 0: 'null', 1: 'progbits', 2: 'symtab', 3: 'strtab', 4: 'rela', 5: 'hash', 6: 'dynamic', 7: 'note', 8: 'nobits', 9: 'rel', 10: 'shlib', 11: 'dynsym', 12: 'unknown12', 13: 'unknown13', 14: 'init_array', 15: 'fini_array', 16: 'preinit_array', 17: 'group', 18: 'symtab_shndx', 19: 'num', 0x60000000: 'loos', 0x6fffffef: 'sunw_capchain', 0x6ffffff0: 'sunw_capinfo', 0x6ffffff1: 'sunw_symsort', 0x6ffffff2: 'sunw_tlssort', 0x6ffffff3: 'sunw_ldynsym', 0x6ffffff4: 'sunw_dof', 0x6ffffff5: 'sunw_cap', 0x6ffffff6: 'sunw_signature', 0x6ffffff7: 'sunw_annotate', 0x6ffffff8: 'sunw_debugstr', 0x6ffffff9: 'sunw_debug', 0x6ffffffa: 'sunw_move', 0x6ffffffb: 'sunw_comdat', 0x6ffffffc: 'sunw_syminfo', 0x6ffffffd: 'sunw_verdef', 0x6ffffffe: 'sunw_verneed', 0x6fffffff: 'sunw_versym', 0x6fffffff: 'hisunw', 0x6fffffff: 'hios', 0x6ffffff5: 'gnu_attributes', 0x6ffffff6: 'gnu_hash', 0x6ffffff7: 'gnu_liblist', 0x6ffffff8: 'checksum' }; constants.sectFlags = { 0x01: 'write', 0x02: 'alloc', 0x04: 'execinstr', 0x10: 'merge', 0x20: 'strings', 0x40: 'info_link', 0x80: 'link_order', 0x100: 'os_nonconforming', 0x200: 'group', 0x400: 'tls' }; /***/ }), /***/ 29154: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var assert = __webpack_require__(39491); var util = __webpack_require__(73837); var Reader = __webpack_require__(97784); var elfy = __webpack_require__(18); var constants = elfy.constants; function Parser() { Reader.call(this); } util.inherits(Parser, Reader); module.exports = Parser; Parser.prototype.mapFlags = function mapFlags(value, map) { var res = {}; for (var bit = 1; (value < 0 || bit <= value) && bit !== 0; bit <<= 1) if (value & bit) res[map[bit] || bit] = true; return res; }; Parser.prototype.execute = function execute(buf) { if (buf.length < 16) throw new Error('Not enough bytes to parse ident'); var magic = buf.slice(0, 4).toString(); if (magic !== '\x7fELF') throw new Error('Invalid magic: ' + magic); var header = this.parseHeader(buf); header.body = this.parseBody(buf, header); header.body = this.resolveBody(header.body, header); return header; }; Parser.prototype.parseHeader = function parseHeader(buf) { var class_ = constants.class[buf[4]]; var endian = constants.endian[buf[5]]; var osabi = constants.osabi[buf[6]]; var abiversion = constants.abiversion[buf[7]]; if (class_ !== '32' && class_ !== '64') throw new Error('Invalid class: ' + class_); if (endian !== 'lsb' && endian !== 'msb') throw new Error('Invalid endian: ' + endian); this.setEndian(endian); if (class_ === '32') this.setWord(4); else this.setWord(8); if (class_ === '32') { var type = constants.type[this.readUInt16(buf, 16)]; var machine = constants.machine[this.readUInt16(buf, 18)]; var version = this.readUInt32(buf, 20); var entry = this.readUInt32(buf, 24); var phoff = this.readUInt32(buf, 28); var shoff = this.readUInt32(buf, 32); var flags = this.readUInt32(buf, 36); var ehsize = this.readUInt16(buf, 40); var phentsize = this.readUInt16(buf, 42); var phnum = this.readUInt16(buf, 44); var shentsize = this.readUInt16(buf, 46); var shnum = this.readUInt16(buf, 48); var shstrndx = this.readUInt16(buf, 50); } else { var type = constants.type[this.readUInt16(buf, 16)]; var machine = constants.machine[this.readUInt16(buf, 18)]; var version = this.readUInt32(buf, 20); var entry = this.readUInt64(buf, 24); var phoff = this.readUInt64(buf, 32); var shoff = this.readUInt64(buf, 40); var flags = this.readUInt32(buf, 48); var ehsize = this.readUInt16(buf, 52); var phentsize = this.readUInt16(buf, 54); var phnum = this.readUInt16(buf, 56); var shentsize = this.readUInt16(buf, 58); var shnum = this.readUInt16(buf, 60); var shstrndx = this.readUInt16(buf, 62); } return { class: class_, endian: endian, version: buf[7], osabi: osabi, abiversion: abiversion, type: type, machine: machine, version: version, entry: entry, phoff: phoff, shoff: shoff, flags: flags, ehsize: ehsize, phentsize: phentsize, phnum: phnum, shentsize: shentsize, shnum: shnum, shstrndx: shstrndx }; }; Parser.prototype.parseBody = function parseBody(buf, header) { return { programs: this.parsePrograms(buf, header), sections: this.parseSections(buf, header) }; }; Parser.prototype.sliceChunks = function sliceChunks(buf, off, count, size) { var start = off; var end = start + count * size; if (end > buf.length) throw new Error('Failed to slice chunks'); var chunks = []; for (var off = start; off < end; off += size) chunks.push(buf.slice(off, off + size)); return chunks; }; Parser.prototype.parsePrograms = function parsePrograms(buf, header) { if (header.phoff === 0 || header.phnum === 0) return []; var programs = this.sliceChunks(buf, header.phoff, header.phnum, header.phentsize); return programs.map(function(program) { return this.parseProgram(program, header, buf); }, this); }; Parser.prototype.parseProgram = function parseProgram(ent, header, buf) { var type = constants.entryType[this.readUInt32(ent, 0)]; if (header.class === '32') { var offset = this.readUInt32(ent, 4); var vaddr = this.readUInt32(ent, 8); var paddr = this.readUInt32(ent, 12); var filesz = this.readUInt32(ent, 16); var memsz = this.readUInt32(ent, 20); var flags = this.readUInt32(ent, 24); var align = this.readUInt32(ent, 28); } else { var flags = this.readUInt32(ent, 4); var offset = this.readUInt64(ent, 8); var vaddr = this.readUInt64(ent, 16); var paddr = this.readUInt64(ent, 24); var filesz = this.readUInt64(ent, 32); var memsz = this.readUInt64(ent, 40); var align = this.readUInt64(ent, 48); } return { type: type, offset: offset, vaddr: vaddr, paddr: paddr, filesz: filesz, memsz: memsz, flags: this.mapFlags(flags, constants.entryFlags), align: align, data: buf.slice(offset, offset + filesz) }; }; Parser.prototype.parseSections = function parseSections(buf, header) { if (header.shoff === 0 || header.shnum === 0) return []; var sections = this.sliceChunks(buf, header.shoff, header.shnum, header.shentsize); return sections.map(function(section) { return this.parseSection(section, header, buf); }, this); }; Parser.prototype.parseSection = function parseSection(section, header, buf) { var name = this.readUInt32(section, 0); var type = this.readUInt32(section, 4); if (header.class === '32') { var flags = this.readUInt32(section, 8); var addr = this.readUInt32(section, 12); var off = this.readUInt32(section, 16); var size = this.readUInt32(section, 20); var link = this.readUInt32(section, 24); var info = this.readUInt32(section, 28); var addralign = this.readUInt32(section, 32); var entsize = this.readUInt32(section, 36); } else { var flags = this.readUInt64(section, 8); var addr = this.readUInt64(section, 16); var off = this.readUInt64(section, 24); var size = this.readUInt64(section, 32); var link = this.readUInt32(section, 40); var info = this.readUInt32(section, 44); var addralign = this.readUInt64(section, 46); var entsize = this.readUInt64(section, 54); } return { name: name, type: constants.sectType[type] || type, flags: this.mapFlags(flags, constants.sectFlags), addr: addr, off: off, size: size, link: link, info: info, addralign: addralign, entsize: entsize, data: buf.slice(off, off + size) }; }; Parser.prototype.resolveStr = function resolveStr(strtab, off) { for (var i = off; i < strtab.length && strtab[i] != 0; i++); return strtab.slice(off, i).toString(); }; Parser.prototype.resolveBody = function resolveBody(body, header) { var strtab = body.sections[header.shstrndx]; assert.equal(strtab.type, 'strtab'); return { programs: body.programs, sections: body.sections.map(function(section) { section.name = this.resolveStr(strtab.data, section.name); return section; }, this) }; }; /***/ }), /***/ 12346: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const assert = __webpack_require__(39491) const { URL } = __webpack_require__(57310) const mem = __webpack_require__(10956) module.exports = mem(encodeRegistry) function encodeRegistry (registry) { assert(registry, '`registry` is required') assert(typeof registry === 'string', '`registry` should be a string') const host = getHost(registry) return escapeHost(host) } function escapeHost (host) { return host.replace(':', '+') } function getHost (rawUrl) { let urlObj try { urlObj = new URL(rawUrl) } catch (err) { throw new Error(`Failed to parse registry URL "${rawUrl}": ${err.message}`) } if (!urlObj || !urlObj.host) { throw new Error(`Couldn't get host from ${rawUrl}`) } return urlObj.host } /***/ }), /***/ 12840: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var once = __webpack_require__(30778); var noop = function() {}; var isRequest = function(stream) { return stream.setHeader && typeof stream.abort === 'function'; }; var isChildProcess = function(stream) { return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 }; var eos = function(stream, opts, callback) { if (typeof opts === 'function') return eos(stream, null, opts); if (!opts) opts = {}; callback = once(callback || noop); var ws = stream._writableState; var rs = stream._readableState; var readable = opts.readable || (opts.readable !== false && stream.readable); var writable = opts.writable || (opts.writable !== false && stream.writable); var cancelled = false; var onlegacyfinish = function() { if (!stream.writable) onfinish(); }; var onfinish = function() { writable = false; if (!readable) callback.call(stream); }; var onend = function() { readable = false; if (!writable) callback.call(stream); }; var onexit = function(exitCode) { callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); }; var onerror = function(err) { callback.call(stream, err); }; var onclose = function() { process.nextTick(onclosenexttick); }; var onclosenexttick = function() { if (cancelled) return; if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close')); if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close')); }; var onrequest = function() { stream.req.on('finish', onfinish); }; if (isRequest(stream)) { stream.on('complete', onfinish); stream.on('abort', onclose); if (stream.req) onrequest(); else stream.on('request', onrequest); } else if (writable && !ws) { // legacy streams stream.on('end', onlegacyfinish); stream.on('close', onlegacyfinish); } if (isChildProcess(stream)) stream.on('exit', onexit); stream.on('end', onend); stream.on('finish', onfinish); if (opts.error !== false) stream.on('error', onerror); stream.on('close', onclose); return function() { cancelled = true; stream.removeListener('complete', onfinish); stream.removeListener('abort', onclose); stream.removeListener('request', onrequest); if (stream.req) stream.req.removeListener('finish', onfinish); stream.removeListener('end', onlegacyfinish); stream.removeListener('close', onlegacyfinish); stream.removeListener('finish', onfinish); stream.removeListener('exit', onexit); stream.removeListener('end', onend); stream.removeListener('error', onerror); stream.removeListener('close', onclose); }; }; module.exports = eos; /***/ }), /***/ 97784: /***/ ((module) => { function Reader(endian, word) { this.endian = null; this.word = 4; if (endian) this.setEndian(endian); if (word) this.setWord(word); }; module.exports = Reader; Reader.prototype.setEndian = function setEndian(endian) { this.endian = /le|lsb|little/i.test(endian) ? 'le' : 'be'; }; Reader.prototype.setWord = function setWord(word) { this.word = word; }; Reader.prototype.readUInt8 = function readUInt8(buf, offset) { return buf.readUInt8(offset); }; Reader.prototype.readInt8 = function readInt8(buf, offset) { return buf.readInt8(offset); }; Reader.prototype.readUInt16 = function readUInt16(buf, offset) { if (this.endian === 'le') return buf.readUInt16LE(offset); else return buf.readUInt16BE(offset); }; Reader.prototype.readInt16 = function readInt16(buf, offset) { if (this.endian === 'le') return buf.readInt16LE(offset); else return buf.readInt16BE(offset); }; Reader.prototype.readUInt32 = function readUInt32(buf, offset) { if (this.endian === 'le') return buf.readUInt32LE(offset); else return buf.readUInt32BE(offset); }; Reader.prototype.readInt32 = function readInt32(buf, offset) { if (this.endian === 'le') return buf.readInt32LE(offset); else return buf.readInt32BE(offset); }; Reader.prototype.readUInt64 = function readUInt64(buf, offset) { var a = this.readUInt32(buf, offset); var b = this.readUInt32(buf, offset + 4); if (this.endian === 'le') return a + b * 0x100000000; else return b + a * 0x100000000; }; Reader.prototype.readInt64 = function readInt64(buf, offset) { if (this.endian === 'le') { var a = this.readUInt32(buf, offset); var b = this.readInt32(buf, offset + 4); return a + b * 0x100000000; } else { var a = this.readInt32(buf, offset); var b = this.readUInt32(buf, offset + 4); return b + a * 0x100000000; } }; Reader.prototype.readHalf = function readHalf(buf, offset) { if (this.word === 2) return this.readInt8(buf, offset); else if (this.word === 4) return this.readInt16(buf, offset); else return this.readInt32(buf, offset); }; Reader.prototype.readUHalf = function readUHalf(buf, offset) { if (this.word === 2) return this.readUInt8(buf, offset); else if (this.word === 4) return this.readUInt16(buf, offset); else return this.readUInt32(buf, offset); }; Reader.prototype.readWord = function readWord(buf, offset) { if (this.word === 1) return this.readInt8(buf, offset); else if (this.word === 2) return this.readInt16(buf, offset); else if (this.word === 4) return this.readInt32(buf, offset); else return this.readInt64(buf, offset); }; Reader.prototype.readUWord = function readUWord(buf, offset) { if (this.word === 1) return this.readUInt8(buf, offset); else if (this.word === 2) return this.readUInt16(buf, offset); else if (this.word === 4) return this.readUInt32(buf, offset); else return this.readUInt64(buf, offset); }; /***/ }), /***/ 31072: /***/ (function(module) { (function webpackUniversalModuleDefinition(root, factory) { /* istanbul ignore next */ if(true) module.exports = factory(); else {} })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __nested_webpack_require_583__(moduleId) { /******/ // Check if module is in cache /* istanbul ignore if */ /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __nested_webpack_require_583__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __nested_webpack_require_583__.m = modules; /******/ // expose the module cache /******/ __nested_webpack_require_583__.c = installedModules; /******/ // __webpack_public_path__ /******/ __nested_webpack_require_583__.p = ""; /******/ // Load entry module and return exports /******/ return __nested_webpack_require_583__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __nested_webpack_require_1808__) { "use strict"; /* Copyright JS Foundation and other contributors, https://js.foundation/ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ Object.defineProperty(exports, "__esModule", { value: true }); var comment_handler_1 = __nested_webpack_require_1808__(1); var jsx_parser_1 = __nested_webpack_require_1808__(3); var parser_1 = __nested_webpack_require_1808__(8); var tokenizer_1 = __nested_webpack_require_1808__(15); function parse(code, options, delegate) { var commentHandler = null; var proxyDelegate = function (node, metadata) { if (delegate) { delegate(node, metadata); } if (commentHandler) { commentHandler.visit(node, metadata); } }; var parserDelegate = (typeof delegate === 'function') ? proxyDelegate : null; var collectComment = false; if (options) { collectComment = (typeof options.comment === 'boolean' && options.comment); var attachComment = (typeof options.attachComment === 'boolean' && options.attachComment); if (collectComment || attachComment) { commentHandler = new comment_handler_1.CommentHandler(); commentHandler.attach = attachComment; options.comment = true; parserDelegate = proxyDelegate; } } var isModule = false; if (options && typeof options.sourceType === 'string') { isModule = (options.sourceType === 'module'); } var parser; if (options && typeof options.jsx === 'boolean' && options.jsx) { parser = new jsx_parser_1.JSXParser(code, options, parserDelegate); } else { parser = new parser_1.Parser(code, options, parserDelegate); } var program = isModule ? parser.parseModule() : parser.parseScript(); var ast = program; if (collectComment && commentHandler) { ast.comments = commentHandler.comments; } if (parser.config.tokens) { ast.tokens = parser.tokens; } if (parser.config.tolerant) { ast.errors = parser.errorHandler.errors; } return ast; } exports.parse = parse; function parseModule(code, options, delegate) { var parsingOptions = options || {}; parsingOptions.sourceType = 'module'; return parse(code, parsingOptions, delegate); } exports.parseModule = parseModule; function parseScript(code, options, delegate) { var parsingOptions = options || {}; parsingOptions.sourceType = 'script'; return parse(code, parsingOptions, delegate); } exports.parseScript = parseScript; function tokenize(code, options, delegate) { var tokenizer = new tokenizer_1.Tokenizer(code, options); var tokens; tokens = []; try { while (true) { var token = tokenizer.getNextToken(); if (!token) { break; } if (delegate) { token = delegate(token); } tokens.push(token); } } catch (e) { tokenizer.errorHandler.tolerate(e); } if (tokenizer.errorHandler.tolerant) { tokens.errors = tokenizer.errors(); } return tokens; } exports.tokenize = tokenize; var syntax_1 = __nested_webpack_require_1808__(2); exports.Syntax = syntax_1.Syntax; // Sync with *.json manifests. exports.version = '4.0.1'; /***/ }, /* 1 */ /***/ function(module, exports, __nested_webpack_require_6456__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var syntax_1 = __nested_webpack_require_6456__(2); var CommentHandler = (function () { function CommentHandler() { this.attach = false; this.comments = []; this.stack = []; this.leading = []; this.trailing = []; } CommentHandler.prototype.insertInnerComments = function (node, metadata) { // innnerComments for properties empty block // `function a() {/** comments **\/}` if (node.type === syntax_1.Syntax.BlockStatement && node.body.length === 0) { var innerComments = []; for (var i = this.leading.length - 1; i >= 0; --i) { var entry = this.leading[i]; if (metadata.end.offset >= entry.start) { innerComments.unshift(entry.comment); this.leading.splice(i, 1); this.trailing.splice(i, 1); } } if (innerComments.length) { node.innerComments = innerComments; } } }; CommentHandler.prototype.findTrailingComments = function (metadata) { var trailingComments = []; if (this.trailing.length > 0) { for (var i = this.trailing.length - 1; i >= 0; --i) { var entry_1 = this.trailing[i]; if (entry_1.start >= metadata.end.offset) { trailingComments.unshift(entry_1.comment); } } this.trailing.length = 0; return trailingComments; } var entry = this.stack[this.stack.length - 1]; if (entry && entry.node.trailingComments) { var firstComment = entry.node.trailingComments[0]; if (firstComment && firstComment.range[0] >= metadata.end.offset) { trailingComments = entry.node.trailingComments; delete entry.node.trailingComments; } } return trailingComments; }; CommentHandler.prototype.findLeadingComments = function (metadata) { var leadingComments = []; var target; while (this.stack.length > 0) { var entry = this.stack[this.stack.length - 1]; if (entry && entry.start >= metadata.start.offset) { target = entry.node; this.stack.pop(); } else { break; } } if (target) { var count = target.leadingComments ? target.leadingComments.length : 0; for (var i = count - 1; i >= 0; --i) { var comment = target.leadingComments[i]; if (comment.range[1] <= metadata.start.offset) { leadingComments.unshift(comment); target.leadingComments.splice(i, 1); } } if (target.leadingComments && target.leadingComments.length === 0) { delete target.leadingComments; } return leadingComments; } for (var i = this.leading.length - 1; i >= 0; --i) { var entry = this.leading[i]; if (entry.start <= metadata.start.offset) { leadingComments.unshift(entry.comment); this.leading.splice(i, 1); } } return leadingComments; }; CommentHandler.prototype.visitNode = function (node, metadata) { if (node.type === syntax_1.Syntax.Program && node.body.length > 0) { return; } this.insertInnerComments(node, metadata); var trailingComments = this.findTrailingComments(metadata); var leadingComments = this.findLeadingComments(metadata); if (leadingComments.length > 0) { node.leadingComments = leadingComments; } if (trailingComments.length > 0) { node.trailingComments = trailingComments; } this.stack.push({ node: node, start: metadata.start.offset }); }; CommentHandler.prototype.visitComment = function (node, metadata) { var type = (node.type[0] === 'L') ? 'Line' : 'Block'; var comment = { type: type, value: node.value }; if (node.range) { comment.range = node.range; } if (node.loc) { comment.loc = node.loc; } this.comments.push(comment); if (this.attach) { var entry = { comment: { type: type, value: node.value, range: [metadata.start.offset, metadata.end.offset] }, start: metadata.start.offset }; if (node.loc) { entry.comment.loc = node.loc; } node.type = type; this.leading.push(entry); this.trailing.push(entry); } }; CommentHandler.prototype.visit = function (node, metadata) { if (node.type === 'LineComment') { this.visitComment(node, metadata); } else if (node.type === 'BlockComment') { this.visitComment(node, metadata); } else if (this.attach) { this.visitNode(node, metadata); } }; return CommentHandler; }()); exports.CommentHandler = CommentHandler; /***/ }, /* 2 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Syntax = { AssignmentExpression: 'AssignmentExpression', AssignmentPattern: 'AssignmentPattern', ArrayExpression: 'ArrayExpression', ArrayPattern: 'ArrayPattern', ArrowFunctionExpression: 'ArrowFunctionExpression', AwaitExpression: 'AwaitExpression', BlockStatement: 'BlockStatement', BinaryExpression: 'BinaryExpression', BreakStatement: 'BreakStatement', CallExpression: 'CallExpression', CatchClause: 'CatchClause', ClassBody: 'ClassBody', ClassDeclaration: 'ClassDeclaration', ClassExpression: 'ClassExpression', ConditionalExpression: 'ConditionalExpression', ContinueStatement: 'ContinueStatement', DoWhileStatement: 'DoWhileStatement', DebuggerStatement: 'DebuggerStatement', EmptyStatement: 'EmptyStatement', ExportAllDeclaration: 'ExportAllDeclaration', ExportDefaultDeclaration: 'ExportDefaultDeclaration', ExportNamedDeclaration: 'ExportNamedDeclaration', ExportSpecifier: 'ExportSpecifier', ExpressionStatement: 'ExpressionStatement', ForStatement: 'ForStatement', ForOfStatement: 'ForOfStatement', ForInStatement: 'ForInStatement', FunctionDeclaration: 'FunctionDeclaration', FunctionExpression: 'FunctionExpression', Identifier: 'Identifier', IfStatement: 'IfStatement', ImportDeclaration: 'ImportDeclaration', ImportDefaultSpecifier: 'ImportDefaultSpecifier', ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', ImportSpecifier: 'ImportSpecifier', Literal: 'Literal', LabeledStatement: 'LabeledStatement', LogicalExpression: 'LogicalExpression', MemberExpression: 'MemberExpression', MetaProperty: 'MetaProperty', MethodDefinition: 'MethodDefinition', NewExpression: 'NewExpression', ObjectExpression: 'ObjectExpression', ObjectPattern: 'ObjectPattern', Program: 'Program', Property: 'Property', RestElement: 'RestElement', ReturnStatement: 'ReturnStatement', SequenceExpression: 'SequenceExpression', SpreadElement: 'SpreadElement', Super: 'Super', SwitchCase: 'SwitchCase', SwitchStatement: 'SwitchStatement', TaggedTemplateExpression: 'TaggedTemplateExpression', TemplateElement: 'TemplateElement', TemplateLiteral: 'TemplateLiteral', ThisExpression: 'ThisExpression', ThrowStatement: 'ThrowStatement', TryStatement: 'TryStatement', UnaryExpression: 'UnaryExpression', UpdateExpression: 'UpdateExpression', VariableDeclaration: 'VariableDeclaration', VariableDeclarator: 'VariableDeclarator', WhileStatement: 'WhileStatement', WithStatement: 'WithStatement', YieldExpression: 'YieldExpression' }; /***/ }, /* 3 */ /***/ function(module, exports, __nested_webpack_require_15019__) { "use strict"; /* istanbul ignore next */ var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var character_1 = __nested_webpack_require_15019__(4); var JSXNode = __nested_webpack_require_15019__(5); var jsx_syntax_1 = __nested_webpack_require_15019__(6); var Node = __nested_webpack_require_15019__(7); var parser_1 = __nested_webpack_require_15019__(8); var token_1 = __nested_webpack_require_15019__(13); var xhtml_entities_1 = __nested_webpack_require_15019__(14); token_1.TokenName[100 /* Identifier */] = 'JSXIdentifier'; token_1.TokenName[101 /* Text */] = 'JSXText'; // Fully qualified element name, e.g. returns "svg:path" function getQualifiedElementName(elementName) { var qualifiedName; switch (elementName.type) { case jsx_syntax_1.JSXSyntax.JSXIdentifier: var id = elementName; qualifiedName = id.name; break; case jsx_syntax_1.JSXSyntax.JSXNamespacedName: var ns = elementName; qualifiedName = getQualifiedElementName(ns.namespace) + ':' + getQualifiedElementName(ns.name); break; case jsx_syntax_1.JSXSyntax.JSXMemberExpression: var expr = elementName; qualifiedName = getQualifiedElementName(expr.object) + '.' + getQualifiedElementName(expr.property); break; /* istanbul ignore next */ default: break; } return qualifiedName; } var JSXParser = (function (_super) { __extends(JSXParser, _super); function JSXParser(code, options, delegate) { return _super.call(this, code, options, delegate) || this; } JSXParser.prototype.parsePrimaryExpression = function () { return this.match('<') ? this.parseJSXRoot() : _super.prototype.parsePrimaryExpression.call(this); }; JSXParser.prototype.startJSX = function () { // Unwind the scanner before the lookahead token. this.scanner.index = this.startMarker.index; this.scanner.lineNumber = this.startMarker.line; this.scanner.lineStart = this.startMarker.index - this.startMarker.column; }; JSXParser.prototype.finishJSX = function () { // Prime the next lookahead. this.nextToken(); }; JSXParser.prototype.reenterJSX = function () { this.startJSX(); this.expectJSX('}'); // Pop the closing '}' added from the lookahead. if (this.config.tokens) { this.tokens.pop(); } }; JSXParser.prototype.createJSXNode = function () { this.collectComments(); return { index: this.scanner.index, line: this.scanner.lineNumber, column: this.scanner.index - this.scanner.lineStart }; }; JSXParser.prototype.createJSXChildNode = function () { return { index: this.scanner.index, line: this.scanner.lineNumber, column: this.scanner.index - this.scanner.lineStart }; }; JSXParser.prototype.scanXHTMLEntity = function (quote) { var result = '&'; var valid = true; var terminated = false; var numeric = false; var hex = false; while (!this.scanner.eof() && valid && !terminated) { var ch = this.scanner.source[this.scanner.index]; if (ch === quote) { break; } terminated = (ch === ';'); result += ch; ++this.scanner.index; if (!terminated) { switch (result.length) { case 2: // e.g. '{' numeric = (ch === '#'); break; case 3: if (numeric) { // e.g. 'A' hex = (ch === 'x'); valid = hex || character_1.Character.isDecimalDigit(ch.charCodeAt(0)); numeric = numeric && !hex; } break; default: valid = valid && !(numeric && !character_1.Character.isDecimalDigit(ch.charCodeAt(0))); valid = valid && !(hex && !character_1.Character.isHexDigit(ch.charCodeAt(0))); break; } } } if (valid && terminated && result.length > 2) { // e.g. 'A' becomes just '#x41' var str = result.substr(1, result.length - 2); if (numeric && str.length > 1) { result = String.fromCharCode(parseInt(str.substr(1), 10)); } else if (hex && str.length > 2) { result = String.fromCharCode(parseInt('0' + str.substr(1), 16)); } else if (!numeric && !hex && xhtml_entities_1.XHTMLEntities[str]) { result = xhtml_entities_1.XHTMLEntities[str]; } } return result; }; // Scan the next JSX token. This replaces Scanner#lex when in JSX mode. JSXParser.prototype.lexJSX = function () { var cp = this.scanner.source.charCodeAt(this.scanner.index); // < > / : = { } if (cp === 60 || cp === 62 || cp === 47 || cp === 58 || cp === 61 || cp === 123 || cp === 125) { var value = this.scanner.source[this.scanner.index++]; return { type: 7 /* Punctuator */, value: value, lineNumber: this.scanner.lineNumber, lineStart: this.scanner.lineStart, start: this.scanner.index - 1, end: this.scanner.index }; } // " ' if (cp === 34 || cp === 39) { var start = this.scanner.index; var quote = this.scanner.source[this.scanner.index++]; var str = ''; while (!this.scanner.eof()) { var ch = this.scanner.source[this.scanner.index++]; if (ch === quote) { break; } else if (ch === '&') { str += this.scanXHTMLEntity(quote); } else { str += ch; } } return { type: 8 /* StringLiteral */, value: str, lineNumber: this.scanner.lineNumber, lineStart: this.scanner.lineStart, start: start, end: this.scanner.index }; } // ... or . if (cp === 46) { var n1 = this.scanner.source.charCodeAt(this.scanner.index + 1); var n2 = this.scanner.source.charCodeAt(this.scanner.index + 2); var value = (n1 === 46 && n2 === 46) ? '...' : '.'; var start = this.scanner.index; this.scanner.index += value.length; return { type: 7 /* Punctuator */, value: value, lineNumber: this.scanner.lineNumber, lineStart: this.scanner.lineStart, start: start, end: this.scanner.index }; } // ` if (cp === 96) { // Only placeholder, since it will be rescanned as a real assignment expression. return { type: 10 /* Template */, value: '', lineNumber: this.scanner.lineNumber, lineStart: this.scanner.lineStart, start: this.scanner.index, end: this.scanner.index }; } // Identifer can not contain backslash (char code 92). if (character_1.Character.isIdentifierStart(cp) && (cp !== 92)) { var start = this.scanner.index; ++this.scanner.index; while (!this.scanner.eof()) { var ch = this.scanner.source.charCodeAt(this.scanner.index); if (character_1.Character.isIdentifierPart(ch) && (ch !== 92)) { ++this.scanner.index; } else if (ch === 45) { // Hyphen (char code 45) can be part of an identifier. ++this.scanner.index; } else { break; } } var id = this.scanner.source.slice(start, this.scanner.index); return { type: 100 /* Identifier */, value: id, lineNumber: this.scanner.lineNumber, lineStart: this.scanner.lineStart, start: start, end: this.scanner.index }; } return this.scanner.lex(); }; JSXParser.prototype.nextJSXToken = function () { this.collectComments(); this.startMarker.index = this.scanner.index; this.startMarker.line = this.scanner.lineNumber; this.startMarker.column = this.scanner.index - this.scanner.lineStart; var token = this.lexJSX(); this.lastMarker.index = this.scanner.index; this.lastMarker.line = this.scanner.lineNumber; this.lastMarker.column = this.scanner.index - this.scanner.lineStart; if (this.config.tokens) { this.tokens.push(this.convertToken(token)); } return token; }; JSXParser.prototype.nextJSXText = function () { this.startMarker.index = this.scanner.index; this.startMarker.line = this.scanner.lineNumber; this.startMarker.column = this.scanner.index - this.scanner.lineStart; var start = this.scanner.index; var text = ''; while (!this.scanner.eof()) { var ch = this.scanner.source[this.scanner.index]; if (ch === '{' || ch === '<') { break; } ++this.scanner.index; text += ch; if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { ++this.scanner.lineNumber; if (ch === '\r' && this.scanner.source[this.scanner.index] === '\n') { ++this.scanner.index; } this.scanner.lineStart = this.scanner.index; } } this.lastMarker.index = this.scanner.index; this.lastMarker.line = this.scanner.lineNumber; this.lastMarker.column = this.scanner.index - this.scanner.lineStart; var token = { type: 101 /* Text */, value: text, lineNumber: this.scanner.lineNumber, lineStart: this.scanner.lineStart, start: start, end: this.scanner.index }; if ((text.length > 0) && this.config.tokens) { this.tokens.push(this.convertToken(token)); } return token; }; JSXParser.prototype.peekJSXToken = function () { var state = this.scanner.saveState(); this.scanner.scanComments(); var next = this.lexJSX(); this.scanner.restoreState(state); return next; }; // Expect the next JSX token to match the specified punctuator. // If not, an exception will be thrown. JSXParser.prototype.expectJSX = function (value) { var token = this.nextJSXToken(); if (token.type !== 7 /* Punctuator */ || token.value !== value) { this.throwUnexpectedToken(token); } }; // Return true if the next JSX token matches the specified punctuator. JSXParser.prototype.matchJSX = function (value) { var next = this.peekJSXToken(); return next.type === 7 /* Punctuator */ && next.value === value; }; JSXParser.prototype.parseJSXIdentifier = function () { var node = this.createJSXNode(); var token = this.nextJSXToken(); if (token.type !== 100 /* Identifier */) { this.throwUnexpectedToken(token); } return this.finalize(node, new JSXNode.JSXIdentifier(token.value)); }; JSXParser.prototype.parseJSXElementName = function () { var node = this.createJSXNode(); var elementName = this.parseJSXIdentifier(); if (this.matchJSX(':')) { var namespace = elementName; this.expectJSX(':'); var name_1 = this.parseJSXIdentifier(); elementName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_1)); } else if (this.matchJSX('.')) { while (this.matchJSX('.')) { var object = elementName; this.expectJSX('.'); var property = this.parseJSXIdentifier(); elementName = this.finalize(node, new JSXNode.JSXMemberExpression(object, property)); } } return elementName; }; JSXParser.prototype.parseJSXAttributeName = function () { var node = this.createJSXNode(); var attributeName; var identifier = this.parseJSXIdentifier(); if (this.matchJSX(':')) { var namespace = identifier; this.expectJSX(':'); var name_2 = this.parseJSXIdentifier(); attributeName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_2)); } else { attributeName = identifier; } return attributeName; }; JSXParser.prototype.parseJSXStringLiteralAttribute = function () { var node = this.createJSXNode(); var token = this.nextJSXToken(); if (token.type !== 8 /* StringLiteral */) { this.throwUnexpectedToken(token); } var raw = this.getTokenRaw(token); return this.finalize(node, new Node.Literal(token.value, raw)); }; JSXParser.prototype.parseJSXExpressionAttribute = function () { var node = this.createJSXNode(); this.expectJSX('{'); this.finishJSX(); if (this.match('}')) { this.tolerateError('JSX attributes must only be assigned a non-empty expression'); } var expression = this.parseAssignmentExpression(); this.reenterJSX(); return this.finalize(node, new JSXNode.JSXExpressionContainer(expression)); }; JSXParser.prototype.parseJSXAttributeValue = function () { return this.matchJSX('{') ? this.parseJSXExpressionAttribute() : this.matchJSX('<') ? this.parseJSXElement() : this.parseJSXStringLiteralAttribute(); }; JSXParser.prototype.parseJSXNameValueAttribute = function () { var node = this.createJSXNode(); var name = this.parseJSXAttributeName(); var value = null; if (this.matchJSX('=')) { this.expectJSX('='); value = this.parseJSXAttributeValue(); } return this.finalize(node, new JSXNode.JSXAttribute(name, value)); }; JSXParser.prototype.parseJSXSpreadAttribute = function () { var node = this.createJSXNode(); this.expectJSX('{'); this.expectJSX('...'); this.finishJSX(); var argument = this.parseAssignmentExpression(); this.reenterJSX(); return this.finalize(node, new JSXNode.JSXSpreadAttribute(argument)); }; JSXParser.prototype.parseJSXAttributes = function () { var attributes = []; while (!this.matchJSX('/') && !this.matchJSX('>')) { var attribute = this.matchJSX('{') ? this.parseJSXSpreadAttribute() : this.parseJSXNameValueAttribute(); attributes.push(attribute); } return attributes; }; JSXParser.prototype.parseJSXOpeningElement = function () { var node = this.createJSXNode(); this.expectJSX('<'); var name = this.parseJSXElementName(); var attributes = this.parseJSXAttributes(); var selfClosing = this.matchJSX('/'); if (selfClosing) { this.expectJSX('/'); } this.expectJSX('>'); return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes)); }; JSXParser.prototype.parseJSXBoundaryElement = function () { var node = this.createJSXNode(); this.expectJSX('<'); if (this.matchJSX('/')) { this.expectJSX('/'); var name_3 = this.parseJSXElementName(); this.expectJSX('>'); return this.finalize(node, new JSXNode.JSXClosingElement(name_3)); } var name = this.parseJSXElementName(); var attributes = this.parseJSXAttributes(); var selfClosing = this.matchJSX('/'); if (selfClosing) { this.expectJSX('/'); } this.expectJSX('>'); return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes)); }; JSXParser.prototype.parseJSXEmptyExpression = function () { var node = this.createJSXChildNode(); this.collectComments(); this.lastMarker.index = this.scanner.index; this.lastMarker.line = this.scanner.lineNumber; this.lastMarker.column = this.scanner.index - this.scanner.lineStart; return this.finalize(node, new JSXNode.JSXEmptyExpression()); }; JSXParser.prototype.parseJSXExpressionContainer = function () { var node = this.createJSXNode(); this.expectJSX('{'); var expression; if (this.matchJSX('}')) { expression = this.parseJSXEmptyExpression(); this.expectJSX('}'); } else { this.finishJSX(); expression = this.parseAssignmentExpression(); this.reenterJSX(); } return this.finalize(node, new JSXNode.JSXExpressionContainer(expression)); }; JSXParser.prototype.parseJSXChildren = function () { var children = []; while (!this.scanner.eof()) { var node = this.createJSXChildNode(); var token = this.nextJSXText(); if (token.start < token.end) { var raw = this.getTokenRaw(token); var child = this.finalize(node, new JSXNode.JSXText(token.value, raw)); children.push(child); } if (this.scanner.source[this.scanner.index] === '{') { var container = this.parseJSXExpressionContainer(); children.push(container); } else { break; } } return children; }; JSXParser.prototype.parseComplexJSXElement = function (el) { var stack = []; while (!this.scanner.eof()) { el.children = el.children.concat(this.parseJSXChildren()); var node = this.createJSXChildNode(); var element = this.parseJSXBoundaryElement(); if (element.type === jsx_syntax_1.JSXSyntax.JSXOpeningElement) { var opening = element; if (opening.selfClosing) { var child = this.finalize(node, new JSXNode.JSXElement(opening, [], null)); el.children.push(child); } else { stack.push(el); el = { node: node, opening: opening, closing: null, children: [] }; } } if (element.type === jsx_syntax_1.JSXSyntax.JSXClosingElement) { el.closing = element; var open_1 = getQualifiedElementName(el.opening.name); var close_1 = getQualifiedElementName(el.closing.name); if (open_1 !== close_1) { this.tolerateError('Expected corresponding JSX closing tag for %0', open_1); } if (stack.length > 0) { var child = this.finalize(el.node, new JSXNode.JSXElement(el.opening, el.children, el.closing)); el = stack[stack.length - 1]; el.children.push(child); stack.pop(); } else { break; } } } return el; }; JSXParser.prototype.parseJSXElement = function () { var node = this.createJSXNode(); var opening = this.parseJSXOpeningElement(); var children = []; var closing = null; if (!opening.selfClosing) { var el = this.parseComplexJSXElement({ node: node, opening: opening, closing: closing, children: children }); children = el.children; closing = el.closing; } return this.finalize(node, new JSXNode.JSXElement(opening, children, closing)); }; JSXParser.prototype.parseJSXRoot = function () { // Pop the opening '<' added from the lookahead. if (this.config.tokens) { this.tokens.pop(); } this.startJSX(); var element = this.parseJSXElement(); this.finishJSX(); return element; }; JSXParser.prototype.isStartOfExpression = function () { return _super.prototype.isStartOfExpression.call(this) || this.match('<'); }; return JSXParser; }(parser_1.Parser)); exports.JSXParser = JSXParser; /***/ }, /* 4 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // See also tools/generate-unicode-regex.js. var Regex = { // Unicode v8.0.0 NonAsciiIdentifierStart: NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/, // Unicode v8.0.0 NonAsciiIdentifierPart: NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ }; exports.Character = { /* tslint:disable:no-bitwise */ fromCodePoint: function (cp) { return (cp < 0x10000) ? String.fromCharCode(cp) : String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) + String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023)); }, // https://tc39.github.io/ecma262/#sec-white-space isWhiteSpace: function (cp) { return (cp === 0x20) || (cp === 0x09) || (cp === 0x0B) || (cp === 0x0C) || (cp === 0xA0) || (cp >= 0x1680 && [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(cp) >= 0); }, // https://tc39.github.io/ecma262/#sec-line-terminators isLineTerminator: function (cp) { return (cp === 0x0A) || (cp === 0x0D) || (cp === 0x2028) || (cp === 0x2029); }, // https://tc39.github.io/ecma262/#sec-names-and-keywords isIdentifierStart: function (cp) { return (cp === 0x24) || (cp === 0x5F) || (cp >= 0x41 && cp <= 0x5A) || (cp >= 0x61 && cp <= 0x7A) || (cp === 0x5C) || ((cp >= 0x80) && Regex.NonAsciiIdentifierStart.test(exports.Character.fromCodePoint(cp))); }, isIdentifierPart: function (cp) { return (cp === 0x24) || (cp === 0x5F) || (cp >= 0x41 && cp <= 0x5A) || (cp >= 0x61 && cp <= 0x7A) || (cp >= 0x30 && cp <= 0x39) || (cp === 0x5C) || ((cp >= 0x80) && Regex.NonAsciiIdentifierPart.test(exports.Character.fromCodePoint(cp))); }, // https://tc39.github.io/ecma262/#sec-literals-numeric-literals isDecimalDigit: function (cp) { return (cp >= 0x30 && cp <= 0x39); // 0..9 }, isHexDigit: function (cp) { return (cp >= 0x30 && cp <= 0x39) || (cp >= 0x41 && cp <= 0x46) || (cp >= 0x61 && cp <= 0x66); // a..f }, isOctalDigit: function (cp) { return (cp >= 0x30 && cp <= 0x37); // 0..7 } }; /***/ }, /* 5 */ /***/ function(module, exports, __nested_webpack_require_54354__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var jsx_syntax_1 = __nested_webpack_require_54354__(6); /* tslint:disable:max-classes-per-file */ var JSXClosingElement = (function () { function JSXClosingElement(name) { this.type = jsx_syntax_1.JSXSyntax.JSXClosingElement; this.name = name; } return JSXClosingElement; }()); exports.JSXClosingElement = JSXClosingElement; var JSXElement = (function () { function JSXElement(openingElement, children, closingElement) { this.type = jsx_syntax_1.JSXSyntax.JSXElement; this.openingElement = openingElement; this.children = children; this.closingElement = closingElement; } return JSXElement; }()); exports.JSXElement = JSXElement; var JSXEmptyExpression = (function () { function JSXEmptyExpression() { this.type = jsx_syntax_1.JSXSyntax.JSXEmptyExpression; } return JSXEmptyExpression; }()); exports.JSXEmptyExpression = JSXEmptyExpression; var JSXExpressionContainer = (function () { function JSXExpressionContainer(expression) { this.type = jsx_syntax_1.JSXSyntax.JSXExpressionContainer; this.expression = expression; } return JSXExpressionContainer; }()); exports.JSXExpressionContainer = JSXExpressionContainer; var JSXIdentifier = (function () { function JSXIdentifier(name) { this.type = jsx_syntax_1.JSXSyntax.JSXIdentifier; this.name = name; } return JSXIdentifier; }()); exports.JSXIdentifier = JSXIdentifier; var JSXMemberExpression = (function () { function JSXMemberExpression(object, property) { this.type = jsx_syntax_1.JSXSyntax.JSXMemberExpression; this.object = object; this.property = property; } return JSXMemberExpression; }()); exports.JSXMemberExpression = JSXMemberExpression; var JSXAttribute = (function () { function JSXAttribute(name, value) { this.type = jsx_syntax_1.JSXSyntax.JSXAttribute; this.name = name; this.value = value; } return JSXAttribute; }()); exports.JSXAttribute = JSXAttribute; var JSXNamespacedName = (function () { function JSXNamespacedName(namespace, name) { this.type = jsx_syntax_1.JSXSyntax.JSXNamespacedName; this.namespace = namespace; this.name = name; } return JSXNamespacedName; }()); exports.JSXNamespacedName = JSXNamespacedName; var JSXOpeningElement = (function () { function JSXOpeningElement(name, selfClosing, attributes) { this.type = jsx_syntax_1.JSXSyntax.JSXOpeningElement; this.name = name; this.selfClosing = selfClosing; this.attributes = attributes; } return JSXOpeningElement; }()); exports.JSXOpeningElement = JSXOpeningElement; var JSXSpreadAttribute = (function () { function JSXSpreadAttribute(argument) { this.type = jsx_syntax_1.JSXSyntax.JSXSpreadAttribute; this.argument = argument; } return JSXSpreadAttribute; }()); exports.JSXSpreadAttribute = JSXSpreadAttribute; var JSXText = (function () { function JSXText(value, raw) { this.type = jsx_syntax_1.JSXSyntax.JSXText; this.value = value; this.raw = raw; } return JSXText; }()); exports.JSXText = JSXText; /***/ }, /* 6 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.JSXSyntax = { JSXAttribute: 'JSXAttribute', JSXClosingElement: 'JSXClosingElement', JSXElement: 'JSXElement', JSXEmptyExpression: 'JSXEmptyExpression', JSXExpressionContainer: 'JSXExpressionContainer', JSXIdentifier: 'JSXIdentifier', JSXMemberExpression: 'JSXMemberExpression', JSXNamespacedName: 'JSXNamespacedName', JSXOpeningElement: 'JSXOpeningElement', JSXSpreadAttribute: 'JSXSpreadAttribute', JSXText: 'JSXText' }; /***/ }, /* 7 */ /***/ function(module, exports, __nested_webpack_require_58416__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var syntax_1 = __nested_webpack_require_58416__(2); /* tslint:disable:max-classes-per-file */ var ArrayExpression = (function () { function ArrayExpression(elements) { this.type = syntax_1.Syntax.ArrayExpression; this.elements = elements; } return ArrayExpression; }()); exports.ArrayExpression = ArrayExpression; var ArrayPattern = (function () { function ArrayPattern(elements) { this.type = syntax_1.Syntax.ArrayPattern; this.elements = elements; } return ArrayPattern; }()); exports.ArrayPattern = ArrayPattern; var ArrowFunctionExpression = (function () { function ArrowFunctionExpression(params, body, expression) { this.type = syntax_1.Syntax.ArrowFunctionExpression; this.id = null; this.params = params; this.body = body; this.generator = false; this.expression = expression; this.async = false; } return ArrowFunctionExpression; }()); exports.ArrowFunctionExpression = ArrowFunctionExpression; var AssignmentExpression = (function () { function AssignmentExpression(operator, left, right) { this.type = syntax_1.Syntax.AssignmentExpression; this.operator = operator; this.left = left; this.right = right; } return AssignmentExpression; }()); exports.AssignmentExpression = AssignmentExpression; var AssignmentPattern = (function () { function AssignmentPattern(left, right) { this.type = syntax_1.Syntax.AssignmentPattern; this.left = left; this.right = right; } return AssignmentPattern; }()); exports.AssignmentPattern = AssignmentPattern; var AsyncArrowFunctionExpression = (function () { function AsyncArrowFunctionExpression(params, body, expression) { this.type = syntax_1.Syntax.ArrowFunctionExpression; this.id = null; this.params = params; this.body = body; this.generator = false; this.expression = expression; this.async = true; } return AsyncArrowFunctionExpression; }()); exports.AsyncArrowFunctionExpression = AsyncArrowFunctionExpression; var AsyncFunctionDeclaration = (function () { function AsyncFunctionDeclaration(id, params, body) { this.type = syntax_1.Syntax.FunctionDeclaration; this.id = id; this.params = params; this.body = body; this.generator = false; this.expression = false; this.async = true; } return AsyncFunctionDeclaration; }()); exports.AsyncFunctionDeclaration = AsyncFunctionDeclaration; var AsyncFunctionExpression = (function () { function AsyncFunctionExpression(id, params, body) { this.type = syntax_1.Syntax.FunctionExpression; this.id = id; this.params = params; this.body = body; this.generator = false; this.expression = false; this.async = true; } return AsyncFunctionExpression; }()); exports.AsyncFunctionExpression = AsyncFunctionExpression; var AwaitExpression = (function () { function AwaitExpression(argument) { this.type = syntax_1.Syntax.AwaitExpression; this.argument = argument; } return AwaitExpression; }()); exports.AwaitExpression = AwaitExpression; var BinaryExpression = (function () { function BinaryExpression(operator, left, right) { var logical = (operator === '||' || operator === '&&'); this.type = logical ? syntax_1.Syntax.LogicalExpression : syntax_1.Syntax.BinaryExpression; this.operator = operator; this.left = left; this.right = right; } return BinaryExpression; }()); exports.BinaryExpression = BinaryExpression; var BlockStatement = (function () { function BlockStatement(body) { this.type = syntax_1.Syntax.BlockStatement; this.body = body; } return BlockStatement; }()); exports.BlockStatement = BlockStatement; var BreakStatement = (function () { function BreakStatement(label) { this.type = syntax_1.Syntax.BreakStatement; this.label = label; } return BreakStatement; }()); exports.BreakStatement = BreakStatement; var CallExpression = (function () { function CallExpression(callee, args) { this.type = syntax_1.Syntax.CallExpression; this.callee = callee; this.arguments = args; } return CallExpression; }()); exports.CallExpression = CallExpression; var CatchClause = (function () { function CatchClause(param, body) { this.type = syntax_1.Syntax.CatchClause; this.param = param; this.body = body; } return CatchClause; }()); exports.CatchClause = CatchClause; var ClassBody = (function () { function ClassBody(body) { this.type = syntax_1.Syntax.ClassBody; this.body = body; } return ClassBody; }()); exports.ClassBody = ClassBody; var ClassDeclaration = (function () { function ClassDeclaration(id, superClass, body) { this.type = syntax_1.Syntax.ClassDeclaration; this.id = id; this.superClass = superClass; this.body = body; } return ClassDeclaration; }()); exports.ClassDeclaration = ClassDeclaration; var ClassExpression = (function () { function ClassExpression(id, superClass, body) { this.type = syntax_1.Syntax.ClassExpression; this.id = id; this.superClass = superClass; this.body = body; } return ClassExpression; }()); exports.ClassExpression = ClassExpression; var ComputedMemberExpression = (function () { function ComputedMemberExpression(object, property) { this.type = syntax_1.Syntax.MemberExpression; this.computed = true; this.object = object; this.property = property; } return ComputedMemberExpression; }()); exports.ComputedMemberExpression = ComputedMemberExpression; var ConditionalExpression = (function () { function ConditionalExpression(test, consequent, alternate) { this.type = syntax_1.Syntax.ConditionalExpression; this.test = test; this.consequent = consequent; this.alternate = alternate; } return ConditionalExpression; }()); exports.ConditionalExpression = ConditionalExpression; var ContinueStatement = (function () { function ContinueStatement(label) { this.type = syntax_1.Syntax.ContinueStatement; this.label = label; } return ContinueStatement; }()); exports.ContinueStatement = ContinueStatement; var DebuggerStatement = (function () { function DebuggerStatement() { this.type = syntax_1.Syntax.DebuggerStatement; } return DebuggerStatement; }()); exports.DebuggerStatement = DebuggerStatement; var Directive = (function () { function Directive(expression, directive) { this.type = syntax_1.Syntax.ExpressionStatement; this.expression = expression; this.directive = directive; } return Directive; }()); exports.Directive = Directive; var DoWhileStatement = (function () { function DoWhileStatement(body, test) { this.type = syntax_1.Syntax.DoWhileStatement; this.body = body; this.test = test; } return DoWhileStatement; }()); exports.DoWhileStatement = DoWhileStatement; var EmptyStatement = (function () { function EmptyStatement() { this.type = syntax_1.Syntax.EmptyStatement; } return EmptyStatement; }()); exports.EmptyStatement = EmptyStatement; var ExportAllDeclaration = (function () { function ExportAllDeclaration(source) { this.type = syntax_1.Syntax.ExportAllDeclaration; this.source = source; } return ExportAllDeclaration; }()); exports.ExportAllDeclaration = ExportAllDeclaration; var ExportDefaultDeclaration = (function () { function ExportDefaultDeclaration(declaration) { this.type = syntax_1.Syntax.ExportDefaultDeclaration; this.declaration = declaration; } return ExportDefaultDeclaration; }()); exports.ExportDefaultDeclaration = ExportDefaultDeclaration; var ExportNamedDeclaration = (function () { function ExportNamedDeclaration(declaration, specifiers, source) { this.type = syntax_1.Syntax.ExportNamedDeclaration; this.declaration = declaration; this.specifiers = specifiers; this.source = source; } return ExportNamedDeclaration; }()); exports.ExportNamedDeclaration = ExportNamedDeclaration; var ExportSpecifier = (function () { function ExportSpecifier(local, exported) { this.type = syntax_1.Syntax.ExportSpecifier; this.exported = exported; this.local = local; } return ExportSpecifier; }()); exports.ExportSpecifier = ExportSpecifier; var ExpressionStatement = (function () { function ExpressionStatement(expression) { this.type = syntax_1.Syntax.ExpressionStatement; this.expression = expression; } return ExpressionStatement; }()); exports.ExpressionStatement = ExpressionStatement; var ForInStatement = (function () { function ForInStatement(left, right, body) { this.type = syntax_1.Syntax.ForInStatement; this.left = left; this.right = right; this.body = body; this.each = false; } return ForInStatement; }()); exports.ForInStatement = ForInStatement; var ForOfStatement = (function () { function ForOfStatement(left, right, body) { this.type = syntax_1.Syntax.ForOfStatement; this.left = left; this.right = right; this.body = body; } return ForOfStatement; }()); exports.ForOfStatement = ForOfStatement; var ForStatement = (function () { function ForStatement(init, test, update, body) { this.type = syntax_1.Syntax.ForStatement; this.init = init; this.test = test; this.update = update; this.body = body; } return ForStatement; }()); exports.ForStatement = ForStatement; var FunctionDeclaration = (function () { function FunctionDeclaration(id, params, body, generator) { this.type = syntax_1.Syntax.FunctionDeclaration; this.id = id; this.params = params; this.body = body; this.generator = generator; this.expression = false; this.async = false; } return FunctionDeclaration; }()); exports.FunctionDeclaration = FunctionDeclaration; var FunctionExpression = (function () { function FunctionExpression(id, params, body, generator) { this.type = syntax_1.Syntax.FunctionExpression; this.id = id; this.params = params; this.body = body; this.generator = generator; this.expression = false; this.async = false; } return FunctionExpression; }()); exports.FunctionExpression = FunctionExpression; var Identifier = (function () { function Identifier(name) { this.type = syntax_1.Syntax.Identifier; this.name = name; } return Identifier; }()); exports.Identifier = Identifier; var IfStatement = (function () { function IfStatement(test, consequent, alternate) { this.type = syntax_1.Syntax.IfStatement; this.test = test; this.consequent = consequent; this.alternate = alternate; } return IfStatement; }()); exports.IfStatement = IfStatement; var ImportDeclaration = (function () { function ImportDeclaration(specifiers, source) { this.type = syntax_1.Syntax.ImportDeclaration; this.specifiers = specifiers; this.source = source; } return ImportDeclaration; }()); exports.ImportDeclaration = ImportDeclaration; var ImportDefaultSpecifier = (function () { function ImportDefaultSpecifier(local) { this.type = syntax_1.Syntax.ImportDefaultSpecifier; this.local = local; } return ImportDefaultSpecifier; }()); exports.ImportDefaultSpecifier = ImportDefaultSpecifier; var ImportNamespaceSpecifier = (function () { function ImportNamespaceSpecifier(local) { this.type = syntax_1.Syntax.ImportNamespaceSpecifier; this.local = local; } return ImportNamespaceSpecifier; }()); exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier; var ImportSpecifier = (function () { function ImportSpecifier(local, imported) { this.type = syntax_1.Syntax.ImportSpecifier; this.local = local; this.imported = imported; } return ImportSpecifier; }()); exports.ImportSpecifier = ImportSpecifier; var LabeledStatement = (function () { function LabeledStatement(label, body) { this.type = syntax_1.Syntax.LabeledStatement; this.label = label; this.body = body; } return LabeledStatement; }()); exports.LabeledStatement = LabeledStatement; var Literal = (function () { function Literal(value, raw) { this.type = syntax_1.Syntax.Literal; this.value = value; this.raw = raw; } return Literal; }()); exports.Literal = Literal; var MetaProperty = (function () { function MetaProperty(meta, property) { this.type = syntax_1.Syntax.MetaProperty; this.meta = meta; this.property = property; } return MetaProperty; }()); exports.MetaProperty = MetaProperty; var MethodDefinition = (function () { function MethodDefinition(key, computed, value, kind, isStatic) { this.type = syntax_1.Syntax.MethodDefinition; this.key = key; this.computed = computed; this.value = value; this.kind = kind; this.static = isStatic; } return MethodDefinition; }()); exports.MethodDefinition = MethodDefinition; var Module = (function () { function Module(body) { this.type = syntax_1.Syntax.Program; this.body = body; this.sourceType = 'module'; } return Module; }()); exports.Module = Module; var NewExpression = (function () { function NewExpression(callee, args) { this.type = syntax_1.Syntax.NewExpression; this.callee = callee; this.arguments = args; } return NewExpression; }()); exports.NewExpression = NewExpression; var ObjectExpression = (function () { function ObjectExpression(properties) { this.type = syntax_1.Syntax.ObjectExpression; this.properties = properties; } return ObjectExpression; }()); exports.ObjectExpression = ObjectExpression; var ObjectPattern = (function () { function ObjectPattern(properties) { this.type = syntax_1.Syntax.ObjectPattern; this.properties = properties; } return ObjectPattern; }()); exports.ObjectPattern = ObjectPattern; var Property = (function () { function Property(kind, key, computed, value, method, shorthand) { this.type = syntax_1.Syntax.Property; this.key = key; this.computed = computed; this.value = value; this.kind = kind; this.method = method; this.shorthand = shorthand; } return Property; }()); exports.Property = Property; var RegexLiteral = (function () { function RegexLiteral(value, raw, pattern, flags) { this.type = syntax_1.Syntax.Literal; this.value = value; this.raw = raw; this.regex = { pattern: pattern, flags: flags }; } return RegexLiteral; }()); exports.RegexLiteral = RegexLiteral; var RestElement = (function () { function RestElement(argument) { this.type = syntax_1.Syntax.RestElement; this.argument = argument; } return RestElement; }()); exports.RestElement = RestElement; var ReturnStatement = (function () { function ReturnStatement(argument) { this.type = syntax_1.Syntax.ReturnStatement; this.argument = argument; } return ReturnStatement; }()); exports.ReturnStatement = ReturnStatement; var Script = (function () { function Script(body) { this.type = syntax_1.Syntax.Program; this.body = body; this.sourceType = 'script'; } return Script; }()); exports.Script = Script; var SequenceExpression = (function () { function SequenceExpression(expressions) { this.type = syntax_1.Syntax.SequenceExpression; this.expressions = expressions; } return SequenceExpression; }()); exports.SequenceExpression = SequenceExpression; var SpreadElement = (function () { function SpreadElement(argument) { this.type = syntax_1.Syntax.SpreadElement; this.argument = argument; } return SpreadElement; }()); exports.SpreadElement = SpreadElement; var StaticMemberExpression = (function () { function StaticMemberExpression(object, property) { this.type = syntax_1.Syntax.MemberExpression; this.computed = false; this.object = object; this.property = property; } return StaticMemberExpression; }()); exports.StaticMemberExpression = StaticMemberExpression; var Super = (function () { function Super() { this.type = syntax_1.Syntax.Super; } return Super; }()); exports.Super = Super; var SwitchCase = (function () { function SwitchCase(test, consequent) { this.type = syntax_1.Syntax.SwitchCase; this.test = test; this.consequent = consequent; } return SwitchCase; }()); exports.SwitchCase = SwitchCase; var SwitchStatement = (function () { function SwitchStatement(discriminant, cases) { this.type = syntax_1.Syntax.SwitchStatement; this.discriminant = discriminant; this.cases = cases; } return SwitchStatement; }()); exports.SwitchStatement = SwitchStatement; var TaggedTemplateExpression = (function () { function TaggedTemplateExpression(tag, quasi) { this.type = syntax_1.Syntax.TaggedTemplateExpression; this.tag = tag; this.quasi = quasi; } return TaggedTemplateExpression; }()); exports.TaggedTemplateExpression = TaggedTemplateExpression; var TemplateElement = (function () { function TemplateElement(value, tail) { this.type = syntax_1.Syntax.TemplateElement; this.value = value; this.tail = tail; } return TemplateElement; }()); exports.TemplateElement = TemplateElement; var TemplateLiteral = (function () { function TemplateLiteral(quasis, expressions) { this.type = syntax_1.Syntax.TemplateLiteral; this.quasis = quasis; this.expressions = expressions; } return TemplateLiteral; }()); exports.TemplateLiteral = TemplateLiteral; var ThisExpression = (function () { function ThisExpression() { this.type = syntax_1.Syntax.ThisExpression; } return ThisExpression; }()); exports.ThisExpression = ThisExpression; var ThrowStatement = (function () { function ThrowStatement(argument) { this.type = syntax_1.Syntax.ThrowStatement; this.argument = argument; } return ThrowStatement; }()); exports.ThrowStatement = ThrowStatement; var TryStatement = (function () { function TryStatement(block, handler, finalizer) { this.type = syntax_1.Syntax.TryStatement; this.block = block; this.handler = handler; this.finalizer = finalizer; } return TryStatement; }()); exports.TryStatement = TryStatement; var UnaryExpression = (function () { function UnaryExpression(operator, argument) { this.type = syntax_1.Syntax.UnaryExpression; this.operator = operator; this.argument = argument; this.prefix = true; } return UnaryExpression; }()); exports.UnaryExpression = UnaryExpression; var UpdateExpression = (function () { function UpdateExpression(operator, argument, prefix) { this.type = syntax_1.Syntax.UpdateExpression; this.operator = operator; this.argument = argument; this.prefix = prefix; } return UpdateExpression; }()); exports.UpdateExpression = UpdateExpression; var VariableDeclaration = (function () { function VariableDeclaration(declarations, kind) { this.type = syntax_1.Syntax.VariableDeclaration; this.declarations = declarations; this.kind = kind; } return VariableDeclaration; }()); exports.VariableDeclaration = VariableDeclaration; var VariableDeclarator = (function () { function VariableDeclarator(id, init) { this.type = syntax_1.Syntax.VariableDeclarator; this.id = id; this.init = init; } return VariableDeclarator; }()); exports.VariableDeclarator = VariableDeclarator; var WhileStatement = (function () { function WhileStatement(test, body) { this.type = syntax_1.Syntax.WhileStatement; this.test = test; this.body = body; } return WhileStatement; }()); exports.WhileStatement = WhileStatement; var WithStatement = (function () { function WithStatement(object, body) { this.type = syntax_1.Syntax.WithStatement; this.object = object; this.body = body; } return WithStatement; }()); exports.WithStatement = WithStatement; var YieldExpression = (function () { function YieldExpression(argument, delegate) { this.type = syntax_1.Syntax.YieldExpression; this.argument = argument; this.delegate = delegate; } return YieldExpression; }()); exports.YieldExpression = YieldExpression; /***/ }, /* 8 */ /***/ function(module, exports, __nested_webpack_require_80491__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var assert_1 = __nested_webpack_require_80491__(9); var error_handler_1 = __nested_webpack_require_80491__(10); var messages_1 = __nested_webpack_require_80491__(11); var Node = __nested_webpack_require_80491__(7); var scanner_1 = __nested_webpack_require_80491__(12); var syntax_1 = __nested_webpack_require_80491__(2); var token_1 = __nested_webpack_require_80491__(13); var ArrowParameterPlaceHolder = 'ArrowParameterPlaceHolder'; var Parser = (function () { function Parser(code, options, delegate) { if (options === void 0) { options = {}; } this.config = { range: (typeof options.range === 'boolean') && options.range, loc: (typeof options.loc === 'boolean') && options.loc, source: null, tokens: (typeof options.tokens === 'boolean') && options.tokens, comment: (typeof options.comment === 'boolean') && options.comment, tolerant: (typeof options.tolerant === 'boolean') && options.tolerant }; if (this.config.loc && options.source && options.source !== null) { this.config.source = String(options.source); } this.delegate = delegate; this.errorHandler = new error_handler_1.ErrorHandler(); this.errorHandler.tolerant = this.config.tolerant; this.scanner = new scanner_1.Scanner(code, this.errorHandler); this.scanner.trackComment = this.config.comment; this.operatorPrecedence = { ')': 0, ';': 0, ',': 0, '=': 0, ']': 0, '||': 1, '&&': 2, '|': 3, '^': 4, '&': 5, '==': 6, '!=': 6, '===': 6, '!==': 6, '<': 7, '>': 7, '<=': 7, '>=': 7, '<<': 8, '>>': 8, '>>>': 8, '+': 9, '-': 9, '*': 11, '/': 11, '%': 11 }; this.lookahead = { type: 2 /* EOF */, value: '', lineNumber: this.scanner.lineNumber, lineStart: 0, start: 0, end: 0 }; this.hasLineTerminator = false; this.context = { isModule: false, await: false, allowIn: true, allowStrictDirective: true, allowYield: true, firstCoverInitializedNameError: null, isAssignmentTarget: false, isBindingElement: false, inFunctionBody: false, inIteration: false, inSwitch: false, labelSet: {}, strict: false }; this.tokens = []; this.startMarker = { index: 0, line: this.scanner.lineNumber, column: 0 }; this.lastMarker = { index: 0, line: this.scanner.lineNumber, column: 0 }; this.nextToken(); this.lastMarker = { index: this.scanner.index, line: this.scanner.lineNumber, column: this.scanner.index - this.scanner.lineStart }; } Parser.prototype.throwError = function (messageFormat) { var values = []; for (var _i = 1; _i < arguments.length; _i++) { values[_i - 1] = arguments[_i]; } var args = Array.prototype.slice.call(arguments, 1); var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) { assert_1.assert(idx < args.length, 'Message reference must be in range'); return args[idx]; }); var index = this.lastMarker.index; var line = this.lastMarker.line; var column = this.lastMarker.column + 1; throw this.errorHandler.createError(index, line, column, msg); }; Parser.prototype.tolerateError = function (messageFormat) { var values = []; for (var _i = 1; _i < arguments.length; _i++) { values[_i - 1] = arguments[_i]; } var args = Array.prototype.slice.call(arguments, 1); var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) { assert_1.assert(idx < args.length, 'Message reference must be in range'); return args[idx]; }); var index = this.lastMarker.index; var line = this.scanner.lineNumber; var column = this.lastMarker.column + 1; this.errorHandler.tolerateError(index, line, column, msg); }; // Throw an exception because of the token. Parser.prototype.unexpectedTokenError = function (token, message) { var msg = message || messages_1.Messages.UnexpectedToken; var value; if (token) { if (!message) { msg = (token.type === 2 /* EOF */) ? messages_1.Messages.UnexpectedEOS : (token.type === 3 /* Identifier */) ? messages_1.Messages.UnexpectedIdentifier : (token.type === 6 /* NumericLiteral */) ? messages_1.Messages.UnexpectedNumber : (token.type === 8 /* StringLiteral */) ? messages_1.Messages.UnexpectedString : (token.type === 10 /* Template */) ? messages_1.Messages.UnexpectedTemplate : messages_1.Messages.UnexpectedToken; if (token.type === 4 /* Keyword */) { if (this.scanner.isFutureReservedWord(token.value)) { msg = messages_1.Messages.UnexpectedReserved; } else if (this.context.strict && this.scanner.isStrictModeReservedWord(token.value)) { msg = messages_1.Messages.StrictReservedWord; } } } value = token.value; } else { value = 'ILLEGAL'; } msg = msg.replace('%0', value); if (token && typeof token.lineNumber === 'number') { var index = token.start; var line = token.lineNumber; var lastMarkerLineStart = this.lastMarker.index - this.lastMarker.column; var column = token.start - lastMarkerLineStart + 1; return this.errorHandler.createError(index, line, column, msg); } else { var index = this.lastMarker.index; var line = this.lastMarker.line; var column = this.lastMarker.column + 1; return this.errorHandler.createError(index, line, column, msg); } }; Parser.prototype.throwUnexpectedToken = function (token, message) { throw this.unexpectedTokenError(token, message); }; Parser.prototype.tolerateUnexpectedToken = function (token, message) { this.errorHandler.tolerate(this.unexpectedTokenError(token, message)); }; Parser.prototype.collectComments = function () { if (!this.config.comment) { this.scanner.scanComments(); } else { var comments = this.scanner.scanComments(); if (comments.length > 0 && this.delegate) { for (var i = 0; i < comments.length; ++i) { var e = comments[i]; var node = void 0; node = { type: e.multiLine ? 'BlockComment' : 'LineComment', value: this.scanner.source.slice(e.slice[0], e.slice[1]) }; if (this.config.range) { node.range = e.range; } if (this.config.loc) { node.loc = e.loc; } var metadata = { start: { line: e.loc.start.line, column: e.loc.start.column, offset: e.range[0] }, end: { line: e.loc.end.line, column: e.loc.end.column, offset: e.range[1] } }; this.delegate(node, metadata); } } } }; // From internal representation to an external structure Parser.prototype.getTokenRaw = function (token) { return this.scanner.source.slice(token.start, token.end); }; Parser.prototype.convertToken = function (token) { var t = { type: token_1.TokenName[token.type], value: this.getTokenRaw(token) }; if (this.config.range) { t.range = [token.start, token.end]; } if (this.config.loc) { t.loc = { start: { line: this.startMarker.line, column: this.startMarker.column }, end: { line: this.scanner.lineNumber, column: this.scanner.index - this.scanner.lineStart } }; } if (token.type === 9 /* RegularExpression */) { var pattern = token.pattern; var flags = token.flags; t.regex = { pattern: pattern, flags: flags }; } return t; }; Parser.prototype.nextToken = function () { var token = this.lookahead; this.lastMarker.index = this.scanner.index; this.lastMarker.line = this.scanner.lineNumber; this.lastMarker.column = this.scanner.index - this.scanner.lineStart; this.collectComments(); if (this.scanner.index !== this.startMarker.index) { this.startMarker.index = this.scanner.index; this.startMarker.line = this.scanner.lineNumber; this.startMarker.column = this.scanner.index - this.scanner.lineStart; } var next = this.scanner.lex(); this.hasLineTerminator = (token.lineNumber !== next.lineNumber); if (next && this.context.strict && next.type === 3 /* Identifier */) { if (this.scanner.isStrictModeReservedWord(next.value)) { next.type = 4 /* Keyword */; } } this.lookahead = next; if (this.config.tokens && next.type !== 2 /* EOF */) { this.tokens.push(this.convertToken(next)); } return token; }; Parser.prototype.nextRegexToken = function () { this.collectComments(); var token = this.scanner.scanRegExp(); if (this.config.tokens) { // Pop the previous token, '/' or '/=' // This is added from the lookahead token. this.tokens.pop(); this.tokens.push(this.convertToken(token)); } // Prime the next lookahead. this.lookahead = token; this.nextToken(); return token; }; Parser.prototype.createNode = function () { return { index: this.startMarker.index, line: this.startMarker.line, column: this.startMarker.column }; }; Parser.prototype.startNode = function (token, lastLineStart) { if (lastLineStart === void 0) { lastLineStart = 0; } var column = token.start - token.lineStart; var line = token.lineNumber; if (column < 0) { column += lastLineStart; line--; } return { index: token.start, line: line, column: column }; }; Parser.prototype.finalize = function (marker, node) { if (this.config.range) { node.range = [marker.index, this.lastMarker.index]; } if (this.config.loc) { node.loc = { start: { line: marker.line, column: marker.column, }, end: { line: this.lastMarker.line, column: this.lastMarker.column } }; if (this.config.source) { node.loc.source = this.config.source; } } if (this.delegate) { var metadata = { start: { line: marker.line, column: marker.column, offset: marker.index }, end: { line: this.lastMarker.line, column: this.lastMarker.column, offset: this.lastMarker.index } }; this.delegate(node, metadata); } return node; }; // Expect the next token to match the specified punctuator. // If not, an exception will be thrown. Parser.prototype.expect = function (value) { var token = this.nextToken(); if (token.type !== 7 /* Punctuator */ || token.value !== value) { this.throwUnexpectedToken(token); } }; // Quietly expect a comma when in tolerant mode, otherwise delegates to expect(). Parser.prototype.expectCommaSeparator = function () { if (this.config.tolerant) { var token = this.lookahead; if (token.type === 7 /* Punctuator */ && token.value === ',') { this.nextToken(); } else if (token.type === 7 /* Punctuator */ && token.value === ';') { this.nextToken(); this.tolerateUnexpectedToken(token); } else { this.tolerateUnexpectedToken(token, messages_1.Messages.UnexpectedToken); } } else { this.expect(','); } }; // Expect the next token to match the specified keyword. // If not, an exception will be thrown. Parser.prototype.expectKeyword = function (keyword) { var token = this.nextToken(); if (token.type !== 4 /* Keyword */ || token.value !== keyword) { this.throwUnexpectedToken(token); } }; // Return true if the next token matches the specified punctuator. Parser.prototype.match = function (value) { return this.lookahead.type === 7 /* Punctuator */ && this.lookahead.value === value; }; // Return true if the next token matches the specified keyword Parser.prototype.matchKeyword = function (keyword) { return this.lookahead.type === 4 /* Keyword */ && this.lookahead.value === keyword; }; // Return true if the next token matches the specified contextual keyword // (where an identifier is sometimes a keyword depending on the context) Parser.prototype.matchContextualKeyword = function (keyword) { return this.lookahead.type === 3 /* Identifier */ && this.lookahead.value === keyword; }; // Return true if the next token is an assignment operator Parser.prototype.matchAssign = function () { if (this.lookahead.type !== 7 /* Punctuator */) { return false; } var op = this.lookahead.value; return op === '=' || op === '*=' || op === '**=' || op === '/=' || op === '%=' || op === '+=' || op === '-=' || op === '<<=' || op === '>>=' || op === '>>>=' || op === '&=' || op === '^=' || op === '|='; }; // Cover grammar support. // // When an assignment expression position starts with an left parenthesis, the determination of the type // of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead) // or the first comma. This situation also defers the determination of all the expressions nested in the pair. // // There are three productions that can be parsed in a parentheses pair that needs to be determined // after the outermost pair is closed. They are: // // 1. AssignmentExpression // 2. BindingElements // 3. AssignmentTargets // // In order to avoid exponential backtracking, we use two flags to denote if the production can be // binding element or assignment target. // // The three productions have the relationship: // // BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression // // with a single exception that CoverInitializedName when used directly in an Expression, generates // an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the // first usage of CoverInitializedName and report it when we reached the end of the parentheses pair. // // isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not // effect the current flags. This means the production the parser parses is only used as an expression. Therefore // the CoverInitializedName check is conducted. // // inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates // the flags outside of the parser. This means the production the parser parses is used as a part of a potential // pattern. The CoverInitializedName check is deferred. Parser.prototype.isolateCoverGrammar = function (parseFunction) { var previousIsBindingElement = this.context.isBindingElement; var previousIsAssignmentTarget = this.context.isAssignmentTarget; var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError; this.context.isBindingElement = true; this.context.isAssignmentTarget = true; this.context.firstCoverInitializedNameError = null; var result = parseFunction.call(this); if (this.context.firstCoverInitializedNameError !== null) { this.throwUnexpectedToken(this.context.firstCoverInitializedNameError); } this.context.isBindingElement = previousIsBindingElement; this.context.isAssignmentTarget = previousIsAssignmentTarget; this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError; return result; }; Parser.prototype.inheritCoverGrammar = function (parseFunction) { var previousIsBindingElement = this.context.isBindingElement; var previousIsAssignmentTarget = this.context.isAssignmentTarget; var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError; this.context.isBindingElement = true; this.context.isAssignmentTarget = true; this.context.firstCoverInitializedNameError = null; var result = parseFunction.call(this); this.context.isBindingElement = this.context.isBindingElement && previousIsBindingElement; this.context.isAssignmentTarget = this.context.isAssignmentTarget && previousIsAssignmentTarget; this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError || this.context.firstCoverInitializedNameError; return result; }; Parser.prototype.consumeSemicolon = function () { if (this.match(';')) { this.nextToken(); } else if (!this.hasLineTerminator) { if (this.lookahead.type !== 2 /* EOF */ && !this.match('}')) { this.throwUnexpectedToken(this.lookahead); } this.lastMarker.index = this.startMarker.index; this.lastMarker.line = this.startMarker.line; this.lastMarker.column = this.startMarker.column; } }; // https://tc39.github.io/ecma262/#sec-primary-expression Parser.prototype.parsePrimaryExpression = function () { var node = this.createNode(); var expr; var token, raw; switch (this.lookahead.type) { case 3 /* Identifier */: if ((this.context.isModule || this.context.await) && this.lookahead.value === 'await') { this.tolerateUnexpectedToken(this.lookahead); } expr = this.matchAsyncFunction() ? this.parseFunctionExpression() : this.finalize(node, new Node.Identifier(this.nextToken().value)); break; case 6 /* NumericLiteral */: case 8 /* StringLiteral */: if (this.context.strict && this.lookahead.octal) { this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.StrictOctalLiteral); } this.context.isAssignmentTarget = false; this.context.isBindingElement = false; token = this.nextToken(); raw = this.getTokenRaw(token); expr = this.finalize(node, new Node.Literal(token.value, raw)); break; case 1 /* BooleanLiteral */: this.context.isAssignmentTarget = false; this.context.isBindingElement = false; token = this.nextToken(); raw = this.getTokenRaw(token); expr = this.finalize(node, new Node.Literal(token.value === 'true', raw)); break; case 5 /* NullLiteral */: this.context.isAssignmentTarget = false; this.context.isBindingElement = false; token = this.nextToken(); raw = this.getTokenRaw(token); expr = this.finalize(node, new Node.Literal(null, raw)); break; case 10 /* Template */: expr = this.parseTemplateLiteral(); break; case 7 /* Punctuator */: switch (this.lookahead.value) { case '(': this.context.isBindingElement = false; expr = this.inheritCoverGrammar(this.parseGroupExpression); break; case '[': expr = this.inheritCoverGrammar(this.parseArrayInitializer); break; case '{': expr = this.inheritCoverGrammar(this.parseObjectInitializer); break; case '/': case '/=': this.context.isAssignmentTarget = false; this.context.isBindingElement = false; this.scanner.index = this.startMarker.index; token = this.nextRegexToken(); raw = this.getTokenRaw(token); expr = this.finalize(node, new Node.RegexLiteral(token.regex, raw, token.pattern, token.flags)); break; default: expr = this.throwUnexpectedToken(this.nextToken()); } break; case 4 /* Keyword */: if (!this.context.strict && this.context.allowYield && this.matchKeyword('yield')) { expr = this.parseIdentifierName(); } else if (!this.context.strict && this.matchKeyword('let')) { expr = this.finalize(node, new Node.Identifier(this.nextToken().value)); } else { this.context.isAssignmentTarget = false; this.context.isBindingElement = false; if (this.matchKeyword('function')) { expr = this.parseFunctionExpression(); } else if (this.matchKeyword('this')) { this.nextToken(); expr = this.finalize(node, new Node.ThisExpression()); } else if (this.matchKeyword('class')) { expr = this.parseClassExpression(); } else { expr = this.throwUnexpectedToken(this.nextToken()); } } break; default: expr = this.throwUnexpectedToken(this.nextToken()); } return expr; }; // https://tc39.github.io/ecma262/#sec-array-initializer Parser.prototype.parseSpreadElement = function () { var node = this.createNode(); this.expect('...'); var arg = this.inheritCoverGrammar(this.parseAssignmentExpression); return this.finalize(node, new Node.SpreadElement(arg)); }; Parser.prototype.parseArrayInitializer = function () { var node = this.createNode(); var elements = []; this.expect('['); while (!this.match(']')) { if (this.match(',')) { this.nextToken(); elements.push(null); } else if (this.match('...')) { var element = this.parseSpreadElement(); if (!this.match(']')) { this.context.isAssignmentTarget = false; this.context.isBindingElement = false; this.expect(','); } elements.push(element); } else { elements.push(this.inheritCoverGrammar(this.parseAssignmentExpression)); if (!this.match(']')) { this.expect(','); } } } this.expect(']'); return this.finalize(node, new Node.ArrayExpression(elements)); }; // https://tc39.github.io/ecma262/#sec-object-initializer Parser.prototype.parsePropertyMethod = function (params) { this.context.isAssignmentTarget = false; this.context.isBindingElement = false; var previousStrict = this.context.strict; var previousAllowStrictDirective = this.context.allowStrictDirective; this.context.allowStrictDirective = params.simple; var body = this.isolateCoverGrammar(this.parseFunctionSourceElements); if (this.context.strict && params.firstRestricted) { this.tolerateUnexpectedToken(params.firstRestricted, params.message); } if (this.context.strict && params.stricted) { this.tolerateUnexpectedToken(params.stricted, params.message); } this.context.strict = previousStrict; this.context.allowStrictDirective = previousAllowStrictDirective; return body; }; Parser.prototype.parsePropertyMethodFunction = function () { var isGenerator = false; var node = this.createNode(); var previousAllowYield = this.context.allowYield; this.context.allowYield = true; var params = this.parseFormalParameters(); var method = this.parsePropertyMethod(params); this.context.allowYield = previousAllowYield; return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator)); }; Parser.prototype.parsePropertyMethodAsyncFunction = function () { var node = this.createNode(); var previousAllowYield = this.context.allowYield; var previousAwait = this.context.await; this.context.allowYield = false; this.context.await = true; var params = this.parseFormalParameters(); var method = this.parsePropertyMethod(params); this.context.allowYield = previousAllowYield; this.context.await = previousAwait; return this.finalize(node, new Node.AsyncFunctionExpression(null, params.params, method)); }; Parser.prototype.parseObjectPropertyKey = function () { var node = this.createNode(); var token = this.nextToken(); var key; switch (token.type) { case 8 /* StringLiteral */: case 6 /* NumericLiteral */: if (this.context.strict && token.octal) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictOctalLiteral); } var raw = this.getTokenRaw(token); key = this.finalize(node, new Node.Literal(token.value, raw)); break; case 3 /* Identifier */: case 1 /* BooleanLiteral */: case 5 /* NullLiteral */: case 4 /* Keyword */: key = this.finalize(node, new Node.Identifier(token.value)); break; case 7 /* Punctuator */: if (token.value === '[') { key = this.isolateCoverGrammar(this.parseAssignmentExpression); this.expect(']'); } else { key = this.throwUnexpectedToken(token); } break; default: key = this.throwUnexpectedToken(token); } return key; }; Parser.prototype.isPropertyKey = function (key, value) { return (key.type === syntax_1.Syntax.Identifier && key.name === value) || (key.type === syntax_1.Syntax.Literal && key.value === value); }; Parser.prototype.parseObjectProperty = function (hasProto) { var node = this.createNode(); var token = this.lookahead; var kind; var key = null; var value = null; var computed = false; var method = false; var shorthand = false; var isAsync = false; if (token.type === 3 /* Identifier */) { var id = token.value; this.nextToken(); computed = this.match('['); isAsync = !this.hasLineTerminator && (id === 'async') && !this.match(':') && !this.match('(') && !this.match('*') && !this.match(','); key = isAsync ? this.parseObjectPropertyKey() : this.finalize(node, new Node.Identifier(id)); } else if (this.match('*')) { this.nextToken(); } else { computed = this.match('['); key = this.parseObjectPropertyKey(); } var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead); if (token.type === 3 /* Identifier */ && !isAsync && token.value === 'get' && lookaheadPropertyKey) { kind = 'get'; computed = this.match('['); key = this.parseObjectPropertyKey(); this.context.allowYield = false; value = this.parseGetterMethod(); } else if (token.type === 3 /* Identifier */ && !isAsync && token.value === 'set' && lookaheadPropertyKey) { kind = 'set'; computed = this.match('['); key = this.parseObjectPropertyKey(); value = this.parseSetterMethod(); } else if (token.type === 7 /* Punctuator */ && token.value === '*' && lookaheadPropertyKey) { kind = 'init'; computed = this.match('['); key = this.parseObjectPropertyKey(); value = this.parseGeneratorMethod(); method = true; } else { if (!key) { this.throwUnexpectedToken(this.lookahead); } kind = 'init'; if (this.match(':') && !isAsync) { if (!computed && this.isPropertyKey(key, '__proto__')) { if (hasProto.value) { this.tolerateError(messages_1.Messages.DuplicateProtoProperty); } hasProto.value = true; } this.nextToken(); value = this.inheritCoverGrammar(this.parseAssignmentExpression); } else if (this.match('(')) { value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction(); method = true; } else if (token.type === 3 /* Identifier */) { var id = this.finalize(node, new Node.Identifier(token.value)); if (this.match('=')) { this.context.firstCoverInitializedNameError = this.lookahead; this.nextToken(); shorthand = true; var init = this.isolateCoverGrammar(this.parseAssignmentExpression); value = this.finalize(node, new Node.AssignmentPattern(id, init)); } else { shorthand = true; value = id; } } else { this.throwUnexpectedToken(this.nextToken()); } } return this.finalize(node, new Node.Property(kind, key, computed, value, method, shorthand)); }; Parser.prototype.parseObjectInitializer = function () { var node = this.createNode(); this.expect('{'); var properties = []; var hasProto = { value: false }; while (!this.match('}')) { properties.push(this.parseObjectProperty(hasProto)); if (!this.match('}')) { this.expectCommaSeparator(); } } this.expect('}'); return this.finalize(node, new Node.ObjectExpression(properties)); }; // https://tc39.github.io/ecma262/#sec-template-literals Parser.prototype.parseTemplateHead = function () { assert_1.assert(this.lookahead.head, 'Template literal must start with a template head'); var node = this.createNode(); var token = this.nextToken(); var raw = token.value; var cooked = token.cooked; return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail)); }; Parser.prototype.parseTemplateElement = function () { if (this.lookahead.type !== 10 /* Template */) { this.throwUnexpectedToken(); } var node = this.createNode(); var token = this.nextToken(); var raw = token.value; var cooked = token.cooked; return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail)); }; Parser.prototype.parseTemplateLiteral = function () { var node = this.createNode(); var expressions = []; var quasis = []; var quasi = this.parseTemplateHead(); quasis.push(quasi); while (!quasi.tail) { expressions.push(this.parseExpression()); quasi = this.parseTemplateElement(); quasis.push(quasi); } return this.finalize(node, new Node.TemplateLiteral(quasis, expressions)); }; // https://tc39.github.io/ecma262/#sec-grouping-operator Parser.prototype.reinterpretExpressionAsPattern = function (expr) { switch (expr.type) { case syntax_1.Syntax.Identifier: case syntax_1.Syntax.MemberExpression: case syntax_1.Syntax.RestElement: case syntax_1.Syntax.AssignmentPattern: break; case syntax_1.Syntax.SpreadElement: expr.type = syntax_1.Syntax.RestElement; this.reinterpretExpressionAsPattern(expr.argument); break; case syntax_1.Syntax.ArrayExpression: expr.type = syntax_1.Syntax.ArrayPattern; for (var i = 0; i < expr.elements.length; i++) { if (expr.elements[i] !== null) { this.reinterpretExpressionAsPattern(expr.elements[i]); } } break; case syntax_1.Syntax.ObjectExpression: expr.type = syntax_1.Syntax.ObjectPattern; for (var i = 0; i < expr.properties.length; i++) { this.reinterpretExpressionAsPattern(expr.properties[i].value); } break; case syntax_1.Syntax.AssignmentExpression: expr.type = syntax_1.Syntax.AssignmentPattern; delete expr.operator; this.reinterpretExpressionAsPattern(expr.left); break; default: // Allow other node type for tolerant parsing. break; } }; Parser.prototype.parseGroupExpression = function () { var expr; this.expect('('); if (this.match(')')) { this.nextToken(); if (!this.match('=>')) { this.expect('=>'); } expr = { type: ArrowParameterPlaceHolder, params: [], async: false }; } else { var startToken = this.lookahead; var params = []; if (this.match('...')) { expr = this.parseRestElement(params); this.expect(')'); if (!this.match('=>')) { this.expect('=>'); } expr = { type: ArrowParameterPlaceHolder, params: [expr], async: false }; } else { var arrow = false; this.context.isBindingElement = true; expr = this.inheritCoverGrammar(this.parseAssignmentExpression); if (this.match(',')) { var expressions = []; this.context.isAssignmentTarget = false; expressions.push(expr); while (this.lookahead.type !== 2 /* EOF */) { if (!this.match(',')) { break; } this.nextToken(); if (this.match(')')) { this.nextToken(); for (var i = 0; i < expressions.length; i++) { this.reinterpretExpressionAsPattern(expressions[i]); } arrow = true; expr = { type: ArrowParameterPlaceHolder, params: expressions, async: false }; } else if (this.match('...')) { if (!this.context.isBindingElement) { this.throwUnexpectedToken(this.lookahead); } expressions.push(this.parseRestElement(params)); this.expect(')'); if (!this.match('=>')) { this.expect('=>'); } this.context.isBindingElement = false; for (var i = 0; i < expressions.length; i++) { this.reinterpretExpressionAsPattern(expressions[i]); } arrow = true; expr = { type: ArrowParameterPlaceHolder, params: expressions, async: false }; } else { expressions.push(this.inheritCoverGrammar(this.parseAssignmentExpression)); } if (arrow) { break; } } if (!arrow) { expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions)); } } if (!arrow) { this.expect(')'); if (this.match('=>')) { if (expr.type === syntax_1.Syntax.Identifier && expr.name === 'yield') { arrow = true; expr = { type: ArrowParameterPlaceHolder, params: [expr], async: false }; } if (!arrow) { if (!this.context.isBindingElement) { this.throwUnexpectedToken(this.lookahead); } if (expr.type === syntax_1.Syntax.SequenceExpression) { for (var i = 0; i < expr.expressions.length; i++) { this.reinterpretExpressionAsPattern(expr.expressions[i]); } } else { this.reinterpretExpressionAsPattern(expr); } var parameters = (expr.type === syntax_1.Syntax.SequenceExpression ? expr.expressions : [expr]); expr = { type: ArrowParameterPlaceHolder, params: parameters, async: false }; } } this.context.isBindingElement = false; } } } return expr; }; // https://tc39.github.io/ecma262/#sec-left-hand-side-expressions Parser.prototype.parseArguments = function () { this.expect('('); var args = []; if (!this.match(')')) { while (true) { var expr = this.match('...') ? this.parseSpreadElement() : this.isolateCoverGrammar(this.parseAssignmentExpression); args.push(expr); if (this.match(')')) { break; } this.expectCommaSeparator(); if (this.match(')')) { break; } } } this.expect(')'); return args; }; Parser.prototype.isIdentifierName = function (token) { return token.type === 3 /* Identifier */ || token.type === 4 /* Keyword */ || token.type === 1 /* BooleanLiteral */ || token.type === 5 /* NullLiteral */; }; Parser.prototype.parseIdentifierName = function () { var node = this.createNode(); var token = this.nextToken(); if (!this.isIdentifierName(token)) { this.throwUnexpectedToken(token); } return this.finalize(node, new Node.Identifier(token.value)); }; Parser.prototype.parseNewExpression = function () { var node = this.createNode(); var id = this.parseIdentifierName(); assert_1.assert(id.name === 'new', 'New expression must start with `new`'); var expr; if (this.match('.')) { this.nextToken(); if (this.lookahead.type === 3 /* Identifier */ && this.context.inFunctionBody && this.lookahead.value === 'target') { var property = this.parseIdentifierName(); expr = new Node.MetaProperty(id, property); } else { this.throwUnexpectedToken(this.lookahead); } } else { var callee = this.isolateCoverGrammar(this.parseLeftHandSideExpression); var args = this.match('(') ? this.parseArguments() : []; expr = new Node.NewExpression(callee, args); this.context.isAssignmentTarget = false; this.context.isBindingElement = false; } return this.finalize(node, expr); }; Parser.prototype.parseAsyncArgument = function () { var arg = this.parseAssignmentExpression(); this.context.firstCoverInitializedNameError = null; return arg; }; Parser.prototype.parseAsyncArguments = function () { this.expect('('); var args = []; if (!this.match(')')) { while (true) { var expr = this.match('...') ? this.parseSpreadElement() : this.isolateCoverGrammar(this.parseAsyncArgument); args.push(expr); if (this.match(')')) { break; } this.expectCommaSeparator(); if (this.match(')')) { break; } } } this.expect(')'); return args; }; Parser.prototype.parseLeftHandSideExpressionAllowCall = function () { var startToken = this.lookahead; var maybeAsync = this.matchContextualKeyword('async'); var previousAllowIn = this.context.allowIn; this.context.allowIn = true; var expr; if (this.matchKeyword('super') && this.context.inFunctionBody) { expr = this.createNode(); this.nextToken(); expr = this.finalize(expr, new Node.Super()); if (!this.match('(') && !this.match('.') && !this.match('[')) { this.throwUnexpectedToken(this.lookahead); } } else { expr = this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression); } while (true) { if (this.match('.')) { this.context.isBindingElement = false; this.context.isAssignmentTarget = true; this.expect('.'); var property = this.parseIdentifierName(); expr = this.finalize(this.startNode(startToken), new Node.StaticMemberExpression(expr, property)); } else if (this.match('(')) { var asyncArrow = maybeAsync && (startToken.lineNumber === this.lookahead.lineNumber); this.context.isBindingElement = false; this.context.isAssignmentTarget = false; var args = asyncArrow ? this.parseAsyncArguments() : this.parseArguments(); expr = this.finalize(this.startNode(startToken), new Node.CallExpression(expr, args)); if (asyncArrow && this.match('=>')) { for (var i = 0; i < args.length; ++i) { this.reinterpretExpressionAsPattern(args[i]); } expr = { type: ArrowParameterPlaceHolder, params: args, async: true }; } } else if (this.match('[')) { this.context.isBindingElement = false; this.context.isAssignmentTarget = true; this.expect('['); var property = this.isolateCoverGrammar(this.parseExpression); this.expect(']'); expr = this.finalize(this.startNode(startToken), new Node.ComputedMemberExpression(expr, property)); } else if (this.lookahead.type === 10 /* Template */ && this.lookahead.head) { var quasi = this.parseTemplateLiteral(); expr = this.finalize(this.startNode(startToken), new Node.TaggedTemplateExpression(expr, quasi)); } else { break; } } this.context.allowIn = previousAllowIn; return expr; }; Parser.prototype.parseSuper = function () { var node = this.createNode(); this.expectKeyword('super'); if (!this.match('[') && !this.match('.')) { this.throwUnexpectedToken(this.lookahead); } return this.finalize(node, new Node.Super()); }; Parser.prototype.parseLeftHandSideExpression = function () { assert_1.assert(this.context.allowIn, 'callee of new expression always allow in keyword.'); var node = this.startNode(this.lookahead); var expr = (this.matchKeyword('super') && this.context.inFunctionBody) ? this.parseSuper() : this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression); while (true) { if (this.match('[')) { this.context.isBindingElement = false; this.context.isAssignmentTarget = true; this.expect('['); var property = this.isolateCoverGrammar(this.parseExpression); this.expect(']'); expr = this.finalize(node, new Node.ComputedMemberExpression(expr, property)); } else if (this.match('.')) { this.context.isBindingElement = false; this.context.isAssignmentTarget = true; this.expect('.'); var property = this.parseIdentifierName(); expr = this.finalize(node, new Node.StaticMemberExpression(expr, property)); } else if (this.lookahead.type === 10 /* Template */ && this.lookahead.head) { var quasi = this.parseTemplateLiteral(); expr = this.finalize(node, new Node.TaggedTemplateExpression(expr, quasi)); } else { break; } } return expr; }; // https://tc39.github.io/ecma262/#sec-update-expressions Parser.prototype.parseUpdateExpression = function () { var expr; var startToken = this.lookahead; if (this.match('++') || this.match('--')) { var node = this.startNode(startToken); var token = this.nextToken(); expr = this.inheritCoverGrammar(this.parseUnaryExpression); if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) { this.tolerateError(messages_1.Messages.StrictLHSPrefix); } if (!this.context.isAssignmentTarget) { this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); } var prefix = true; expr = this.finalize(node, new Node.UpdateExpression(token.value, expr, prefix)); this.context.isAssignmentTarget = false; this.context.isBindingElement = false; } else { expr = this.inheritCoverGrammar(this.parseLeftHandSideExpressionAllowCall); if (!this.hasLineTerminator && this.lookahead.type === 7 /* Punctuator */) { if (this.match('++') || this.match('--')) { if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) { this.tolerateError(messages_1.Messages.StrictLHSPostfix); } if (!this.context.isAssignmentTarget) { this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); } this.context.isAssignmentTarget = false; this.context.isBindingElement = false; var operator = this.nextToken().value; var prefix = false; expr = this.finalize(this.startNode(startToken), new Node.UpdateExpression(operator, expr, prefix)); } } } return expr; }; // https://tc39.github.io/ecma262/#sec-unary-operators Parser.prototype.parseAwaitExpression = function () { var node = this.createNode(); this.nextToken(); var argument = this.parseUnaryExpression(); return this.finalize(node, new Node.AwaitExpression(argument)); }; Parser.prototype.parseUnaryExpression = function () { var expr; if (this.match('+') || this.match('-') || this.match('~') || this.match('!') || this.matchKeyword('delete') || this.matchKeyword('void') || this.matchKeyword('typeof')) { var node = this.startNode(this.lookahead); var token = this.nextToken(); expr = this.inheritCoverGrammar(this.parseUnaryExpression); expr = this.finalize(node, new Node.UnaryExpression(token.value, expr)); if (this.context.strict && expr.operator === 'delete' && expr.argument.type === syntax_1.Syntax.Identifier) { this.tolerateError(messages_1.Messages.StrictDelete); } this.context.isAssignmentTarget = false; this.context.isBindingElement = false; } else if (this.context.await && this.matchContextualKeyword('await')) { expr = this.parseAwaitExpression(); } else { expr = this.parseUpdateExpression(); } return expr; }; Parser.prototype.parseExponentiationExpression = function () { var startToken = this.lookahead; var expr = this.inheritCoverGrammar(this.parseUnaryExpression); if (expr.type !== syntax_1.Syntax.UnaryExpression && this.match('**')) { this.nextToken(); this.context.isAssignmentTarget = false; this.context.isBindingElement = false; var left = expr; var right = this.isolateCoverGrammar(this.parseExponentiationExpression); expr = this.finalize(this.startNode(startToken), new Node.BinaryExpression('**', left, right)); } return expr; }; // https://tc39.github.io/ecma262/#sec-exp-operator // https://tc39.github.io/ecma262/#sec-multiplicative-operators // https://tc39.github.io/ecma262/#sec-additive-operators // https://tc39.github.io/ecma262/#sec-bitwise-shift-operators // https://tc39.github.io/ecma262/#sec-relational-operators // https://tc39.github.io/ecma262/#sec-equality-operators // https://tc39.github.io/ecma262/#sec-binary-bitwise-operators // https://tc39.github.io/ecma262/#sec-binary-logical-operators Parser.prototype.binaryPrecedence = function (token) { var op = token.value; var precedence; if (token.type === 7 /* Punctuator */) { precedence = this.operatorPrecedence[op] || 0; } else if (token.type === 4 /* Keyword */) { precedence = (op === 'instanceof' || (this.context.allowIn && op === 'in')) ? 7 : 0; } else { precedence = 0; } return precedence; }; Parser.prototype.parseBinaryExpression = function () { var startToken = this.lookahead; var expr = this.inheritCoverGrammar(this.parseExponentiationExpression); var token = this.lookahead; var prec = this.binaryPrecedence(token); if (prec > 0) { this.nextToken(); this.context.isAssignmentTarget = false; this.context.isBindingElement = false; var markers = [startToken, this.lookahead]; var left = expr; var right = this.isolateCoverGrammar(this.parseExponentiationExpression); var stack = [left, token.value, right]; var precedences = [prec]; while (true) { prec = this.binaryPrecedence(this.lookahead); if (prec <= 0) { break; } // Reduce: make a binary expression from the three topmost entries. while ((stack.length > 2) && (prec <= precedences[precedences.length - 1])) { right = stack.pop(); var operator = stack.pop(); precedences.pop(); left = stack.pop(); markers.pop(); var node = this.startNode(markers[markers.length - 1]); stack.push(this.finalize(node, new Node.BinaryExpression(operator, left, right))); } // Shift. stack.push(this.nextToken().value); precedences.push(prec); markers.push(this.lookahead); stack.push(this.isolateCoverGrammar(this.parseExponentiationExpression)); } // Final reduce to clean-up the stack. var i = stack.length - 1; expr = stack[i]; var lastMarker = markers.pop(); while (i > 1) { var marker = markers.pop(); var lastLineStart = lastMarker && lastMarker.lineStart; var node = this.startNode(marker, lastLineStart); var operator = stack[i - 1]; expr = this.finalize(node, new Node.BinaryExpression(operator, stack[i - 2], expr)); i -= 2; lastMarker = marker; } } return expr; }; // https://tc39.github.io/ecma262/#sec-conditional-operator Parser.prototype.parseConditionalExpression = function () { var startToken = this.lookahead; var expr = this.inheritCoverGrammar(this.parseBinaryExpression); if (this.match('?')) { this.nextToken(); var previousAllowIn = this.context.allowIn; this.context.allowIn = true; var consequent = this.isolateCoverGrammar(this.parseAssignmentExpression); this.context.allowIn = previousAllowIn; this.expect(':'); var alternate = this.isolateCoverGrammar(this.parseAssignmentExpression); expr = this.finalize(this.startNode(startToken), new Node.ConditionalExpression(expr, consequent, alternate)); this.context.isAssignmentTarget = false; this.context.isBindingElement = false; } return expr; }; // https://tc39.github.io/ecma262/#sec-assignment-operators Parser.prototype.checkPatternParam = function (options, param) { switch (param.type) { case syntax_1.Syntax.Identifier: this.validateParam(options, param, param.name); break; case syntax_1.Syntax.RestElement: this.checkPatternParam(options, param.argument); break; case syntax_1.Syntax.AssignmentPattern: this.checkPatternParam(options, param.left); break; case syntax_1.Syntax.ArrayPattern: for (var i = 0; i < param.elements.length; i++) { if (param.elements[i] !== null) { this.checkPatternParam(options, param.elements[i]); } } break; case syntax_1.Syntax.ObjectPattern: for (var i = 0; i < param.properties.length; i++) { this.checkPatternParam(options, param.properties[i].value); } break; default: break; } options.simple = options.simple && (param instanceof Node.Identifier); }; Parser.prototype.reinterpretAsCoverFormalsList = function (expr) { var params = [expr]; var options; var asyncArrow = false; switch (expr.type) { case syntax_1.Syntax.Identifier: break; case ArrowParameterPlaceHolder: params = expr.params; asyncArrow = expr.async; break; default: return null; } options = { simple: true, paramSet: {} }; for (var i = 0; i < params.length; ++i) { var param = params[i]; if (param.type === syntax_1.Syntax.AssignmentPattern) { if (param.right.type === syntax_1.Syntax.YieldExpression) { if (param.right.argument) { this.throwUnexpectedToken(this.lookahead); } param.right.type = syntax_1.Syntax.Identifier; param.right.name = 'yield'; delete param.right.argument; delete param.right.delegate; } } else if (asyncArrow && param.type === syntax_1.Syntax.Identifier && param.name === 'await') { this.throwUnexpectedToken(this.lookahead); } this.checkPatternParam(options, param); params[i] = param; } if (this.context.strict || !this.context.allowYield) { for (var i = 0; i < params.length; ++i) { var param = params[i]; if (param.type === syntax_1.Syntax.YieldExpression) { this.throwUnexpectedToken(this.lookahead); } } } if (options.message === messages_1.Messages.StrictParamDupe) { var token = this.context.strict ? options.stricted : options.firstRestricted; this.throwUnexpectedToken(token, options.message); } return { simple: options.simple, params: params, stricted: options.stricted, firstRestricted: options.firstRestricted, message: options.message }; }; Parser.prototype.parseAssignmentExpression = function () { var expr; if (!this.context.allowYield && this.matchKeyword('yield')) { expr = this.parseYieldExpression(); } else { var startToken = this.lookahead; var token = startToken; expr = this.parseConditionalExpression(); if (token.type === 3 /* Identifier */ && (token.lineNumber === this.lookahead.lineNumber) && token.value === 'async') { if (this.lookahead.type === 3 /* Identifier */ || this.matchKeyword('yield')) { var arg = this.parsePrimaryExpression(); this.reinterpretExpressionAsPattern(arg); expr = { type: ArrowParameterPlaceHolder, params: [arg], async: true }; } } if (expr.type === ArrowParameterPlaceHolder || this.match('=>')) { // https://tc39.github.io/ecma262/#sec-arrow-function-definitions this.context.isAssignmentTarget = false; this.context.isBindingElement = false; var isAsync = expr.async; var list = this.reinterpretAsCoverFormalsList(expr); if (list) { if (this.hasLineTerminator) { this.tolerateUnexpectedToken(this.lookahead); } this.context.firstCoverInitializedNameError = null; var previousStrict = this.context.strict; var previousAllowStrictDirective = this.context.allowStrictDirective; this.context.allowStrictDirective = list.simple; var previousAllowYield = this.context.allowYield; var previousAwait = this.context.await; this.context.allowYield = true; this.context.await = isAsync; var node = this.startNode(startToken); this.expect('=>'); var body = void 0; if (this.match('{')) { var previousAllowIn = this.context.allowIn; this.context.allowIn = true; body = this.parseFunctionSourceElements(); this.context.allowIn = previousAllowIn; } else { body = this.isolateCoverGrammar(this.parseAssignmentExpression); } var expression = body.type !== syntax_1.Syntax.BlockStatement; if (this.context.strict && list.firstRestricted) { this.throwUnexpectedToken(list.firstRestricted, list.message); } if (this.context.strict && list.stricted) { this.tolerateUnexpectedToken(list.stricted, list.message); } expr = isAsync ? this.finalize(node, new Node.AsyncArrowFunctionExpression(list.params, body, expression)) : this.finalize(node, new Node.ArrowFunctionExpression(list.params, body, expression)); this.context.strict = previousStrict; this.context.allowStrictDirective = previousAllowStrictDirective; this.context.allowYield = previousAllowYield; this.context.await = previousAwait; } } else { if (this.matchAssign()) { if (!this.context.isAssignmentTarget) { this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); } if (this.context.strict && expr.type === syntax_1.Syntax.Identifier) { var id = expr; if (this.scanner.isRestrictedWord(id.name)) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictLHSAssignment); } if (this.scanner.isStrictModeReservedWord(id.name)) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); } } if (!this.match('=')) { this.context.isAssignmentTarget = false; this.context.isBindingElement = false; } else { this.reinterpretExpressionAsPattern(expr); } token = this.nextToken(); var operator = token.value; var right = this.isolateCoverGrammar(this.parseAssignmentExpression); expr = this.finalize(this.startNode(startToken), new Node.AssignmentExpression(operator, expr, right)); this.context.firstCoverInitializedNameError = null; } } } return expr; }; // https://tc39.github.io/ecma262/#sec-comma-operator Parser.prototype.parseExpression = function () { var startToken = this.lookahead; var expr = this.isolateCoverGrammar(this.parseAssignmentExpression); if (this.match(',')) { var expressions = []; expressions.push(expr); while (this.lookahead.type !== 2 /* EOF */) { if (!this.match(',')) { break; } this.nextToken(); expressions.push(this.isolateCoverGrammar(this.parseAssignmentExpression)); } expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions)); } return expr; }; // https://tc39.github.io/ecma262/#sec-block Parser.prototype.parseStatementListItem = function () { var statement; this.context.isAssignmentTarget = true; this.context.isBindingElement = true; if (this.lookahead.type === 4 /* Keyword */) { switch (this.lookahead.value) { case 'export': if (!this.context.isModule) { this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalExportDeclaration); } statement = this.parseExportDeclaration(); break; case 'import': if (!this.context.isModule) { this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalImportDeclaration); } statement = this.parseImportDeclaration(); break; case 'const': statement = this.parseLexicalDeclaration({ inFor: false }); break; case 'function': statement = this.parseFunctionDeclaration(); break; case 'class': statement = this.parseClassDeclaration(); break; case 'let': statement = this.isLexicalDeclaration() ? this.parseLexicalDeclaration({ inFor: false }) : this.parseStatement(); break; default: statement = this.parseStatement(); break; } } else { statement = this.parseStatement(); } return statement; }; Parser.prototype.parseBlock = function () { var node = this.createNode(); this.expect('{'); var block = []; while (true) { if (this.match('}')) { break; } block.push(this.parseStatementListItem()); } this.expect('}'); return this.finalize(node, new Node.BlockStatement(block)); }; // https://tc39.github.io/ecma262/#sec-let-and-const-declarations Parser.prototype.parseLexicalBinding = function (kind, options) { var node = this.createNode(); var params = []; var id = this.parsePattern(params, kind); if (this.context.strict && id.type === syntax_1.Syntax.Identifier) { if (this.scanner.isRestrictedWord(id.name)) { this.tolerateError(messages_1.Messages.StrictVarName); } } var init = null; if (kind === 'const') { if (!this.matchKeyword('in') && !this.matchContextualKeyword('of')) { if (this.match('=')) { this.nextToken(); init = this.isolateCoverGrammar(this.parseAssignmentExpression); } else { this.throwError(messages_1.Messages.DeclarationMissingInitializer, 'const'); } } } else if ((!options.inFor && id.type !== syntax_1.Syntax.Identifier) || this.match('=')) { this.expect('='); init = this.isolateCoverGrammar(this.parseAssignmentExpression); } return this.finalize(node, new Node.VariableDeclarator(id, init)); }; Parser.prototype.parseBindingList = function (kind, options) { var list = [this.parseLexicalBinding(kind, options)]; while (this.match(',')) { this.nextToken(); list.push(this.parseLexicalBinding(kind, options)); } return list; }; Parser.prototype.isLexicalDeclaration = function () { var state = this.scanner.saveState(); this.scanner.scanComments(); var next = this.scanner.lex(); this.scanner.restoreState(state); return (next.type === 3 /* Identifier */) || (next.type === 7 /* Punctuator */ && next.value === '[') || (next.type === 7 /* Punctuator */ && next.value === '{') || (next.type === 4 /* Keyword */ && next.value === 'let') || (next.type === 4 /* Keyword */ && next.value === 'yield'); }; Parser.prototype.parseLexicalDeclaration = function (options) { var node = this.createNode(); var kind = this.nextToken().value; assert_1.assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const'); var declarations = this.parseBindingList(kind, options); this.consumeSemicolon(); return this.finalize(node, new Node.VariableDeclaration(declarations, kind)); }; // https://tc39.github.io/ecma262/#sec-destructuring-binding-patterns Parser.prototype.parseBindingRestElement = function (params, kind) { var node = this.createNode(); this.expect('...'); var arg = this.parsePattern(params, kind); return this.finalize(node, new Node.RestElement(arg)); }; Parser.prototype.parseArrayPattern = function (params, kind) { var node = this.createNode(); this.expect('['); var elements = []; while (!this.match(']')) { if (this.match(',')) { this.nextToken(); elements.push(null); } else { if (this.match('...')) { elements.push(this.parseBindingRestElement(params, kind)); break; } else { elements.push(this.parsePatternWithDefault(params, kind)); } if (!this.match(']')) { this.expect(','); } } } this.expect(']'); return this.finalize(node, new Node.ArrayPattern(elements)); }; Parser.prototype.parsePropertyPattern = function (params, kind) { var node = this.createNode(); var computed = false; var shorthand = false; var method = false; var key; var value; if (this.lookahead.type === 3 /* Identifier */) { var keyToken = this.lookahead; key = this.parseVariableIdentifier(); var init = this.finalize(node, new Node.Identifier(keyToken.value)); if (this.match('=')) { params.push(keyToken); shorthand = true; this.nextToken(); var expr = this.parseAssignmentExpression(); value = this.finalize(this.startNode(keyToken), new Node.AssignmentPattern(init, expr)); } else if (!this.match(':')) { params.push(keyToken); shorthand = true; value = init; } else { this.expect(':'); value = this.parsePatternWithDefault(params, kind); } } else { computed = this.match('['); key = this.parseObjectPropertyKey(); this.expect(':'); value = this.parsePatternWithDefault(params, kind); } return this.finalize(node, new Node.Property('init', key, computed, value, method, shorthand)); }; Parser.prototype.parseObjectPattern = function (params, kind) { var node = this.createNode(); var properties = []; this.expect('{'); while (!this.match('}')) { properties.push(this.parsePropertyPattern(params, kind)); if (!this.match('}')) { this.expect(','); } } this.expect('}'); return this.finalize(node, new Node.ObjectPattern(properties)); }; Parser.prototype.parsePattern = function (params, kind) { var pattern; if (this.match('[')) { pattern = this.parseArrayPattern(params, kind); } else if (this.match('{')) { pattern = this.parseObjectPattern(params, kind); } else { if (this.matchKeyword('let') && (kind === 'const' || kind === 'let')) { this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.LetInLexicalBinding); } params.push(this.lookahead); pattern = this.parseVariableIdentifier(kind); } return pattern; }; Parser.prototype.parsePatternWithDefault = function (params, kind) { var startToken = this.lookahead; var pattern = this.parsePattern(params, kind); if (this.match('=')) { this.nextToken(); var previousAllowYield = this.context.allowYield; this.context.allowYield = true; var right = this.isolateCoverGrammar(this.parseAssignmentExpression); this.context.allowYield = previousAllowYield; pattern = this.finalize(this.startNode(startToken), new Node.AssignmentPattern(pattern, right)); } return pattern; }; // https://tc39.github.io/ecma262/#sec-variable-statement Parser.prototype.parseVariableIdentifier = function (kind) { var node = this.createNode(); var token = this.nextToken(); if (token.type === 4 /* Keyword */ && token.value === 'yield') { if (this.context.strict) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); } else if (!this.context.allowYield) { this.throwUnexpectedToken(token); } } else if (token.type !== 3 /* Identifier */) { if (this.context.strict && token.type === 4 /* Keyword */ && this.scanner.isStrictModeReservedWord(token.value)) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); } else { if (this.context.strict || token.value !== 'let' || kind !== 'var') { this.throwUnexpectedToken(token); } } } else if ((this.context.isModule || this.context.await) && token.type === 3 /* Identifier */ && token.value === 'await') { this.tolerateUnexpectedToken(token); } return this.finalize(node, new Node.Identifier(token.value)); }; Parser.prototype.parseVariableDeclaration = function (options) { var node = this.createNode(); var params = []; var id = this.parsePattern(params, 'var'); if (this.context.strict && id.type === syntax_1.Syntax.Identifier) { if (this.scanner.isRestrictedWord(id.name)) { this.tolerateError(messages_1.Messages.StrictVarName); } } var init = null; if (this.match('=')) { this.nextToken(); init = this.isolateCoverGrammar(this.parseAssignmentExpression); } else if (id.type !== syntax_1.Syntax.Identifier && !options.inFor) { this.expect('='); } return this.finalize(node, new Node.VariableDeclarator(id, init)); }; Parser.prototype.parseVariableDeclarationList = function (options) { var opt = { inFor: options.inFor }; var list = []; list.push(this.parseVariableDeclaration(opt)); while (this.match(',')) { this.nextToken(); list.push(this.parseVariableDeclaration(opt)); } return list; }; Parser.prototype.parseVariableStatement = function () { var node = this.createNode(); this.expectKeyword('var'); var declarations = this.parseVariableDeclarationList({ inFor: false }); this.consumeSemicolon(); return this.finalize(node, new Node.VariableDeclaration(declarations, 'var')); }; // https://tc39.github.io/ecma262/#sec-empty-statement Parser.prototype.parseEmptyStatement = function () { var node = this.createNode(); this.expect(';'); return this.finalize(node, new Node.EmptyStatement()); }; // https://tc39.github.io/ecma262/#sec-expression-statement Parser.prototype.parseExpressionStatement = function () { var node = this.createNode(); var expr = this.parseExpression(); this.consumeSemicolon(); return this.finalize(node, new Node.ExpressionStatement(expr)); }; // https://tc39.github.io/ecma262/#sec-if-statement Parser.prototype.parseIfClause = function () { if (this.context.strict && this.matchKeyword('function')) { this.tolerateError(messages_1.Messages.StrictFunction); } return this.parseStatement(); }; Parser.prototype.parseIfStatement = function () { var node = this.createNode(); var consequent; var alternate = null; this.expectKeyword('if'); this.expect('('); var test = this.parseExpression(); if (!this.match(')') && this.config.tolerant) { this.tolerateUnexpectedToken(this.nextToken()); consequent = this.finalize(this.createNode(), new Node.EmptyStatement()); } else { this.expect(')'); consequent = this.parseIfClause(); if (this.matchKeyword('else')) { this.nextToken(); alternate = this.parseIfClause(); } } return this.finalize(node, new Node.IfStatement(test, consequent, alternate)); }; // https://tc39.github.io/ecma262/#sec-do-while-statement Parser.prototype.parseDoWhileStatement = function () { var node = this.createNode(); this.expectKeyword('do'); var previousInIteration = this.context.inIteration; this.context.inIteration = true; var body = this.parseStatement(); this.context.inIteration = previousInIteration; this.expectKeyword('while'); this.expect('('); var test = this.parseExpression(); if (!this.match(')') && this.config.tolerant) { this.tolerateUnexpectedToken(this.nextToken()); } else { this.expect(')'); if (this.match(';')) { this.nextToken(); } } return this.finalize(node, new Node.DoWhileStatement(body, test)); }; // https://tc39.github.io/ecma262/#sec-while-statement Parser.prototype.parseWhileStatement = function () { var node = this.createNode(); var body; this.expectKeyword('while'); this.expect('('); var test = this.parseExpression(); if (!this.match(')') && this.config.tolerant) { this.tolerateUnexpectedToken(this.nextToken()); body = this.finalize(this.createNode(), new Node.EmptyStatement()); } else { this.expect(')'); var previousInIteration = this.context.inIteration; this.context.inIteration = true; body = this.parseStatement(); this.context.inIteration = previousInIteration; } return this.finalize(node, new Node.WhileStatement(test, body)); }; // https://tc39.github.io/ecma262/#sec-for-statement // https://tc39.github.io/ecma262/#sec-for-in-and-for-of-statements Parser.prototype.parseForStatement = function () { var init = null; var test = null; var update = null; var forIn = true; var left, right; var node = this.createNode(); this.expectKeyword('for'); this.expect('('); if (this.match(';')) { this.nextToken(); } else { if (this.matchKeyword('var')) { init = this.createNode(); this.nextToken(); var previousAllowIn = this.context.allowIn; this.context.allowIn = false; var declarations = this.parseVariableDeclarationList({ inFor: true }); this.context.allowIn = previousAllowIn; if (declarations.length === 1 && this.matchKeyword('in')) { var decl = declarations[0]; if (decl.init && (decl.id.type === syntax_1.Syntax.ArrayPattern || decl.id.type === syntax_1.Syntax.ObjectPattern || this.context.strict)) { this.tolerateError(messages_1.Messages.ForInOfLoopInitializer, 'for-in'); } init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); this.nextToken(); left = init; right = this.parseExpression(); init = null; } else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) { init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); this.nextToken(); left = init; right = this.parseAssignmentExpression(); init = null; forIn = false; } else { init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); this.expect(';'); } } else if (this.matchKeyword('const') || this.matchKeyword('let')) { init = this.createNode(); var kind = this.nextToken().value; if (!this.context.strict && this.lookahead.value === 'in') { init = this.finalize(init, new Node.Identifier(kind)); this.nextToken(); left = init; right = this.parseExpression(); init = null; } else { var previousAllowIn = this.context.allowIn; this.context.allowIn = false; var declarations = this.parseBindingList(kind, { inFor: true }); this.context.allowIn = previousAllowIn; if (declarations.length === 1 && declarations[0].init === null && this.matchKeyword('in')) { init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); this.nextToken(); left = init; right = this.parseExpression(); init = null; } else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) { init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); this.nextToken(); left = init; right = this.parseAssignmentExpression(); init = null; forIn = false; } else { this.consumeSemicolon(); init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); } } } else { var initStartToken = this.lookahead; var previousAllowIn = this.context.allowIn; this.context.allowIn = false; init = this.inheritCoverGrammar(this.parseAssignmentExpression); this.context.allowIn = previousAllowIn; if (this.matchKeyword('in')) { if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) { this.tolerateError(messages_1.Messages.InvalidLHSInForIn); } this.nextToken(); this.reinterpretExpressionAsPattern(init); left = init; right = this.parseExpression(); init = null; } else if (this.matchContextualKeyword('of')) { if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) { this.tolerateError(messages_1.Messages.InvalidLHSInForLoop); } this.nextToken(); this.reinterpretExpressionAsPattern(init); left = init; right = this.parseAssignmentExpression(); init = null; forIn = false; } else { if (this.match(',')) { var initSeq = [init]; while (this.match(',')) { this.nextToken(); initSeq.push(this.isolateCoverGrammar(this.parseAssignmentExpression)); } init = this.finalize(this.startNode(initStartToken), new Node.SequenceExpression(initSeq)); } this.expect(';'); } } } if (typeof left === 'undefined') { if (!this.match(';')) { test = this.parseExpression(); } this.expect(';'); if (!this.match(')')) { update = this.parseExpression(); } } var body; if (!this.match(')') && this.config.tolerant) { this.tolerateUnexpectedToken(this.nextToken()); body = this.finalize(this.createNode(), new Node.EmptyStatement()); } else { this.expect(')'); var previousInIteration = this.context.inIteration; this.context.inIteration = true; body = this.isolateCoverGrammar(this.parseStatement); this.context.inIteration = previousInIteration; } return (typeof left === 'undefined') ? this.finalize(node, new Node.ForStatement(init, test, update, body)) : forIn ? this.finalize(node, new Node.ForInStatement(left, right, body)) : this.finalize(node, new Node.ForOfStatement(left, right, body)); }; // https://tc39.github.io/ecma262/#sec-continue-statement Parser.prototype.parseContinueStatement = function () { var node = this.createNode(); this.expectKeyword('continue'); var label = null; if (this.lookahead.type === 3 /* Identifier */ && !this.hasLineTerminator) { var id = this.parseVariableIdentifier(); label = id; var key = '$' + id.name; if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { this.throwError(messages_1.Messages.UnknownLabel, id.name); } } this.consumeSemicolon(); if (label === null && !this.context.inIteration) { this.throwError(messages_1.Messages.IllegalContinue); } return this.finalize(node, new Node.ContinueStatement(label)); }; // https://tc39.github.io/ecma262/#sec-break-statement Parser.prototype.parseBreakStatement = function () { var node = this.createNode(); this.expectKeyword('break'); var label = null; if (this.lookahead.type === 3 /* Identifier */ && !this.hasLineTerminator) { var id = this.parseVariableIdentifier(); var key = '$' + id.name; if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { this.throwError(messages_1.Messages.UnknownLabel, id.name); } label = id; } this.consumeSemicolon(); if (label === null && !this.context.inIteration && !this.context.inSwitch) { this.throwError(messages_1.Messages.IllegalBreak); } return this.finalize(node, new Node.BreakStatement(label)); }; // https://tc39.github.io/ecma262/#sec-return-statement Parser.prototype.parseReturnStatement = function () { if (!this.context.inFunctionBody) { this.tolerateError(messages_1.Messages.IllegalReturn); } var node = this.createNode(); this.expectKeyword('return'); var hasArgument = (!this.match(';') && !this.match('}') && !this.hasLineTerminator && this.lookahead.type !== 2 /* EOF */) || this.lookahead.type === 8 /* StringLiteral */ || this.lookahead.type === 10 /* Template */; var argument = hasArgument ? this.parseExpression() : null; this.consumeSemicolon(); return this.finalize(node, new Node.ReturnStatement(argument)); }; // https://tc39.github.io/ecma262/#sec-with-statement Parser.prototype.parseWithStatement = function () { if (this.context.strict) { this.tolerateError(messages_1.Messages.StrictModeWith); } var node = this.createNode(); var body; this.expectKeyword('with'); this.expect('('); var object = this.parseExpression(); if (!this.match(')') && this.config.tolerant) { this.tolerateUnexpectedToken(this.nextToken()); body = this.finalize(this.createNode(), new Node.EmptyStatement()); } else { this.expect(')'); body = this.parseStatement(); } return this.finalize(node, new Node.WithStatement(object, body)); }; // https://tc39.github.io/ecma262/#sec-switch-statement Parser.prototype.parseSwitchCase = function () { var node = this.createNode(); var test; if (this.matchKeyword('default')) { this.nextToken(); test = null; } else { this.expectKeyword('case'); test = this.parseExpression(); } this.expect(':'); var consequent = []; while (true) { if (this.match('}') || this.matchKeyword('default') || this.matchKeyword('case')) { break; } consequent.push(this.parseStatementListItem()); } return this.finalize(node, new Node.SwitchCase(test, consequent)); }; Parser.prototype.parseSwitchStatement = function () { var node = this.createNode(); this.expectKeyword('switch'); this.expect('('); var discriminant = this.parseExpression(); this.expect(')'); var previousInSwitch = this.context.inSwitch; this.context.inSwitch = true; var cases = []; var defaultFound = false; this.expect('{'); while (true) { if (this.match('}')) { break; } var clause = this.parseSwitchCase(); if (clause.test === null) { if (defaultFound) { this.throwError(messages_1.Messages.MultipleDefaultsInSwitch); } defaultFound = true; } cases.push(clause); } this.expect('}'); this.context.inSwitch = previousInSwitch; return this.finalize(node, new Node.SwitchStatement(discriminant, cases)); }; // https://tc39.github.io/ecma262/#sec-labelled-statements Parser.prototype.parseLabelledStatement = function () { var node = this.createNode(); var expr = this.parseExpression(); var statement; if ((expr.type === syntax_1.Syntax.Identifier) && this.match(':')) { this.nextToken(); var id = expr; var key = '$' + id.name; if (Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { this.throwError(messages_1.Messages.Redeclaration, 'Label', id.name); } this.context.labelSet[key] = true; var body = void 0; if (this.matchKeyword('class')) { this.tolerateUnexpectedToken(this.lookahead); body = this.parseClassDeclaration(); } else if (this.matchKeyword('function')) { var token = this.lookahead; var declaration = this.parseFunctionDeclaration(); if (this.context.strict) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunction); } else if (declaration.generator) { this.tolerateUnexpectedToken(token, messages_1.Messages.GeneratorInLegacyContext); } body = declaration; } else { body = this.parseStatement(); } delete this.context.labelSet[key]; statement = new Node.LabeledStatement(id, body); } else { this.consumeSemicolon(); statement = new Node.ExpressionStatement(expr); } return this.finalize(node, statement); }; // https://tc39.github.io/ecma262/#sec-throw-statement Parser.prototype.parseThrowStatement = function () { var node = this.createNode(); this.expectKeyword('throw'); if (this.hasLineTerminator) { this.throwError(messages_1.Messages.NewlineAfterThrow); } var argument = this.parseExpression(); this.consumeSemicolon(); return this.finalize(node, new Node.ThrowStatement(argument)); }; // https://tc39.github.io/ecma262/#sec-try-statement Parser.prototype.parseCatchClause = function () { var node = this.createNode(); this.expectKeyword('catch'); this.expect('('); if (this.match(')')) { this.throwUnexpectedToken(this.lookahead); } var params = []; var param = this.parsePattern(params); var paramMap = {}; for (var i = 0; i < params.length; i++) { var key = '$' + params[i].value; if (Object.prototype.hasOwnProperty.call(paramMap, key)) { this.tolerateError(messages_1.Messages.DuplicateBinding, params[i].value); } paramMap[key] = true; } if (this.context.strict && param.type === syntax_1.Syntax.Identifier) { if (this.scanner.isRestrictedWord(param.name)) { this.tolerateError(messages_1.Messages.StrictCatchVariable); } } this.expect(')'); var body = this.parseBlock(); return this.finalize(node, new Node.CatchClause(param, body)); }; Parser.prototype.parseFinallyClause = function () { this.expectKeyword('finally'); return this.parseBlock(); }; Parser.prototype.parseTryStatement = function () { var node = this.createNode(); this.expectKeyword('try'); var block = this.parseBlock(); var handler = this.matchKeyword('catch') ? this.parseCatchClause() : null; var finalizer = this.matchKeyword('finally') ? this.parseFinallyClause() : null; if (!handler && !finalizer) { this.throwError(messages_1.Messages.NoCatchOrFinally); } return this.finalize(node, new Node.TryStatement(block, handler, finalizer)); }; // https://tc39.github.io/ecma262/#sec-debugger-statement Parser.prototype.parseDebuggerStatement = function () { var node = this.createNode(); this.expectKeyword('debugger'); this.consumeSemicolon(); return this.finalize(node, new Node.DebuggerStatement()); }; // https://tc39.github.io/ecma262/#sec-ecmascript-language-statements-and-declarations Parser.prototype.parseStatement = function () { var statement; switch (this.lookahead.type) { case 1 /* BooleanLiteral */: case 5 /* NullLiteral */: case 6 /* NumericLiteral */: case 8 /* StringLiteral */: case 10 /* Template */: case 9 /* RegularExpression */: statement = this.parseExpressionStatement(); break; case 7 /* Punctuator */: var value = this.lookahead.value; if (value === '{') { statement = this.parseBlock(); } else if (value === '(') { statement = this.parseExpressionStatement(); } else if (value === ';') { statement = this.parseEmptyStatement(); } else { statement = this.parseExpressionStatement(); } break; case 3 /* Identifier */: statement = this.matchAsyncFunction() ? this.parseFunctionDeclaration() : this.parseLabelledStatement(); break; case 4 /* Keyword */: switch (this.lookahead.value) { case 'break': statement = this.parseBreakStatement(); break; case 'continue': statement = this.parseContinueStatement(); break; case 'debugger': statement = this.parseDebuggerStatement(); break; case 'do': statement = this.parseDoWhileStatement(); break; case 'for': statement = this.parseForStatement(); break; case 'function': statement = this.parseFunctionDeclaration(); break; case 'if': statement = this.parseIfStatement(); break; case 'return': statement = this.parseReturnStatement(); break; case 'switch': statement = this.parseSwitchStatement(); break; case 'throw': statement = this.parseThrowStatement(); break; case 'try': statement = this.parseTryStatement(); break; case 'var': statement = this.parseVariableStatement(); break; case 'while': statement = this.parseWhileStatement(); break; case 'with': statement = this.parseWithStatement(); break; default: statement = this.parseExpressionStatement(); break; } break; default: statement = this.throwUnexpectedToken(this.lookahead); } return statement; }; // https://tc39.github.io/ecma262/#sec-function-definitions Parser.prototype.parseFunctionSourceElements = function () { var node = this.createNode(); this.expect('{'); var body = this.parseDirectivePrologues(); var previousLabelSet = this.context.labelSet; var previousInIteration = this.context.inIteration; var previousInSwitch = this.context.inSwitch; var previousInFunctionBody = this.context.inFunctionBody; this.context.labelSet = {}; this.context.inIteration = false; this.context.inSwitch = false; this.context.inFunctionBody = true; while (this.lookahead.type !== 2 /* EOF */) { if (this.match('}')) { break; } body.push(this.parseStatementListItem()); } this.expect('}'); this.context.labelSet = previousLabelSet; this.context.inIteration = previousInIteration; this.context.inSwitch = previousInSwitch; this.context.inFunctionBody = previousInFunctionBody; return this.finalize(node, new Node.BlockStatement(body)); }; Parser.prototype.validateParam = function (options, param, name) { var key = '$' + name; if (this.context.strict) { if (this.scanner.isRestrictedWord(name)) { options.stricted = param; options.message = messages_1.Messages.StrictParamName; } if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { options.stricted = param; options.message = messages_1.Messages.StrictParamDupe; } } else if (!options.firstRestricted) { if (this.scanner.isRestrictedWord(name)) { options.firstRestricted = param; options.message = messages_1.Messages.StrictParamName; } else if (this.scanner.isStrictModeReservedWord(name)) { options.firstRestricted = param; options.message = messages_1.Messages.StrictReservedWord; } else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { options.stricted = param; options.message = messages_1.Messages.StrictParamDupe; } } /* istanbul ignore next */ if (typeof Object.defineProperty === 'function') { Object.defineProperty(options.paramSet, key, { value: true, enumerable: true, writable: true, configurable: true }); } else { options.paramSet[key] = true; } }; Parser.prototype.parseRestElement = function (params) { var node = this.createNode(); this.expect('...'); var arg = this.parsePattern(params); if (this.match('=')) { this.throwError(messages_1.Messages.DefaultRestParameter); } if (!this.match(')')) { this.throwError(messages_1.Messages.ParameterAfterRestParameter); } return this.finalize(node, new Node.RestElement(arg)); }; Parser.prototype.parseFormalParameter = function (options) { var params = []; var param = this.match('...') ? this.parseRestElement(params) : this.parsePatternWithDefault(params); for (var i = 0; i < params.length; i++) { this.validateParam(options, params[i], params[i].value); } options.simple = options.simple && (param instanceof Node.Identifier); options.params.push(param); }; Parser.prototype.parseFormalParameters = function (firstRestricted) { var options; options = { simple: true, params: [], firstRestricted: firstRestricted }; this.expect('('); if (!this.match(')')) { options.paramSet = {}; while (this.lookahead.type !== 2 /* EOF */) { this.parseFormalParameter(options); if (this.match(')')) { break; } this.expect(','); if (this.match(')')) { break; } } } this.expect(')'); return { simple: options.simple, params: options.params, stricted: options.stricted, firstRestricted: options.firstRestricted, message: options.message }; }; Parser.prototype.matchAsyncFunction = function () { var match = this.matchContextualKeyword('async'); if (match) { var state = this.scanner.saveState(); this.scanner.scanComments(); var next = this.scanner.lex(); this.scanner.restoreState(state); match = (state.lineNumber === next.lineNumber) && (next.type === 4 /* Keyword */) && (next.value === 'function'); } return match; }; Parser.prototype.parseFunctionDeclaration = function (identifierIsOptional) { var node = this.createNode(); var isAsync = this.matchContextualKeyword('async'); if (isAsync) { this.nextToken(); } this.expectKeyword('function'); var isGenerator = isAsync ? false : this.match('*'); if (isGenerator) { this.nextToken(); } var message; var id = null; var firstRestricted = null; if (!identifierIsOptional || !this.match('(')) { var token = this.lookahead; id = this.parseVariableIdentifier(); if (this.context.strict) { if (this.scanner.isRestrictedWord(token.value)) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName); } } else { if (this.scanner.isRestrictedWord(token.value)) { firstRestricted = token; message = messages_1.Messages.StrictFunctionName; } else if (this.scanner.isStrictModeReservedWord(token.value)) { firstRestricted = token; message = messages_1.Messages.StrictReservedWord; } } } var previousAllowAwait = this.context.await; var previousAllowYield = this.context.allowYield; this.context.await = isAsync; this.context.allowYield = !isGenerator; var formalParameters = this.parseFormalParameters(firstRestricted); var params = formalParameters.params; var stricted = formalParameters.stricted; firstRestricted = formalParameters.firstRestricted; if (formalParameters.message) { message = formalParameters.message; } var previousStrict = this.context.strict; var previousAllowStrictDirective = this.context.allowStrictDirective; this.context.allowStrictDirective = formalParameters.simple; var body = this.parseFunctionSourceElements(); if (this.context.strict && firstRestricted) { this.throwUnexpectedToken(firstRestricted, message); } if (this.context.strict && stricted) { this.tolerateUnexpectedToken(stricted, message); } this.context.strict = previousStrict; this.context.allowStrictDirective = previousAllowStrictDirective; this.context.await = previousAllowAwait; this.context.allowYield = previousAllowYield; return isAsync ? this.finalize(node, new Node.AsyncFunctionDeclaration(id, params, body)) : this.finalize(node, new Node.FunctionDeclaration(id, params, body, isGenerator)); }; Parser.prototype.parseFunctionExpression = function () { var node = this.createNode(); var isAsync = this.matchContextualKeyword('async'); if (isAsync) { this.nextToken(); } this.expectKeyword('function'); var isGenerator = isAsync ? false : this.match('*'); if (isGenerator) { this.nextToken(); } var message; var id = null; var firstRestricted; var previousAllowAwait = this.context.await; var previousAllowYield = this.context.allowYield; this.context.await = isAsync; this.context.allowYield = !isGenerator; if (!this.match('(')) { var token = this.lookahead; id = (!this.context.strict && !isGenerator && this.matchKeyword('yield')) ? this.parseIdentifierName() : this.parseVariableIdentifier(); if (this.context.strict) { if (this.scanner.isRestrictedWord(token.value)) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName); } } else { if (this.scanner.isRestrictedWord(token.value)) { firstRestricted = token; message = messages_1.Messages.StrictFunctionName; } else if (this.scanner.isStrictModeReservedWord(token.value)) { firstRestricted = token; message = messages_1.Messages.StrictReservedWord; } } } var formalParameters = this.parseFormalParameters(firstRestricted); var params = formalParameters.params; var stricted = formalParameters.stricted; firstRestricted = formalParameters.firstRestricted; if (formalParameters.message) { message = formalParameters.message; } var previousStrict = this.context.strict; var previousAllowStrictDirective = this.context.allowStrictDirective; this.context.allowStrictDirective = formalParameters.simple; var body = this.parseFunctionSourceElements(); if (this.context.strict && firstRestricted) { this.throwUnexpectedToken(firstRestricted, message); } if (this.context.strict && stricted) { this.tolerateUnexpectedToken(stricted, message); } this.context.strict = previousStrict; this.context.allowStrictDirective = previousAllowStrictDirective; this.context.await = previousAllowAwait; this.context.allowYield = previousAllowYield; return isAsync ? this.finalize(node, new Node.AsyncFunctionExpression(id, params, body)) : this.finalize(node, new Node.FunctionExpression(id, params, body, isGenerator)); }; // https://tc39.github.io/ecma262/#sec-directive-prologues-and-the-use-strict-directive Parser.prototype.parseDirective = function () { var token = this.lookahead; var node = this.createNode(); var expr = this.parseExpression(); var directive = (expr.type === syntax_1.Syntax.Literal) ? this.getTokenRaw(token).slice(1, -1) : null; this.consumeSemicolon(); return this.finalize(node, directive ? new Node.Directive(expr, directive) : new Node.ExpressionStatement(expr)); }; Parser.prototype.parseDirectivePrologues = function () { var firstRestricted = null; var body = []; while (true) { var token = this.lookahead; if (token.type !== 8 /* StringLiteral */) { break; } var statement = this.parseDirective(); body.push(statement); var directive = statement.directive; if (typeof directive !== 'string') { break; } if (directive === 'use strict') { this.context.strict = true; if (firstRestricted) { this.tolerateUnexpectedToken(firstRestricted, messages_1.Messages.StrictOctalLiteral); } if (!this.context.allowStrictDirective) { this.tolerateUnexpectedToken(token, messages_1.Messages.IllegalLanguageModeDirective); } } else { if (!firstRestricted && token.octal) { firstRestricted = token; } } } return body; }; // https://tc39.github.io/ecma262/#sec-method-definitions Parser.prototype.qualifiedPropertyName = function (token) { switch (token.type) { case 3 /* Identifier */: case 8 /* StringLiteral */: case 1 /* BooleanLiteral */: case 5 /* NullLiteral */: case 6 /* NumericLiteral */: case 4 /* Keyword */: return true; case 7 /* Punctuator */: return token.value === '['; default: break; } return false; }; Parser.prototype.parseGetterMethod = function () { var node = this.createNode(); var isGenerator = false; var previousAllowYield = this.context.allowYield; this.context.allowYield = !isGenerator; var formalParameters = this.parseFormalParameters(); if (formalParameters.params.length > 0) { this.tolerateError(messages_1.Messages.BadGetterArity); } var method = this.parsePropertyMethod(formalParameters); this.context.allowYield = previousAllowYield; return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator)); }; Parser.prototype.parseSetterMethod = function () { var node = this.createNode(); var isGenerator = false; var previousAllowYield = this.context.allowYield; this.context.allowYield = !isGenerator; var formalParameters = this.parseFormalParameters(); if (formalParameters.params.length !== 1) { this.tolerateError(messages_1.Messages.BadSetterArity); } else if (formalParameters.params[0] instanceof Node.RestElement) { this.tolerateError(messages_1.Messages.BadSetterRestParameter); } var method = this.parsePropertyMethod(formalParameters); this.context.allowYield = previousAllowYield; return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator)); }; Parser.prototype.parseGeneratorMethod = function () { var node = this.createNode(); var isGenerator = true; var previousAllowYield = this.context.allowYield; this.context.allowYield = true; var params = this.parseFormalParameters(); this.context.allowYield = false; var method = this.parsePropertyMethod(params); this.context.allowYield = previousAllowYield; return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator)); }; // https://tc39.github.io/ecma262/#sec-generator-function-definitions Parser.prototype.isStartOfExpression = function () { var start = true; var value = this.lookahead.value; switch (this.lookahead.type) { case 7 /* Punctuator */: start = (value === '[') || (value === '(') || (value === '{') || (value === '+') || (value === '-') || (value === '!') || (value === '~') || (value === '++') || (value === '--') || (value === '/') || (value === '/='); // regular expression literal break; case 4 /* Keyword */: start = (value === 'class') || (value === 'delete') || (value === 'function') || (value === 'let') || (value === 'new') || (value === 'super') || (value === 'this') || (value === 'typeof') || (value === 'void') || (value === 'yield'); break; default: break; } return start; }; Parser.prototype.parseYieldExpression = function () { var node = this.createNode(); this.expectKeyword('yield'); var argument = null; var delegate = false; if (!this.hasLineTerminator) { var previousAllowYield = this.context.allowYield; this.context.allowYield = false; delegate = this.match('*'); if (delegate) { this.nextToken(); argument = this.parseAssignmentExpression(); } else if (this.isStartOfExpression()) { argument = this.parseAssignmentExpression(); } this.context.allowYield = previousAllowYield; } return this.finalize(node, new Node.YieldExpression(argument, delegate)); }; // https://tc39.github.io/ecma262/#sec-class-definitions Parser.prototype.parseClassElement = function (hasConstructor) { var token = this.lookahead; var node = this.createNode(); var kind = ''; var key = null; var value = null; var computed = false; var method = false; var isStatic = false; var isAsync = false; if (this.match('*')) { this.nextToken(); } else { computed = this.match('['); key = this.parseObjectPropertyKey(); var id = key; if (id.name === 'static' && (this.qualifiedPropertyName(this.lookahead) || this.match('*'))) { token = this.lookahead; isStatic = true; computed = this.match('['); if (this.match('*')) { this.nextToken(); } else { key = this.parseObjectPropertyKey(); } } if ((token.type === 3 /* Identifier */) && !this.hasLineTerminator && (token.value === 'async')) { var punctuator = this.lookahead.value; if (punctuator !== ':' && punctuator !== '(' && punctuator !== '*') { isAsync = true; token = this.lookahead; key = this.parseObjectPropertyKey(); if (token.type === 3 /* Identifier */ && token.value === 'constructor') { this.tolerateUnexpectedToken(token, messages_1.Messages.ConstructorIsAsync); } } } } var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead); if (token.type === 3 /* Identifier */) { if (token.value === 'get' && lookaheadPropertyKey) { kind = 'get'; computed = this.match('['); key = this.parseObjectPropertyKey(); this.context.allowYield = false; value = this.parseGetterMethod(); } else if (token.value === 'set' && lookaheadPropertyKey) { kind = 'set'; computed = this.match('['); key = this.parseObjectPropertyKey(); value = this.parseSetterMethod(); } } else if (token.type === 7 /* Punctuator */ && token.value === '*' && lookaheadPropertyKey) { kind = 'init'; computed = this.match('['); key = this.parseObjectPropertyKey(); value = this.parseGeneratorMethod(); method = true; } if (!kind && key && this.match('(')) { kind = 'init'; value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction(); method = true; } if (!kind) { this.throwUnexpectedToken(this.lookahead); } if (kind === 'init') { kind = 'method'; } if (!computed) { if (isStatic && this.isPropertyKey(key, 'prototype')) { this.throwUnexpectedToken(token, messages_1.Messages.StaticPrototype); } if (!isStatic && this.isPropertyKey(key, 'constructor')) { if (kind !== 'method' || !method || (value && value.generator)) { this.throwUnexpectedToken(token, messages_1.Messages.ConstructorSpecialMethod); } if (hasConstructor.value) { this.throwUnexpectedToken(token, messages_1.Messages.DuplicateConstructor); } else { hasConstructor.value = true; } kind = 'constructor'; } } return this.finalize(node, new Node.MethodDefinition(key, computed, value, kind, isStatic)); }; Parser.prototype.parseClassElementList = function () { var body = []; var hasConstructor = { value: false }; this.expect('{'); while (!this.match('}')) { if (this.match(';')) { this.nextToken(); } else { body.push(this.parseClassElement(hasConstructor)); } } this.expect('}'); return body; }; Parser.prototype.parseClassBody = function () { var node = this.createNode(); var elementList = this.parseClassElementList(); return this.finalize(node, new Node.ClassBody(elementList)); }; Parser.prototype.parseClassDeclaration = function (identifierIsOptional) { var node = this.createNode(); var previousStrict = this.context.strict; this.context.strict = true; this.expectKeyword('class'); var id = (identifierIsOptional && (this.lookahead.type !== 3 /* Identifier */)) ? null : this.parseVariableIdentifier(); var superClass = null; if (this.matchKeyword('extends')) { this.nextToken(); superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall); } var classBody = this.parseClassBody(); this.context.strict = previousStrict; return this.finalize(node, new Node.ClassDeclaration(id, superClass, classBody)); }; Parser.prototype.parseClassExpression = function () { var node = this.createNode(); var previousStrict = this.context.strict; this.context.strict = true; this.expectKeyword('class'); var id = (this.lookahead.type === 3 /* Identifier */) ? this.parseVariableIdentifier() : null; var superClass = null; if (this.matchKeyword('extends')) { this.nextToken(); superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall); } var classBody = this.parseClassBody(); this.context.strict = previousStrict; return this.finalize(node, new Node.ClassExpression(id, superClass, classBody)); }; // https://tc39.github.io/ecma262/#sec-scripts // https://tc39.github.io/ecma262/#sec-modules Parser.prototype.parseModule = function () { this.context.strict = true; this.context.isModule = true; this.scanner.isModule = true; var node = this.createNode(); var body = this.parseDirectivePrologues(); while (this.lookahead.type !== 2 /* EOF */) { body.push(this.parseStatementListItem()); } return this.finalize(node, new Node.Module(body)); }; Parser.prototype.parseScript = function () { var node = this.createNode(); var body = this.parseDirectivePrologues(); while (this.lookahead.type !== 2 /* EOF */) { body.push(this.parseStatementListItem()); } return this.finalize(node, new Node.Script(body)); }; // https://tc39.github.io/ecma262/#sec-imports Parser.prototype.parseModuleSpecifier = function () { var node = this.createNode(); if (this.lookahead.type !== 8 /* StringLiteral */) { this.throwError(messages_1.Messages.InvalidModuleSpecifier); } var token = this.nextToken(); var raw = this.getTokenRaw(token); return this.finalize(node, new Node.Literal(token.value, raw)); }; // import {} ...; Parser.prototype.parseImportSpecifier = function () { var node = this.createNode(); var imported; var local; if (this.lookahead.type === 3 /* Identifier */) { imported = this.parseVariableIdentifier(); local = imported; if (this.matchContextualKeyword('as')) { this.nextToken(); local = this.parseVariableIdentifier(); } } else { imported = this.parseIdentifierName(); local = imported; if (this.matchContextualKeyword('as')) { this.nextToken(); local = this.parseVariableIdentifier(); } else { this.throwUnexpectedToken(this.nextToken()); } } return this.finalize(node, new Node.ImportSpecifier(local, imported)); }; // {foo, bar as bas} Parser.prototype.parseNamedImports = function () { this.expect('{'); var specifiers = []; while (!this.match('}')) { specifiers.push(this.parseImportSpecifier()); if (!this.match('}')) { this.expect(','); } } this.expect('}'); return specifiers; }; // import ...; Parser.prototype.parseImportDefaultSpecifier = function () { var node = this.createNode(); var local = this.parseIdentifierName(); return this.finalize(node, new Node.ImportDefaultSpecifier(local)); }; // import <* as foo> ...; Parser.prototype.parseImportNamespaceSpecifier = function () { var node = this.createNode(); this.expect('*'); if (!this.matchContextualKeyword('as')) { this.throwError(messages_1.Messages.NoAsAfterImportNamespace); } this.nextToken(); var local = this.parseIdentifierName(); return this.finalize(node, new Node.ImportNamespaceSpecifier(local)); }; Parser.prototype.parseImportDeclaration = function () { if (this.context.inFunctionBody) { this.throwError(messages_1.Messages.IllegalImportDeclaration); } var node = this.createNode(); this.expectKeyword('import'); var src; var specifiers = []; if (this.lookahead.type === 8 /* StringLiteral */) { // import 'foo'; src = this.parseModuleSpecifier(); } else { if (this.match('{')) { // import {bar} specifiers = specifiers.concat(this.parseNamedImports()); } else if (this.match('*')) { // import * as foo specifiers.push(this.parseImportNamespaceSpecifier()); } else if (this.isIdentifierName(this.lookahead) && !this.matchKeyword('default')) { // import foo specifiers.push(this.parseImportDefaultSpecifier()); if (this.match(',')) { this.nextToken(); if (this.match('*')) { // import foo, * as foo specifiers.push(this.parseImportNamespaceSpecifier()); } else if (this.match('{')) { // import foo, {bar} specifiers = specifiers.concat(this.parseNamedImports()); } else { this.throwUnexpectedToken(this.lookahead); } } } else { this.throwUnexpectedToken(this.nextToken()); } if (!this.matchContextualKeyword('from')) { var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; this.throwError(message, this.lookahead.value); } this.nextToken(); src = this.parseModuleSpecifier(); } this.consumeSemicolon(); return this.finalize(node, new Node.ImportDeclaration(specifiers, src)); }; // https://tc39.github.io/ecma262/#sec-exports Parser.prototype.parseExportSpecifier = function () { var node = this.createNode(); var local = this.parseIdentifierName(); var exported = local; if (this.matchContextualKeyword('as')) { this.nextToken(); exported = this.parseIdentifierName(); } return this.finalize(node, new Node.ExportSpecifier(local, exported)); }; Parser.prototype.parseExportDeclaration = function () { if (this.context.inFunctionBody) { this.throwError(messages_1.Messages.IllegalExportDeclaration); } var node = this.createNode(); this.expectKeyword('export'); var exportDeclaration; if (this.matchKeyword('default')) { // export default ... this.nextToken(); if (this.matchKeyword('function')) { // export default function foo () {} // export default function () {} var declaration = this.parseFunctionDeclaration(true); exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); } else if (this.matchKeyword('class')) { // export default class foo {} var declaration = this.parseClassDeclaration(true); exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); } else if (this.matchContextualKeyword('async')) { // export default async function f () {} // export default async function () {} // export default async x => x var declaration = this.matchAsyncFunction() ? this.parseFunctionDeclaration(true) : this.parseAssignmentExpression(); exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); } else { if (this.matchContextualKeyword('from')) { this.throwError(messages_1.Messages.UnexpectedToken, this.lookahead.value); } // export default {}; // export default []; // export default (1 + 2); var declaration = this.match('{') ? this.parseObjectInitializer() : this.match('[') ? this.parseArrayInitializer() : this.parseAssignmentExpression(); this.consumeSemicolon(); exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); } } else if (this.match('*')) { // export * from 'foo'; this.nextToken(); if (!this.matchContextualKeyword('from')) { var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; this.throwError(message, this.lookahead.value); } this.nextToken(); var src = this.parseModuleSpecifier(); this.consumeSemicolon(); exportDeclaration = this.finalize(node, new Node.ExportAllDeclaration(src)); } else if (this.lookahead.type === 4 /* Keyword */) { // export var f = 1; var declaration = void 0; switch (this.lookahead.value) { case 'let': case 'const': declaration = this.parseLexicalDeclaration({ inFor: false }); break; case 'var': case 'class': case 'function': declaration = this.parseStatementListItem(); break; default: this.throwUnexpectedToken(this.lookahead); } exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null)); } else if (this.matchAsyncFunction()) { var declaration = this.parseFunctionDeclaration(); exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null)); } else { var specifiers = []; var source = null; var isExportFromIdentifier = false; this.expect('{'); while (!this.match('}')) { isExportFromIdentifier = isExportFromIdentifier || this.matchKeyword('default'); specifiers.push(this.parseExportSpecifier()); if (!this.match('}')) { this.expect(','); } } this.expect('}'); if (this.matchContextualKeyword('from')) { // export {default} from 'foo'; // export {foo} from 'foo'; this.nextToken(); source = this.parseModuleSpecifier(); this.consumeSemicolon(); } else if (isExportFromIdentifier) { // export {default}; // missing fromClause var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; this.throwError(message, this.lookahead.value); } else { // export {foo}; this.consumeSemicolon(); } exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(null, specifiers, source)); } return exportDeclaration; }; return Parser; }()); exports.Parser = Parser; /***/ }, /* 9 */ /***/ function(module, exports) { "use strict"; // Ensure the condition is true, otherwise throw an error. // This is only to have a better contract semantic, i.e. another safety net // to catch a logic error. The condition shall be fulfilled in normal case. // Do NOT use this to enforce a certain condition on any user input. Object.defineProperty(exports, "__esModule", { value: true }); function assert(condition, message) { /* istanbul ignore if */ if (!condition) { throw new Error('ASSERT: ' + message); } } exports.assert = assert; /***/ }, /* 10 */ /***/ function(module, exports) { "use strict"; /* tslint:disable:max-classes-per-file */ Object.defineProperty(exports, "__esModule", { value: true }); var ErrorHandler = (function () { function ErrorHandler() { this.errors = []; this.tolerant = false; } ErrorHandler.prototype.recordError = function (error) { this.errors.push(error); }; ErrorHandler.prototype.tolerate = function (error) { if (this.tolerant) { this.recordError(error); } else { throw error; } }; ErrorHandler.prototype.constructError = function (msg, column) { var error = new Error(msg); try { throw error; } catch (base) { /* istanbul ignore else */ if (Object.create && Object.defineProperty) { error = Object.create(base); Object.defineProperty(error, 'column', { value: column }); } } /* istanbul ignore next */ return error; }; ErrorHandler.prototype.createError = function (index, line, col, description) { var msg = 'Line ' + line + ': ' + description; var error = this.constructError(msg, col); error.index = index; error.lineNumber = line; error.description = description; return error; }; ErrorHandler.prototype.throwError = function (index, line, col, description) { throw this.createError(index, line, col, description); }; ErrorHandler.prototype.tolerateError = function (index, line, col, description) { var error = this.createError(index, line, col, description); if (this.tolerant) { this.recordError(error); } else { throw error; } }; return ErrorHandler; }()); exports.ErrorHandler = ErrorHandler; /***/ }, /* 11 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // Error messages should be identical to V8. exports.Messages = { BadGetterArity: 'Getter must not have any formal parameters', BadSetterArity: 'Setter must have exactly one formal parameter', BadSetterRestParameter: 'Setter function argument must not be a rest parameter', ConstructorIsAsync: 'Class constructor may not be an async method', ConstructorSpecialMethod: 'Class constructor may not be an accessor', DeclarationMissingInitializer: 'Missing initializer in %0 declaration', DefaultRestParameter: 'Unexpected token =', DuplicateBinding: 'Duplicate binding %0', DuplicateConstructor: 'A class may only have one constructor', DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals', ForInOfLoopInitializer: '%0 loop variable declaration may not have an initializer', GeneratorInLegacyContext: 'Generator declarations are not allowed in legacy contexts', IllegalBreak: 'Illegal break statement', IllegalContinue: 'Illegal continue statement', IllegalExportDeclaration: 'Unexpected token', IllegalImportDeclaration: 'Unexpected token', IllegalLanguageModeDirective: 'Illegal \'use strict\' directive in function with non-simple parameter list', IllegalReturn: 'Illegal return statement', InvalidEscapedReservedWord: 'Keyword must not contain escaped characters', InvalidHexEscapeSequence: 'Invalid hexadecimal escape sequence', InvalidLHSInAssignment: 'Invalid left-hand side in assignment', InvalidLHSInForIn: 'Invalid left-hand side in for-in', InvalidLHSInForLoop: 'Invalid left-hand side in for-loop', InvalidModuleSpecifier: 'Unexpected token', InvalidRegExp: 'Invalid regular expression', LetInLexicalBinding: 'let is disallowed as a lexically bound name', MissingFromClause: 'Unexpected token', MultipleDefaultsInSwitch: 'More than one default clause in switch statement', NewlineAfterThrow: 'Illegal newline after throw', NoAsAfterImportNamespace: 'Unexpected token', NoCatchOrFinally: 'Missing catch or finally after try', ParameterAfterRestParameter: 'Rest parameter must be last formal parameter', Redeclaration: '%0 \'%1\' has already been declared', StaticPrototype: 'Classes may not have static property named prototype', StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', StrictDelete: 'Delete of an unqualified identifier in strict mode.', StrictFunction: 'In strict mode code, functions can only be declared at top level or inside a block', StrictFunctionName: 'Function name may not be eval or arguments in strict mode', StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', StrictModeWith: 'Strict mode code may not include a with statement', StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', StrictParamDupe: 'Strict mode function may not have duplicate parameter names', StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', StrictReservedWord: 'Use of future reserved word in strict mode', StrictVarName: 'Variable name may not be eval or arguments in strict mode', TemplateOctalLiteral: 'Octal literals are not allowed in template strings.', UnexpectedEOS: 'Unexpected end of input', UnexpectedIdentifier: 'Unexpected identifier', UnexpectedNumber: 'Unexpected number', UnexpectedReserved: 'Unexpected reserved word', UnexpectedString: 'Unexpected string', UnexpectedTemplate: 'Unexpected quasi %0', UnexpectedToken: 'Unexpected token %0', UnexpectedTokenIllegal: 'Unexpected token ILLEGAL', UnknownLabel: 'Undefined label \'%0\'', UnterminatedRegExp: 'Invalid regular expression: missing /' }; /***/ }, /* 12 */ /***/ function(module, exports, __nested_webpack_require_226595__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var assert_1 = __nested_webpack_require_226595__(9); var character_1 = __nested_webpack_require_226595__(4); var messages_1 = __nested_webpack_require_226595__(11); function hexValue(ch) { return '0123456789abcdef'.indexOf(ch.toLowerCase()); } function octalValue(ch) { return '01234567'.indexOf(ch); } var Scanner = (function () { function Scanner(code, handler) { this.source = code; this.errorHandler = handler; this.trackComment = false; this.isModule = false; this.length = code.length; this.index = 0; this.lineNumber = (code.length > 0) ? 1 : 0; this.lineStart = 0; this.curlyStack = []; } Scanner.prototype.saveState = function () { return { index: this.index, lineNumber: this.lineNumber, lineStart: this.lineStart }; }; Scanner.prototype.restoreState = function (state) { this.index = state.index; this.lineNumber = state.lineNumber; this.lineStart = state.lineStart; }; Scanner.prototype.eof = function () { return this.index >= this.length; }; Scanner.prototype.throwUnexpectedToken = function (message) { if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; } return this.errorHandler.throwError(this.index, this.lineNumber, this.index - this.lineStart + 1, message); }; Scanner.prototype.tolerateUnexpectedToken = function (message) { if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; } this.errorHandler.tolerateError(this.index, this.lineNumber, this.index - this.lineStart + 1, message); }; // https://tc39.github.io/ecma262/#sec-comments Scanner.prototype.skipSingleLineComment = function (offset) { var comments = []; var start, loc; if (this.trackComment) { comments = []; start = this.index - offset; loc = { start: { line: this.lineNumber, column: this.index - this.lineStart - offset }, end: {} }; } while (!this.eof()) { var ch = this.source.charCodeAt(this.index); ++this.index; if (character_1.Character.isLineTerminator(ch)) { if (this.trackComment) { loc.end = { line: this.lineNumber, column: this.index - this.lineStart - 1 }; var entry = { multiLine: false, slice: [start + offset, this.index - 1], range: [start, this.index - 1], loc: loc }; comments.push(entry); } if (ch === 13 && this.source.charCodeAt(this.index) === 10) { ++this.index; } ++this.lineNumber; this.lineStart = this.index; return comments; } } if (this.trackComment) { loc.end = { line: this.lineNumber, column: this.index - this.lineStart }; var entry = { multiLine: false, slice: [start + offset, this.index], range: [start, this.index], loc: loc }; comments.push(entry); } return comments; }; Scanner.prototype.skipMultiLineComment = function () { var comments = []; var start, loc; if (this.trackComment) { comments = []; start = this.index - 2; loc = { start: { line: this.lineNumber, column: this.index - this.lineStart - 2 }, end: {} }; } while (!this.eof()) { var ch = this.source.charCodeAt(this.index); if (character_1.Character.isLineTerminator(ch)) { if (ch === 0x0D && this.source.charCodeAt(this.index + 1) === 0x0A) { ++this.index; } ++this.lineNumber; ++this.index; this.lineStart = this.index; } else if (ch === 0x2A) { // Block comment ends with '*/'. if (this.source.charCodeAt(this.index + 1) === 0x2F) { this.index += 2; if (this.trackComment) { loc.end = { line: this.lineNumber, column: this.index - this.lineStart }; var entry = { multiLine: true, slice: [start + 2, this.index - 2], range: [start, this.index], loc: loc }; comments.push(entry); } return comments; } ++this.index; } else { ++this.index; } } // Ran off the end of the file - the whole thing is a comment if (this.trackComment) { loc.end = { line: this.lineNumber, column: this.index - this.lineStart }; var entry = { multiLine: true, slice: [start + 2, this.index], range: [start, this.index], loc: loc }; comments.push(entry); } this.tolerateUnexpectedToken(); return comments; }; Scanner.prototype.scanComments = function () { var comments; if (this.trackComment) { comments = []; } var start = (this.index === 0); while (!this.eof()) { var ch = this.source.charCodeAt(this.index); if (character_1.Character.isWhiteSpace(ch)) { ++this.index; } else if (character_1.Character.isLineTerminator(ch)) { ++this.index; if (ch === 0x0D && this.source.charCodeAt(this.index) === 0x0A) { ++this.index; } ++this.lineNumber; this.lineStart = this.index; start = true; } else if (ch === 0x2F) { ch = this.source.charCodeAt(this.index + 1); if (ch === 0x2F) { this.index += 2; var comment = this.skipSingleLineComment(2); if (this.trackComment) { comments = comments.concat(comment); } start = true; } else if (ch === 0x2A) { this.index += 2; var comment = this.skipMultiLineComment(); if (this.trackComment) { comments = comments.concat(comment); } } else { break; } } else if (start && ch === 0x2D) { // U+003E is '>' if ((this.source.charCodeAt(this.index + 1) === 0x2D) && (this.source.charCodeAt(this.index + 2) === 0x3E)) { // '-->' is a single-line comment this.index += 3; var comment = this.skipSingleLineComment(3); if (this.trackComment) { comments = comments.concat(comment); } } else { break; } } else if (ch === 0x3C && !this.isModule) { if (this.source.slice(this.index + 1, this.index + 4) === '!--') { this.index += 4; // ` * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 // ~0.0.1 --> >=0.0.1 <0.1.0-0 const replaceTildes = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceTilde(c, options)) .join(' ') } const replaceTilde = (comp, options) => { const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] return comp.replace(r, (_, M, m, p, pr) => { debug('tilde', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0 <${+M + 1}.0.0-0` } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0-0 ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` } else if (pr) { debug('replaceTilde pr', pr) ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } else { // ~1.2.3 == >=1.2.3 <1.3.0-0 ret = `>=${M}.${m}.${p } <${M}.${+m + 1}.0-0` } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 // ^1.2.3 --> >=1.2.3 <2.0.0-0 // ^1.2.0 --> >=1.2.0 <2.0.0-0 // ^0.0.1 --> >=0.0.1 <0.0.2-0 // ^0.1.0 --> >=0.1.0 <0.2.0-0 const replaceCarets = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceCaret(c, options)) .join(' ') } const replaceCaret = (comp, options) => { debug('caret', comp, options) const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] const z = options.includePrerelease ? '-0' : '' return comp.replace(r, (_, M, m, p, pr) => { debug('caret', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` } else if (isX(p)) { if (M === '0') { ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` } else { ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p}-${pr } <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p}-${pr } <${+M + 1}.0.0-0` } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p }${z} <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p }${z} <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p } <${+M + 1}.0.0-0` } } debug('caret return', ret) return ret }) } const replaceXRanges = (comp, options) => { debug('replaceXRanges', comp, options) return comp .split(/\s+/) .map((c) => replaceXRange(c, options)) .join(' ') } const replaceXRange = (comp, options) => { comp = comp.trim() const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] return comp.replace(r, (ret, gtlt, M, m, p, pr) => { debug('xRange', comp, ret, gtlt, M, m, p, pr) const xM = isX(M) const xm = xM || isX(m) const xp = xm || isX(p) const anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } // if we're including prereleases in the match, then we need // to fix this to -0, the lowest possible prerelease value pr = options.includePrerelease ? '-0' : '' if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0-0' } else { // nothing is forbidden ret = '*' } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0 } p = 0 if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 gtlt = '>=' if (xm) { M = +M + 1 m = 0 p = 0 } else { m = +m + 1 p = 0 } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<' if (xm) { M = +M + 1 } else { m = +m + 1 } } if (gtlt === '<') { pr = '-0' } ret = `${gtlt + M}.${m}.${p}${pr}` } else if (xm) { ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` } else if (xp) { ret = `>=${M}.${m}.0${pr } <${M}.${+m + 1}.0-0` } debug('xRange return', ret) return ret }) } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. const replaceStars = (comp, options) => { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp .trim() .replace(re[t.STAR], '') } const replaceGTE0 = (comp, options) => { debug('replaceGTE0', comp, options) return comp .trim() .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') } // This function is passed to string.replace(re[t.HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 const hyphenReplace = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) => { if (isX(fM)) { from = '' } else if (isX(fm)) { from = `>=${fM}.0.0${incPr ? '-0' : ''}` } else if (isX(fp)) { from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` } else if (fpr) { from = `>=${from}` } else { from = `>=${from}${incPr ? '-0' : ''}` } if (isX(tM)) { to = '' } else if (isX(tm)) { to = `<${+tM + 1}.0.0-0` } else if (isX(tp)) { to = `<${tM}.${+tm + 1}.0-0` } else if (tpr) { to = `<=${tM}.${tm}.${tp}-${tpr}` } else if (incPr) { to = `<${tM}.${tm}.${+tp + 1}-0` } else { to = `<=${to}` } return `${from} ${to}`.trim() } const testSet = (set, version, options) => { for (let i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (let i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === Comparator.ANY) { continue } if (set[i].semver.prerelease.length > 0) { const allowed = set[i].semver if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } /***/ }), /***/ 37946: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const debug = __webpack_require__(35858) const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(89998) const { safeRe: re, t } = __webpack_require__(16618) const parseOptions = __webpack_require__(74919) const { compareIdentifiers } = __webpack_require__(26123) class SemVer { constructor (version, options) { options = parseOptions(options) if (version instanceof SemVer) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) } if (version.length > MAX_LENGTH) { throw new TypeError( `version is longer than ${MAX_LENGTH} characters` ) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose // this isn't actually relevant for versions, but keep it so that we // don't run into trouble passing this.options around. this.includePrerelease = !!options.includePrerelease const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) if (!m) { throw new TypeError(`Invalid Version: ${version}`) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map((id) => { if (/^[0-9]+$/.test(id)) { const num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } format () { this.version = `${this.major}.${this.minor}.${this.patch}` if (this.prerelease.length) { this.version += `-${this.prerelease.join('.')}` } return this.version } toString () { return this.version } compare (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { if (typeof other === 'string' && other === this.version) { return 0 } other = new SemVer(other, this.options) } if (other.version === this.version) { return 0 } return this.compareMain(other) || this.comparePre(other) } compareMain (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return ( compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) ) } comparePre (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } let i = 0 do { const a = this.prerelease[i] const b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } compareBuild (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } let i = 0 do { const a = this.build[i] const b = other.build[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc (release, identifier, identifierBase) { switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier, identifierBase) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier, identifierBase) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier, identifierBase) this.inc('pre', identifier, identifierBase) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier, identifierBase) } this.inc('pre', identifier, identifierBase) break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if ( this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0 ) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. case 'pre': { const base = Number(identifierBase) ? 1 : 0 if (!identifier && identifierBase === false) { throw new Error('invalid increment argument: identifier is empty') } if (this.prerelease.length === 0) { this.prerelease = [base] } else { let i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything if (identifier === this.prerelease.join('.') && identifierBase === false) { throw new Error('invalid increment argument: identifier already exists') } this.prerelease.push(base) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 let prerelease = [identifier, base] if (identifierBase === false) { prerelease = [identifier] } if (compareIdentifiers(this.prerelease[0], identifier) === 0) { if (isNaN(this.prerelease[1])) { this.prerelease = prerelease } } else { this.prerelease = prerelease } } break } default: throw new Error(`invalid increment argument: ${release}`) } this.raw = this.format() if (this.build.length) { this.raw += `+${this.build.join('.')}` } return this } } module.exports = SemVer /***/ }), /***/ 4078: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(50038) const clean = (version, options) => { const s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } module.exports = clean /***/ }), /***/ 7910: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const eq = __webpack_require__(24598) const neq = __webpack_require__(54618) const gt = __webpack_require__(27912) const gte = __webpack_require__(27022) const lt = __webpack_require__(73394) const lte = __webpack_require__(63591) const cmp = (a, op, b, loose) => { switch (op) { case '===': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a === b case '!==': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError(`Invalid operator: ${op}`) } } module.exports = cmp /***/ }), /***/ 63599: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(37946) const parse = __webpack_require__(50038) const { safeRe: re, t } = __webpack_require__(16618) const coerce = (version, options) => { if (version instanceof SemVer) { return version } if (typeof version === 'number') { version = String(version) } if (typeof version !== 'string') { return null } options = options || {} let match = null if (!options.rtl) { match = version.match(re[t.COERCE]) } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' // // Walk through the string checking with a /g regexp // Manually set the index so as to pick up overlapping matches. // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. let next while ((next = re[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next } re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length } // leave it in a clean state re[t.COERCERTL].lastIndex = -1 } if (match === null) { return null } return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) } module.exports = coerce /***/ }), /***/ 79615: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(37946) const compareBuild = (a, b, loose) => { const versionA = new SemVer(a, loose) const versionB = new SemVer(b, loose) return versionA.compare(versionB) || versionA.compareBuild(versionB) } module.exports = compareBuild /***/ }), /***/ 21282: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(83381) const compareLoose = (a, b) => compare(a, b, true) module.exports = compareLoose /***/ }), /***/ 83381: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(37946) const compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)) module.exports = compare /***/ }), /***/ 23934: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(50038) const diff = (version1, version2) => { const v1 = parse(version1, null, true) const v2 = parse(version2, null, true) const comparison = v1.compare(v2) if (comparison === 0) { return null } const v1Higher = comparison > 0 const highVersion = v1Higher ? v1 : v2 const lowVersion = v1Higher ? v2 : v1 const highHasPre = !!highVersion.prerelease.length const lowHasPre = !!lowVersion.prerelease.length if (lowHasPre && !highHasPre) { // Going from prerelease -> no prerelease requires some special casing // If the low version has only a major, then it will always be a major // Some examples: // 1.0.0-1 -> 1.0.0 // 1.0.0-1 -> 1.1.1 // 1.0.0-1 -> 2.0.0 if (!lowVersion.patch && !lowVersion.minor) { return 'major' } // Otherwise it can be determined by checking the high version if (highVersion.patch) { // anything higher than a patch bump would result in the wrong version return 'patch' } if (highVersion.minor) { // anything higher than a minor bump would result in the wrong version return 'minor' } // bumping major/minor/patch all have same result return 'major' } // add the `pre` prefix if we are going to a prerelease version const prefix = highHasPre ? 'pre' : '' if (v1.major !== v2.major) { return prefix + 'major' } if (v1.minor !== v2.minor) { return prefix + 'minor' } if (v1.patch !== v2.patch) { return prefix + 'patch' } // high and low are preleases return 'prerelease' } module.exports = diff /***/ }), /***/ 24598: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(83381) const eq = (a, b, loose) => compare(a, b, loose) === 0 module.exports = eq /***/ }), /***/ 27912: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(83381) const gt = (a, b, loose) => compare(a, b, loose) > 0 module.exports = gt /***/ }), /***/ 27022: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(83381) const gte = (a, b, loose) => compare(a, b, loose) >= 0 module.exports = gte /***/ }), /***/ 93427: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(37946) const inc = (version, release, options, identifier, identifierBase) => { if (typeof (options) === 'string') { identifierBase = identifier identifier = options options = undefined } try { return new SemVer( version instanceof SemVer ? version.version : version, options ).inc(release, identifier, identifierBase).version } catch (er) { return null } } module.exports = inc /***/ }), /***/ 73394: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(83381) const lt = (a, b, loose) => compare(a, b, loose) < 0 module.exports = lt /***/ }), /***/ 63591: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(83381) const lte = (a, b, loose) => compare(a, b, loose) <= 0 module.exports = lte /***/ }), /***/ 25136: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(37946) const major = (a, loose) => new SemVer(a, loose).major module.exports = major /***/ }), /***/ 66770: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(37946) const minor = (a, loose) => new SemVer(a, loose).minor module.exports = minor /***/ }), /***/ 54618: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(83381) const neq = (a, b, loose) => compare(a, b, loose) !== 0 module.exports = neq /***/ }), /***/ 50038: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(37946) const parse = (version, options, throwErrors = false) => { if (version instanceof SemVer) { return version } try { return new SemVer(version, options) } catch (er) { if (!throwErrors) { return null } throw er } } module.exports = parse /***/ }), /***/ 13569: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(37946) const patch = (a, loose) => new SemVer(a, loose).patch module.exports = patch /***/ }), /***/ 83963: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(50038) const prerelease = (version, options) => { const parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } module.exports = prerelease /***/ }), /***/ 87077: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(83381) const rcompare = (a, b, loose) => compare(b, a, loose) module.exports = rcompare /***/ }), /***/ 94246: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(79615) const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) module.exports = rsort /***/ }), /***/ 56736: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(97839) const satisfies = (version, range, options) => { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } module.exports = satisfies /***/ }), /***/ 81463: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(79615) const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) module.exports = sort /***/ }), /***/ 17643: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(50038) const valid = (version, options) => { const v = parse(version, options) return v ? v.version : null } module.exports = valid /***/ }), /***/ 11310: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // just pre-load all the stuff that index.js lazily exports const internalRe = __webpack_require__(16618) const constants = __webpack_require__(89998) const SemVer = __webpack_require__(37946) const identifiers = __webpack_require__(26123) const parse = __webpack_require__(50038) const valid = __webpack_require__(17643) const clean = __webpack_require__(4078) const inc = __webpack_require__(93427) const diff = __webpack_require__(23934) const major = __webpack_require__(25136) const minor = __webpack_require__(66770) const patch = __webpack_require__(13569) const prerelease = __webpack_require__(83963) const compare = __webpack_require__(83381) const rcompare = __webpack_require__(87077) const compareLoose = __webpack_require__(21282) const compareBuild = __webpack_require__(79615) const sort = __webpack_require__(81463) const rsort = __webpack_require__(94246) const gt = __webpack_require__(27912) const lt = __webpack_require__(73394) const eq = __webpack_require__(24598) const neq = __webpack_require__(54618) const gte = __webpack_require__(27022) const lte = __webpack_require__(63591) const cmp = __webpack_require__(7910) const coerce = __webpack_require__(63599) const Comparator = __webpack_require__(158) const Range = __webpack_require__(97839) const satisfies = __webpack_require__(56736) const toComparators = __webpack_require__(98062) const maxSatisfying = __webpack_require__(91267) const minSatisfying = __webpack_require__(52014) const minVersion = __webpack_require__(6449) const validRange = __webpack_require__(23217) const outside = __webpack_require__(91710) const gtr = __webpack_require__(77383) const ltr = __webpack_require__(11872) const intersects = __webpack_require__(24803) const simplifyRange = __webpack_require__(30862) const subset = __webpack_require__(31299) module.exports = { parse, valid, clean, inc, diff, major, minor, patch, prerelease, compare, rcompare, compareLoose, compareBuild, sort, rsort, gt, lt, eq, neq, gte, lte, cmp, coerce, Comparator, Range, satisfies, toComparators, maxSatisfying, minSatisfying, minVersion, validRange, outside, gtr, ltr, intersects, simplifyRange, subset, SemVer, re: internalRe.re, src: internalRe.src, tokens: internalRe.t, SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, RELEASE_TYPES: constants.RELEASE_TYPES, compareIdentifiers: identifiers.compareIdentifiers, rcompareIdentifiers: identifiers.rcompareIdentifiers, } /***/ }), /***/ 89998: /***/ ((module) => { // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. const SEMVER_SPEC_VERSION = '2.0.0' const MAX_LENGTH = 256 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. const MAX_SAFE_COMPONENT_LENGTH = 16 // Max safe length for a build identifier. The max length minus 6 characters for // the shortest version with a build 0.0.0+BUILD. const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 const RELEASE_TYPES = [ 'major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease', ] module.exports = { MAX_LENGTH, MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_SAFE_INTEGER, RELEASE_TYPES, SEMVER_SPEC_VERSION, FLAG_INCLUDE_PRERELEASE: 0b001, FLAG_LOOSE: 0b010, } /***/ }), /***/ 35858: /***/ ((module) => { const debug = ( typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ) ? (...args) => console.error('SEMVER', ...args) : () => {} module.exports = debug /***/ }), /***/ 26123: /***/ ((module) => { const numeric = /^[0-9]+$/ const compareIdentifiers = (a, b) => { const anum = numeric.test(a) const bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) module.exports = { compareIdentifiers, rcompareIdentifiers, } /***/ }), /***/ 74919: /***/ ((module) => { // parse out just the options we care about const looseOption = Object.freeze({ loose: true }) const emptyOpts = Object.freeze({ }) const parseOptions = options => { if (!options) { return emptyOpts } if (typeof options !== 'object') { return looseOption } return options } module.exports = parseOptions /***/ }), /***/ 16618: /***/ ((module, exports, __webpack_require__) => { const { MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_LENGTH, } = __webpack_require__(89998) const debug = __webpack_require__(35858) exports = module.exports = {} // The actual regexps go on exports.re const re = exports.re = [] const safeRe = exports.safeRe = [] const src = exports.src = [] const t = exports.t = {} let R = 0 const LETTERDASHNUMBER = '[a-zA-Z0-9-]' // Replace some greedy regex tokens to prevent regex dos issues. These regex are // used internally via the safeRe object since all inputs in this library get // normalized first to trim and collapse all extra whitespace. The original // regexes are exported for userland consumption and lower level usage. A // future breaking change could export the safer regex only with a note that // all input should have extra whitespace removed. const safeRegexReplacements = [ ['\\s', 1], ['\\d', MAX_LENGTH], [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], ] const makeSafeRegex = (value) => { for (const [token, max] of safeRegexReplacements) { value = value .split(`${token}*`).join(`${token}{0,${max}}`) .split(`${token}+`).join(`${token}{1,${max}}`) } return value } const createToken = (name, value, isGlobal) => { const safe = makeSafeRegex(value) const index = R++ debug(name, index, value) t[name] = index src[index] = value re[index] = new RegExp(value, isGlobal ? 'g' : undefined) safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) } // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') createToken('NUMERICIDENTIFIERLOOSE', '\\d+') // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) // ## Main Version // Three dot-separated numeric identifiers. createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`) createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] }|${src[t.NONNUMERICIDENTIFIER]})`) createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] }|${src[t.NONNUMERICIDENTIFIER]})`) // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] }(?:\\.${src[t.BUILDIDENTIFIER]})*))`) // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. createToken('FULLPLAIN', `v?${src[t.MAINVERSION] }${src[t.PRERELEASE]}?${ src[t.BUILD]}?`) createToken('FULL', `^${src[t.FULLPLAIN]}$`) // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] }${src[t.PRERELEASELOOSE]}?${ src[t.BUILD]}?`) createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) createToken('GTLT', '((?:<|>)?=?)') // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) // Coercion. // Extract anything that could conceivably be a part of a valid semver createToken('COERCE', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:$|[^\\d])`) createToken('COERCERTL', src[t.COERCE], true) // Tilde ranges. // Meaning is "reasonably at or greater than" createToken('LONETILDE', '(?:~>?)') createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) exports.tildeTrimReplace = '$1~' createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) // Caret ranges. // Meaning is "at least and backwards compatible with" createToken('LONECARET', '(?:\\^)') createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) exports.caretTrimReplace = '$1^' createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) // A simple gt/lt/eq thing, or just "" to indicate "any version" createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) exports.comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`) createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`) // Star ranges basically just allow anything at all. createToken('STAR', '(<|>)?=?\\s*\\*') // >=0.0.0 is like a star createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') /***/ }), /***/ 77383: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Determine if version is greater than all the versions possible in the range. const outside = __webpack_require__(91710) const gtr = (version, range, options) => outside(version, range, '>', options) module.exports = gtr /***/ }), /***/ 24803: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(97839) const intersects = (r1, r2, options) => { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2, options) } module.exports = intersects /***/ }), /***/ 11872: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const outside = __webpack_require__(91710) // Determine if version is less than all the versions possible in the range const ltr = (version, range, options) => outside(version, range, '<', options) module.exports = ltr /***/ }), /***/ 91267: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(37946) const Range = __webpack_require__(97839) const maxSatisfying = (versions, range, options) => { let max = null let maxSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } module.exports = maxSatisfying /***/ }), /***/ 52014: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(37946) const Range = __webpack_require__(97839) const minSatisfying = (versions, range, options) => { let min = null let minSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } module.exports = minSatisfying /***/ }), /***/ 6449: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(37946) const Range = __webpack_require__(97839) const gt = __webpack_require__(27912) const minVersion = (range, loose) => { range = new Range(range, loose) let minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let setMin = null comparators.forEach((comparator) => { // Clone to avoid manipulating the comparator's semver object. const compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!setMin || gt(compver, setMin)) { setMin = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error(`Unexpected operation: ${comparator.operator}`) } }) if (setMin && (!minver || gt(minver, setMin))) { minver = setMin } } if (minver && range.test(minver)) { return minver } return null } module.exports = minVersion /***/ }), /***/ 91710: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(37946) const Comparator = __webpack_require__(158) const { ANY } = Comparator const Range = __webpack_require__(97839) const satisfies = __webpack_require__(56736) const gt = __webpack_require__(27912) const lt = __webpack_require__(73394) const lte = __webpack_require__(63591) const gte = __webpack_require__(27022) const outside = (version, range, hilo, options) => { version = new SemVer(version, options) range = new Range(range, options) let gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisfies the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let high = null let low = null comparators.forEach((comparator) => { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } module.exports = outside /***/ }), /***/ 30862: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // given a set of versions and a range, create a "simplified" range // that includes the same versions that the original range does // If the original range is shorter than the simplified one, return that. const satisfies = __webpack_require__(56736) const compare = __webpack_require__(83381) module.exports = (versions, range, options) => { const set = [] let first = null let prev = null const v = versions.sort((a, b) => compare(a, b, options)) for (const version of v) { const included = satisfies(version, range, options) if (included) { prev = version if (!first) { first = version } } else { if (prev) { set.push([first, prev]) } prev = null first = null } } if (first) { set.push([first, null]) } const ranges = [] for (const [min, max] of set) { if (min === max) { ranges.push(min) } else if (!max && min === v[0]) { ranges.push('*') } else if (!max) { ranges.push(`>=${min}`) } else if (min === v[0]) { ranges.push(`<=${max}`) } else { ranges.push(`${min} - ${max}`) } } const simplified = ranges.join(' || ') const original = typeof range.raw === 'string' ? range.raw : String(range) return simplified.length < original.length ? simplified : range } /***/ }), /***/ 31299: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(97839) const Comparator = __webpack_require__(158) const { ANY } = Comparator const satisfies = __webpack_require__(56736) const compare = __webpack_require__(83381) // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: // - Every simple range `r1, r2, ...` is a null set, OR // - Every simple range `r1, r2, ...` which is not a null set is a subset of // some `R1, R2, ...` // // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: // - If c is only the ANY comparator // - If C is only the ANY comparator, return true // - Else if in prerelease mode, return false // - else replace c with `[>=0.0.0]` // - If C is only the ANY comparator // - if in prerelease mode, return true // - else replace C with `[>=0.0.0]` // - Let EQ be the set of = comparators in c // - If EQ is more than one, return true (null set) // - Let GT be the highest > or >= comparator in c // - Let LT be the lowest < or <= comparator in c // - If GT and LT, and GT.semver > LT.semver, return true (null set) // - If any C is a = range, and GT or LT are set, return false // - If EQ // - If GT, and EQ does not satisfy GT, return true (null set) // - If LT, and EQ does not satisfy LT, return true (null set) // - If EQ satisfies every C, return true // - Else return false // - If GT // - If GT.semver is lower than any > or >= comp in C, return false // - If GT is >=, and GT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the GT.semver tuple, return false // - If LT // - If LT.semver is greater than any < or <= comp in C, return false // - If LT is <=, and LT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the LT.semver tuple, return false // - Else return true const subset = (sub, dom, options = {}) => { if (sub === dom) { return true } sub = new Range(sub, options) dom = new Range(dom, options) let sawNonNull = false OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { const isSub = simpleSubset(simpleSub, simpleDom, options) sawNonNull = sawNonNull || isSub !== null if (isSub) { continue OUTER } } // the null set is a subset of everything, but null simple ranges in // a complex range should be ignored. so if we saw a non-null range, // then we know this isn't a subset, but if EVERY simple range was null, // then it is a subset. if (sawNonNull) { return false } } return true } const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] const minimumVersion = [new Comparator('>=0.0.0')] const simpleSubset = (sub, dom, options) => { if (sub === dom) { return true } if (sub.length === 1 && sub[0].semver === ANY) { if (dom.length === 1 && dom[0].semver === ANY) { return true } else if (options.includePrerelease) { sub = minimumVersionWithPreRelease } else { sub = minimumVersion } } if (dom.length === 1 && dom[0].semver === ANY) { if (options.includePrerelease) { return true } else { dom = minimumVersion } } const eqSet = new Set() let gt, lt for (const c of sub) { if (c.operator === '>' || c.operator === '>=') { gt = higherGT(gt, c, options) } else if (c.operator === '<' || c.operator === '<=') { lt = lowerLT(lt, c, options) } else { eqSet.add(c.semver) } } if (eqSet.size > 1) { return null } let gtltComp if (gt && lt) { gtltComp = compare(gt.semver, lt.semver, options) if (gtltComp > 0) { return null } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { return null } } // will iterate one or zero times for (const eq of eqSet) { if (gt && !satisfies(eq, String(gt), options)) { return null } if (lt && !satisfies(eq, String(lt), options)) { return null } for (const c of dom) { if (!satisfies(eq, String(c), options)) { return false } } return true } let higher, lower let hasDomLT, hasDomGT // if the subset has a prerelease, we need a comparator in the superset // with the same tuple and a prerelease, or it's not a subset let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false // exception: <1.2.3-0 is the same as <1.2.3 if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { needDomLTPre = false } for (const c of dom) { hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' if (gt) { if (needDomGTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { needDomGTPre = false } } if (c.operator === '>' || c.operator === '>=') { higher = higherGT(gt, c, options) if (higher === c && higher !== gt) { return false } } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { return false } } if (lt) { if (needDomLTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { needDomLTPre = false } } if (c.operator === '<' || c.operator === '<=') { lower = lowerLT(lt, c, options) if (lower === c && lower !== lt) { return false } } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { return false } } if (!c.operator && (lt || gt) && gtltComp !== 0) { return false } } // if there was a < or >, and nothing in the dom, then must be false // UNLESS it was limited by another range in the other direction. // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 if (gt && hasDomLT && !lt && gtltComp !== 0) { return false } if (lt && hasDomGT && !gt && gtltComp !== 0) { return false } // we needed a prerelease range in a specific tuple, but didn't get one // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, // because it includes prereleases in the 1.2.3 tuple if (needDomGTPre || needDomLTPre) { return false } return true } // >=1.2.3 is lower than >1.2.3 const higherGT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp > 0 ? a : comp < 0 ? b : b.operator === '>' && a.operator === '>=' ? b : a } // <=1.2.3 is higher than <1.2.3 const lowerLT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp < 0 ? a : comp > 0 ? b : b.operator === '<' && a.operator === '<=' ? b : a } module.exports = subset /***/ }), /***/ 98062: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(97839) // Mostly just for testing and legacy API reasons const toComparators = (range, options) => new Range(range, options).set .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) module.exports = toComparators /***/ }), /***/ 23217: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(97839) const validRange = (range, options) => { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } module.exports = validRange /***/ }), /***/ 93060: /***/ ((module) => { "use strict"; module.exports = function (Yallist) { Yallist.prototype[Symbol.iterator] = function* () { for (let walker = this.head; walker; walker = walker.next) { yield walker.value } } } /***/ }), /***/ 47001: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = Yallist Yallist.Node = Node Yallist.create = Yallist function Yallist (list) { var self = this if (!(self instanceof Yallist)) { self = new Yallist() } self.tail = null self.head = null self.length = 0 if (list && typeof list.forEach === 'function') { list.forEach(function (item) { self.push(item) }) } else if (arguments.length > 0) { for (var i = 0, l = arguments.length; i < l; i++) { self.push(arguments[i]) } } return self } Yallist.prototype.removeNode = function (node) { if (node.list !== this) { throw new Error('removing node which does not belong to this list') } var next = node.next var prev = node.prev if (next) { next.prev = prev } if (prev) { prev.next = next } if (node === this.head) { this.head = next } if (node === this.tail) { this.tail = prev } node.list.length-- node.next = null node.prev = null node.list = null return next } Yallist.prototype.unshiftNode = function (node) { if (node === this.head) { return } if (node.list) { node.list.removeNode(node) } var head = this.head node.list = this node.next = head if (head) { head.prev = node } this.head = node if (!this.tail) { this.tail = node } this.length++ } Yallist.prototype.pushNode = function (node) { if (node === this.tail) { return } if (node.list) { node.list.removeNode(node) } var tail = this.tail node.list = this node.prev = tail if (tail) { tail.next = node } this.tail = node if (!this.head) { this.head = node } this.length++ } Yallist.prototype.push = function () { for (var i = 0, l = arguments.length; i < l; i++) { push(this, arguments[i]) } return this.length } Yallist.prototype.unshift = function () { for (var i = 0, l = arguments.length; i < l; i++) { unshift(this, arguments[i]) } return this.length } Yallist.prototype.pop = function () { if (!this.tail) { return undefined } var res = this.tail.value this.tail = this.tail.prev if (this.tail) { this.tail.next = null } else { this.head = null } this.length-- return res } Yallist.prototype.shift = function () { if (!this.head) { return undefined } var res = this.head.value this.head = this.head.next if (this.head) { this.head.prev = null } else { this.tail = null } this.length-- return res } Yallist.prototype.forEach = function (fn, thisp) { thisp = thisp || this for (var walker = this.head, i = 0; walker !== null; i++) { fn.call(thisp, walker.value, i, this) walker = walker.next } } Yallist.prototype.forEachReverse = function (fn, thisp) { thisp = thisp || this for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { fn.call(thisp, walker.value, i, this) walker = walker.prev } } Yallist.prototype.get = function (n) { for (var i = 0, walker = this.head; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.next } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.getReverse = function (n) { for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.prev } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.map = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.head; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.next } return res } Yallist.prototype.mapReverse = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.tail; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.prev } return res } Yallist.prototype.reduce = function (fn, initial) { var acc var walker = this.head if (arguments.length > 1) { acc = initial } else if (this.head) { walker = this.head.next acc = this.head.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = 0; walker !== null; i++) { acc = fn(acc, walker.value, i) walker = walker.next } return acc } Yallist.prototype.reduceReverse = function (fn, initial) { var acc var walker = this.tail if (arguments.length > 1) { acc = initial } else if (this.tail) { walker = this.tail.prev acc = this.tail.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = this.length - 1; walker !== null; i--) { acc = fn(acc, walker.value, i) walker = walker.prev } return acc } Yallist.prototype.toArray = function () { var arr = new Array(this.length) for (var i = 0, walker = this.head; walker !== null; i++) { arr[i] = walker.value walker = walker.next } return arr } Yallist.prototype.toArrayReverse = function () { var arr = new Array(this.length) for (var i = 0, walker = this.tail; walker !== null; i++) { arr[i] = walker.value walker = walker.prev } return arr } Yallist.prototype.slice = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = 0, walker = this.head; walker !== null && i < from; i++) { walker = walker.next } for (; walker !== null && i < to; i++, walker = walker.next) { ret.push(walker.value) } return ret } Yallist.prototype.sliceReverse = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { walker = walker.prev } for (; walker !== null && i > from; i--, walker = walker.prev) { ret.push(walker.value) } return ret } Yallist.prototype.splice = function (start, deleteCount, ...nodes) { if (start > this.length) { start = this.length - 1 } if (start < 0) { start = this.length + start; } for (var i = 0, walker = this.head; walker !== null && i < start; i++) { walker = walker.next } var ret = [] for (var i = 0; walker && i < deleteCount; i++) { ret.push(walker.value) walker = this.removeNode(walker) } if (walker === null) { walker = this.tail } if (walker !== this.head && walker !== this.tail) { walker = walker.prev } for (var i = 0; i < nodes.length; i++) { walker = insert(this, walker, nodes[i]) } return ret; } Yallist.prototype.reverse = function () { var head = this.head var tail = this.tail for (var walker = head; walker !== null; walker = walker.prev) { var p = walker.prev walker.prev = walker.next walker.next = p } this.head = tail this.tail = head return this } function insert (self, node, value) { var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self) if (inserted.next === null) { self.tail = inserted } if (inserted.prev === null) { self.head = inserted } self.length++ return inserted } function push (self, item) { self.tail = new Node(item, self.tail, null, self) if (!self.head) { self.head = self.tail } self.length++ } function unshift (self, item) { self.head = new Node(item, null, self.head, self) if (!self.tail) { self.tail = self.head } self.length++ } function Node (value, prev, next, list) { if (!(this instanceof Node)) { return new Node(value, prev, next, list) } this.list = list this.value = value if (prev) { prev.next = this this.prev = prev } else { this.prev = null } if (next) { next.prev = this this.next = next } else { this.next = null } } try { // add if support for Symbol.iterator is present __webpack_require__(93060)(Yallist) } catch (er) {} /***/ }), /***/ 19551: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.pipFilesToScannedProjects = exports.poetryFilesToScannedProjects = exports.phpFilesToScannedProjects = exports.nodeFilesToScannedProjects = void 0; const node_1 = __webpack_require__(88819); Object.defineProperty(exports, "nodeFilesToScannedProjects", ({ enumerable: true, get: function () { return node_1.nodeFilesToScannedProjects; } })); const php_1 = __webpack_require__(36609); Object.defineProperty(exports, "phpFilesToScannedProjects", ({ enumerable: true, get: function () { return php_1.phpFilesToScannedProjects; } })); const python_1 = __webpack_require__(76491); Object.defineProperty(exports, "pipFilesToScannedProjects", ({ enumerable: true, get: function () { return python_1.pipFilesToScannedProjects; } })); Object.defineProperty(exports, "poetryFilesToScannedProjects", ({ enumerable: true, get: function () { return python_1.poetryFilesToScannedProjects; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 3823: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parsePomProperties = exports.getCoordsFromPomProperties = exports.jarFilesToScannedResults = void 0; const admzip = __webpack_require__(55285); const path = __webpack_require__(71017); const buffer_utils_1 = __webpack_require__(29098); /** * @param {{[fileName: string]: Buffer}} fileNameToBuffer fileName * @returns {AggregatedJars} */ function groupJarFingerprintsByPath(fileNameToBuffer) { const resultAggregatedByPath = {}; Object.keys(fileNameToBuffer).forEach((filePath) => { const location = path.dirname(filePath); const jarFingerprint = { location: filePath, buffer: fileNameToBuffer[filePath], coords: null, dependencies: [], nestedJars: [], }; resultAggregatedByPath[location] = resultAggregatedByPath[location] || []; resultAggregatedByPath[location].push(jarFingerprint); }); return resultAggregatedByPath; } async function jarFilesToScannedResults(filePathToContent, targetImage, desiredLevelsOfUnpacking) { const mappedResult = groupJarFingerprintsByPath(filePathToContent); const scanResults = []; for (const path in mappedResult) { if (!mappedResult.hasOwnProperty(path)) { continue; } const fingerprints = await getFingerprints(desiredLevelsOfUnpacking, mappedResult[path]); const jarFingerprintsFact = { type: "jarFingerprints", data: { fingerprints, origin: targetImage, path, }, }; scanResults.push({ facts: [jarFingerprintsFact], identity: { type: "maven", targetFile: path, }, }); } return scanResults; } exports.jarFilesToScannedResults = jarFilesToScannedResults; async function getFingerprints(desiredLevelsOfUnpacking, jarBuffers) { const fingerprints = await unpackJars(jarBuffers, desiredLevelsOfUnpacking); return Array.from(new Set(fingerprints)); } /** * Unpacks a JAR and attempts to add coords to the * package and it's dependencies. * * JARs will always be unpacked one level more than requested * by the end-user in order to look for manifest files but will * ignore any JARs found for a level deeper than the user request. * * NOTE: desiredLevelsOfUnpacking and requiredLevelsOfUnpacking * are used to be explicit in nature and distinguish between the * level of JAR detection requested by the user and the level of * unpacking used in the implementation. * @param { object } props * @param { Buffer } props.jarBuffer * @param { string } props.jarPath * @param { number } props.desiredLevelsOfUnpacking * @param { number } props.requiredLevelsOfUnpacking * @param { number } props.unpackedLevels */ function unpackJar({ jarBuffer, jarPath, desiredLevelsOfUnpacking, requiredLevelsOfUnpacking, unpackedLevels, }) { const dependencies = []; const nestedJars = []; let coords = null; // TODO: consider switching to node-stream-zip that supports streaming let zip; let zipEntries; try { zip = new admzip(jarBuffer); zipEntries = zip.getEntries(); } catch (err) { return { location: jarPath, buffer: jarBuffer, coords: null, dependencies, nestedJars, }; } for (const zipEntry of zipEntries) { // pom.properties is file describing a package or package dependency // using this file allows resolution of shaded jars if (zipEntry.entryName.endsWith("pom.properties")) { const entryData = zipEntry.getData().toString(); const entryCoords = getCoordsFromPomProperties(entryData); if (entryCoords) { if ( // sometimes the path does not have the version jarPath.indexOf(`${entryCoords.artifactId}-${entryCoords.version}`) !== -1 || jarPath.indexOf(`${entryCoords.artifactId}`) !== -1) { coords = entryCoords; } else { dependencies.push(entryCoords); } } } // We only want to include JARs found at this level if the user asked for // unpacking using the --nested-jar-depth flag and we are in a level less // than the required level if (desiredLevelsOfUnpacking > 0 && unpackedLevels < requiredLevelsOfUnpacking && zipEntry.entryName.endsWith(".jar")) { const entryData = zipEntry.getData(); const entryName = zipEntry.entryName; nestedJars.push({ buffer: entryData, location: `${jarPath}/${entryName}`, }); } } return { location: jarPath, buffer: jarBuffer, coords, dependencies, nestedJars, }; } /** * Manages the unpacking an array of JarBuffer objects and returns the resulting * fingerprints. Recursion to required depth is handled here when the returned * info from each JAR that is unpacked has nestedJars. * * @param {JarBuffer[]} jarBuffers * @param {number} desiredLevelsOfUnpacking * @param {number} unpackedLevels * @returns JarFingerprint[] */ async function unpackJars(jarBuffers, desiredLevelsOfUnpacking, unpackedLevels = 0) { // We have to unpack jars to get the pom.properties manifest which // we use to support shaded jars and get the package coords (if exists) // to reduce the dependency on maven search and support private jars. // This means that we must unpack 1 more level than customer requests // via --nested-jar-depth option in CLI and the default value for // K8S and DRA integrations // // desiredLevelsOfUnpacking = user specified (--nested-jar-depth) or default // requiredLevelsOfUnpacking = implementation control variable const requiredLevelsOfUnpacking = desiredLevelsOfUnpacking + 1; const fingerprints = []; // jarBuffers is the array of JARS found in the image layers; // this represents the 1st "level" which we will unpack by // default to analyse. Any JARs found when analysing are nested // and we will keep going until we have no more nested JARs or // the desired level of unpacking is met for (const jarBuffer of jarBuffers) { const jarInfo = unpackJar({ jarBuffer: jarBuffer.buffer, jarPath: jarBuffer.location, unpackedLevels: unpackedLevels + 1, desiredLevelsOfUnpacking, requiredLevelsOfUnpacking, }); // we only care about JAR fingerprints. Other Java archive files are not // interesting enough on their own but are merely containers for JARs, // so no point in fingerprinting them if (jarBuffer.location.endsWith(".jar")) { // if any of the coords are null for this JAR we didn't manage to get // anything from the JAR's pom.properties manifest, so calculate the // sha so maven-deps can fallback to searching maven central fingerprints.push({ location: jarInfo.location, digest: jarInfo.coords ? null : await (0, buffer_utils_1.bufferToSha1)(jarInfo.buffer), dependencies: jarInfo.dependencies, ...jarInfo.coords, }); } if (jarInfo.nestedJars.length > 0) { // this is an uber/fat JAR so we need to unpack the nested JARs to // analyze them for coords and further nested JARs (depth flag allowing) const nestedJarFingerprints = await unpackJars(jarInfo.nestedJars, desiredLevelsOfUnpacking, unpackedLevels + 1); fingerprints.push(...nestedJarFingerprints); } } return fingerprints; } /** * Gets coords from the contents of a pom.properties file * @param {string} fileContent * @param {string} jarPath */ function getCoordsFromPomProperties(fileContent) { const coords = parsePomProperties(fileContent); // we need all of these props to allow us to inject the package // into the depGraph if (!coords.artifactId || !coords.groupId || !coords.version) { return null; } return coords; } exports.getCoordsFromPomProperties = getCoordsFromPomProperties; /** * Parses the file content of a pom.properties file to extract * the coords for a package. * @param {string} fileContent */ function parsePomProperties(fileContent) { const fileContentLines = fileContent .split(/\n/) .filter((line) => /^(groupId|artifactId|version)=/.test(line)); // These are the only properties we are interested in const coords = {}; fileContentLines.forEach((line) => { const [key, value] = line.split("="); coords[key] = value.trim(); // Getting rid of EOL }); return coords; } exports.parsePomProperties = parsePomProperties; //# sourceMappingURL=java.js.map /***/ }), /***/ 89252: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.groupNodeModulesFilesByDirectory = exports.groupNodeAppFilesByDirectory = exports.cleanupAppNodeModules = exports.persistNodeModules = void 0; const Debug = __webpack_require__(6807); const promises_1 = __webpack_require__(73292); const path = __webpack_require__(71017); const debug = Debug("snyk"); const nodeModulesRegex = /^(.*?)(?:[\\\/]node_modules)/; async function createTempProjectDir(projectDir) { const tmpDir = await (0, promises_1.mkdtemp)("snyk"); const tempProjectRoot = path.join(tmpDir, projectDir); await (0, promises_1.mkdir)(tempProjectRoot, { recursive: true }); return { tmpDir, tempProjectRoot, }; } const manifestName = "package.json"; async function fileExists(path) { return await (0, promises_1.stat)(path) .then(() => true) .catch(() => false); } async function createSyntheticManifest(tempRootManifestDir) { const tempRootManifestPath = path.join(tempRootManifestDir, manifestName); debug(`Creating an empty synthetic manifest file: ${tempRootManifestPath}`); try { await (0, promises_1.writeFile)(tempRootManifestPath, "{}", "utf-8"); } catch (error) { debug(`Error while writing file ${tempRootManifestPath} : ${error.message}`); } } async function saveOnDisk(tempDir, modules, filePathToContent) { for (const module of modules) { const manifestContent = filePathToContent[module]; if (!manifestContent) { continue; } await createFile(path.join(tempDir, module), manifestContent); } } async function persistNodeModules(project, filePathToContent, fileNamesGroupedByDirectory) { const modules = fileNamesGroupedByDirectory.get(project); const tmpDir = ""; const tempProjectRoot = ""; if (!modules || modules.size === 0) { debug(`Empty application directory tree.`); return { tempDir: tmpDir, tempProjectPath: tempProjectRoot, }; } try { const { tmpDir, tempProjectRoot } = await createTempProjectDir(project); await saveOnDisk(tmpDir, modules, filePathToContent); const result = { tempDir: tmpDir, tempProjectPath: tempProjectRoot, manifestPath: path.join(tempProjectRoot.substring(tmpDir.length), manifestName), }; const manifestFileExists = await fileExists(path.join(tempProjectRoot, manifestName)); if (!manifestFileExists) { await createSyntheticManifest(tempProjectRoot); delete result.manifestPath; } return result; } catch (error) { debug(`Failed to copy the application manifest files locally: ${error.message}`); return { tempDir: tmpDir, tempProjectPath: tempProjectRoot, }; } } exports.persistNodeModules = persistNodeModules; async function createFile(filePath, fileContent) { try { await (0, promises_1.mkdir)(path.dirname(filePath), { recursive: true }); await (0, promises_1.writeFile)(filePath, fileContent, "utf-8"); } catch (error) { debug(`Error while creating file ${filePath} : ${error.message}`); } } function isYarnCacheDependency(filePath) { if (filePath.includes(".yarn/cache") || filePath.includes(".cache/yarn") || filePath.includes("yarn\\cache") || filePath.includes("cache\\yarn") || filePath.includes("Cache\\Yarn") || filePath.includes("Yarn\\Cache")) { return true; } return false; } function isNpmCacheDependency(filePath) { if (filePath.includes(".npm/") || filePath.includes("\\npm-cache")) { return true; } return false; } // TODO: Enable custom cache filtering if needed // function isCustomCache(filePath: string): boolean { // return (filePath.includes("cache") || filePath.includes("Cache")); // } function isPnpmCacheDependency(filePath) { if (filePath.includes("pnpm-store") || filePath.includes("pnpm/store") || filePath.includes("pnpm\\store")) { return true; } return false; } function getNodeModulesParentDir(filePath) { const nodeModulesParentDirMatch = nodeModulesRegex.exec(filePath); if (nodeModulesParentDirMatch && nodeModulesParentDirMatch.length > 1) { const nodeModulesParentDir = nodeModulesParentDirMatch[1]; if (nodeModulesParentDir === "") { return "/"; // ensuring the same behavior of path.dirname for '/' dir } return nodeModulesParentDir; } return null; } function groupNodeAppFilesByDirectory(filePathToContent) { var _a; const filesByDir = new Map(); const filePaths = Object.keys(filePathToContent); for (const filePath of filePaths) { const directory = path.dirname(filePath); if (!filesByDir.has(directory)) { filesByDir.set(directory, new Set()); } (_a = filesByDir.get(directory)) === null || _a === void 0 ? void 0 : _a.add(filePath); } return filesByDir; } exports.groupNodeAppFilesByDirectory = groupNodeAppFilesByDirectory; function getGroupingDir(filePath) { const nodeModulesParentDir = getNodeModulesParentDir(filePath); if (nodeModulesParentDir) { return nodeModulesParentDir; } return path.dirname(filePath); } function groupNodeModulesFilesByDirectory(filePathToContent) { var _a; const filesByDir = new Map(); const filePaths = Object.keys(filePathToContent); for (const filePath of filePaths) { if (isNpmCacheDependency(filePath)) { continue; } if (isYarnCacheDependency(filePath)) { continue; } if (isPnpmCacheDependency(filePath)) { continue; } const directory = getGroupingDir(filePath); if (!filesByDir.has(directory)) { filesByDir.set(directory, new Set()); } (_a = filesByDir.get(directory)) === null || _a === void 0 ? void 0 : _a.add(filePath); } return filesByDir; } exports.groupNodeModulesFilesByDirectory = groupNodeModulesFilesByDirectory; async function cleanupAppNodeModules(appRootDir) { if (!appRootDir) { return; } try { await (0, promises_1.rm)(appRootDir, { recursive: true }); } catch (error) { debug(`Error while removing ${appRootDir} : ${error.message}`); } } exports.cleanupAppNodeModules = cleanupAppNodeModules; //# sourceMappingURL=node-modules-utils.js.map /***/ }), /***/ 88819: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.shouldBuildDepTree = exports.getLockFileVersion = exports.nodeFilesToScannedProjects = void 0; const dep_graph_1 = __webpack_require__(71479); const Debug = __webpack_require__(6807); const path = __webpack_require__(71017); const lockFileParser = __webpack_require__(423); const resolveDeps = __webpack_require__(40068); const debug = Debug("snyk"); const errors_1 = __webpack_require__(18920); const snyk_nodejs_lockfile_parser_1 = __webpack_require__(423); const node_modules_utils_1 = __webpack_require__(89252); async function nodeFilesToScannedProjects(filePathToContent, shouldIncludeNodeModules) { const scanResults = []; /** * TODO: Add support for Yarn workspaces! * https://github.com/snyk/nodejs-lockfile-parser/blob/af8ba81930e950156b539281ecf41c1bc63dacf4/test/lib/yarn-workflows.test.ts#L7-L17 * * When building the ScanResult ensure the workspace is stored in scanResult.identity.args: * args: { * rootWorkspace: , * }; */ if (Object.keys(filePathToContent).length === 0) { return []; } const fileNamesGroupedByDirectory = (0, node_modules_utils_1.groupNodeAppFilesByDirectory)(filePathToContent); const manifestFilePairs = findManifestLockPairsInSameDirectory(fileNamesGroupedByDirectory); if (manifestFilePairs.length !== 0) { scanResults.push(...(await depGraphFromManifestFiles(filePathToContent, manifestFilePairs))); } if (shouldIncludeNodeModules) { const appNodeModulesGroupedByDirectory = (0, node_modules_utils_1.groupNodeModulesFilesByDirectory)(filePathToContent); const nodeProjects = findManifestNodeModulesFilesInSameDirectory(appNodeModulesGroupedByDirectory); if (nodeProjects.length !== 0) { scanResults.push(...(await depGraphFromNodeModules(filePathToContent, nodeProjects, appNodeModulesGroupedByDirectory))); } } return scanResults; } exports.nodeFilesToScannedProjects = nodeFilesToScannedProjects; async function depGraphFromNodeModules(filePathToContent, nodeProjects, fileNamesGroupedByDirectory) { const scanResults = []; for (const project of nodeProjects) { const { tempDir, tempProjectPath, manifestPath } = await (0, node_modules_utils_1.persistNodeModules)(project, filePathToContent, fileNamesGroupedByDirectory); if (!tempDir) { continue; } if (!tempProjectPath) { await (0, node_modules_utils_1.cleanupAppNodeModules)(tempDir); continue; } try { const pkgTree = await resolveDeps(tempProjectPath, { dev: false, noFromArrays: true, }); if (pkgTree.numDependencies === 0) { continue; } const depGraph = await dep_graph_1.legacy.depTreeToGraph(pkgTree, pkgTree.type || "npm"); scanResults.push({ facts: [ { type: "depGraph", data: depGraph, }, { type: "testedFiles", data: manifestPath ? manifestPath : path.join(project, "node_modules"), }, ], identity: { type: depGraph.pkgManager.name, targetFile: manifestPath ? manifestPath : path.join(project, "node_modules"), }, }); } catch (error) { debug(`An error occurred while analysing node_modules dir: ${error.message}`); } finally { await (0, node_modules_utils_1.cleanupAppNodeModules)(tempDir); } } return scanResults; } async function depGraphFromManifestFiles(filePathToContent, manifestFilePairs) { const scanResults = []; const shouldIncludeDevDependencies = false; const shouldBeStrictForManifestAndLockfileOutOfSync = false; for (const pathPair of manifestFilePairs) { let depGraph; try { const lockfileVersion = getLockFileVersion(pathPair.lock, filePathToContent[pathPair.lock]); depGraph = shouldBuildDepTree(lockfileVersion) ? await buildDepGraphFromDepTree(filePathToContent[pathPair.manifest], filePathToContent[pathPair.lock], pathPair.lockType, shouldIncludeDevDependencies, shouldBeStrictForManifestAndLockfileOutOfSync) : await buildDepGraph(filePathToContent[pathPair.manifest], filePathToContent[pathPair.lock], lockfileVersion, shouldIncludeDevDependencies, shouldBeStrictForManifestAndLockfileOutOfSync); } catch (err) { debug(`An error occurred while analysing a pair of manifest and lock files: ${err.message}`); continue; } const depGraphFact = { type: "depGraph", data: depGraph, }; const testedFilesFact = { type: "testedFiles", data: [path.basename(pathPair.manifest), path.basename(pathPair.lock)], }; scanResults.push({ facts: [depGraphFact, testedFilesFact], identity: { type: depGraph.pkgManager.name, targetFile: pathPair.manifest, }, }); } return scanResults; } function findManifestLockPairsInSameDirectory(fileNamesGroupedByDirectory) { const manifestLockPathPairs = []; for (const directoryPath of fileNamesGroupedByDirectory.keys()) { if (directoryPath.includes("node_modules")) { continue; } const filesInDirectory = fileNamesGroupedByDirectory.get(directoryPath); if (!filesInDirectory || filesInDirectory.size < 1) { // missing manifest files continue; } const expectedManifest = path.join(directoryPath, "package.json"); const expectedNpmLockFile = path.join(directoryPath, "package-lock.json"); const expectedYarnLockFile = path.join(directoryPath, "yarn.lock"); const hasManifestFile = filesInDirectory.has(expectedManifest); const hasLockFile = filesInDirectory.has(expectedNpmLockFile) || filesInDirectory.has(expectedYarnLockFile); if (hasManifestFile && hasLockFile) { manifestLockPathPairs.push({ manifest: expectedManifest, // TODO: correlate filtering action with expected lockfile types lock: filesInDirectory.has(expectedNpmLockFile) ? expectedNpmLockFile : expectedYarnLockFile, lockType: filesInDirectory.has(expectedNpmLockFile) ? lockFileParser.LockfileType.npm : lockFileParser.LockfileType.yarn, }); } } return manifestLockPathPairs; } function findManifestNodeModulesFilesInSameDirectory(fileNamesGroupedByDirectory) { const nodeProjects = []; for (const directoryPath of fileNamesGroupedByDirectory.keys()) { const filesInDirectory = fileNamesGroupedByDirectory.get(directoryPath); if (!filesInDirectory || filesInDirectory.size < 1) { // missing manifest files continue; } const expectedManifest = path.join(directoryPath, "package.json"); const expectedNpmLockFile = path.join(directoryPath, "package-lock.json"); const expectedYarnLockFile = path.join(directoryPath, "yarn.lock"); const hasManifestFile = filesInDirectory.has(expectedManifest); const hasLockFile = filesInDirectory.has(expectedNpmLockFile) || filesInDirectory.has(expectedYarnLockFile); if (hasManifestFile && hasLockFile) { continue; } nodeProjects.push(directoryPath); } return nodeProjects; } function stripUndefinedLabels(parserResult) { const optionalLabels = parserResult.labels; const mandatoryLabels = {}; if (optionalLabels) { for (const currentLabelName of Object.keys(optionalLabels)) { if (optionalLabels[currentLabelName] !== undefined) { mandatoryLabels[currentLabelName] = optionalLabels[currentLabelName]; } } } const parserResultWithProperLabels = Object.assign({}, parserResult, { labels: mandatoryLabels, }); return parserResultWithProperLabels; } async function buildDepGraph(manifestFileContents, lockFileContents, lockfileVersion, shouldIncludeDevDependencies, shouldBeStrictForManifestAndLockfileOutOfSync) { switch (lockfileVersion) { case snyk_nodejs_lockfile_parser_1.NodeLockfileVersion.YarnLockV1: return await lockFileParser.parseYarnLockV1Project(manifestFileContents, lockFileContents, { includeDevDeps: shouldIncludeDevDependencies, includeOptionalDeps: true, includePeerDeps: false, pruneLevel: "withinTopLevelDeps", strictOutOfSync: shouldBeStrictForManifestAndLockfileOutOfSync, }); case snyk_nodejs_lockfile_parser_1.NodeLockfileVersion.YarnLockV2: return await lockFileParser.parseYarnLockV2Project(manifestFileContents, lockFileContents, { includeDevDeps: shouldIncludeDevDependencies, includeOptionalDeps: true, pruneWithinTopLevelDeps: true, strictOutOfSync: shouldBeStrictForManifestAndLockfileOutOfSync, }); case snyk_nodejs_lockfile_parser_1.NodeLockfileVersion.NpmLockV2: case snyk_nodejs_lockfile_parser_1.NodeLockfileVersion.NpmLockV3: return await lockFileParser.parseNpmLockV2Project(manifestFileContents, lockFileContents, { includeDevDeps: shouldIncludeDevDependencies, includeOptionalDeps: true, pruneCycles: true, strictOutOfSync: shouldBeStrictForManifestAndLockfileOutOfSync, }); } throw new Error("Failed to build dep graph from current project, unknown lockfile version : " + lockfileVersion.toString() + "."); } async function buildDepGraphFromDepTree(manifestFileContents, lockFileContents, lockfileType, shouldIncludeDevDependencies, shouldBeStrictForManifestAndLockfileOutOfSync) { const parserResult = await lockFileParser.buildDepTree(manifestFileContents, lockFileContents, shouldIncludeDevDependencies, lockfileType, shouldBeStrictForManifestAndLockfileOutOfSync); const strippedLabelsParserResult = stripUndefinedLabels(parserResult); return await dep_graph_1.legacy.depTreeToGraph(strippedLabelsParserResult, lockfileType); } function getLockFileVersion(lockFilePath, lockFileContents) { let lockfileVersion; if (lockFilePath.endsWith("package-lock.json")) { lockfileVersion = (0, snyk_nodejs_lockfile_parser_1.getNpmLockfileVersion)(lockFileContents); } else if (lockFilePath.endsWith("yarn.lock")) { lockfileVersion = (0, snyk_nodejs_lockfile_parser_1.getYarnLockfileVersion)(lockFileContents); } else if (lockFilePath.endsWith("pnpm-lock.yaml")) { lockfileVersion = (0, snyk_nodejs_lockfile_parser_1.getPnpmLockfileVersion)(lockFileContents); } else { throw new errors_1.InvalidUserInputError(`Unknown lockfile ${lockFilePath}. ` + "Please provide either package-lock.json, yarn.lock or pnpm-lock.yaml"); } return lockfileVersion; } exports.getLockFileVersion = getLockFileVersion; function shouldBuildDepTree(lockfileVersion) { return !(lockfileVersion === snyk_nodejs_lockfile_parser_1.NodeLockfileVersion.YarnLockV1 || lockfileVersion === snyk_nodejs_lockfile_parser_1.NodeLockfileVersion.YarnLockV2 || lockfileVersion === snyk_nodejs_lockfile_parser_1.NodeLockfileVersion.NpmLockV2 || lockfileVersion === snyk_nodejs_lockfile_parser_1.NodeLockfileVersion.NpmLockV3); } exports.shouldBuildDepTree = shouldBuildDepTree; //# sourceMappingURL=node.js.map /***/ }), /***/ 36609: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.phpFilesToScannedProjects = void 0; const dep_graph_1 = __webpack_require__(71479); const path = __webpack_require__(71017); const composer_lockfile_parser_1 = __webpack_require__(59794); const errors_1 = __webpack_require__(18920); const PACKAGE_MANAGER_TYPE = "composer"; async function phpFilesToScannedProjects(filePathToContent) { const scanResults = []; const filePairs = findManifestLockPairsInSameDirectory(filePathToContent); const shouldIncludeDevDependencies = false; for (const pathPair of filePairs) { let parserResult; try { parserResult = (0, composer_lockfile_parser_1.buildDepTree)(filePathToContent[pathPair.lock], filePathToContent[pathPair.manifest], pathPair.manifest, {}, shouldIncludeDevDependencies); } catch (e) { // This will skip parsing all files that error due to being malformed. // If we do not do this, the entire scan will fail. // Ideally, we'd like to log this, but logging does not exist in this library. if (e instanceof errors_1.InvalidUserInputError) { continue; } else { throw e; } } const depGraph = await dep_graph_1.legacy.depTreeToGraph(parserResult, PACKAGE_MANAGER_TYPE); const depGraphFact = { type: "depGraph", data: depGraph, }; const testedFilesFact = { type: "testedFiles", data: [path.basename(pathPair.manifest), path.basename(pathPair.lock)], }; scanResults.push({ facts: [depGraphFact, testedFilesFact], identity: { type: depGraph.pkgManager.name, targetFile: pathPair.lock, }, }); } return scanResults; } exports.phpFilesToScannedProjects = phpFilesToScannedProjects; function findManifestLockPairsInSameDirectory(filePathToContent) { const fileNamesGroupedByDirectory = groupFilesByDirectory(filePathToContent); const manifestLockPathPairs = []; for (const directoryPath of Object.keys(fileNamesGroupedByDirectory)) { const filesInDirectory = fileNamesGroupedByDirectory[directoryPath]; if (filesInDirectory.length !== 2) { // either a missing file or too many files, ignore continue; } const hasComposerJson = filesInDirectory.includes("composer.json"); const hasComposerLock = filesInDirectory.includes("composer.lock"); if (hasComposerJson && hasComposerLock) { manifestLockPathPairs.push({ manifest: path.join(directoryPath, "composer.json"), lock: path.join(directoryPath, "composer.lock"), }); } } return manifestLockPathPairs; } // assumption: we only care about manifest+lock files if they are in the same directory function groupFilesByDirectory(filePathToContent) { const fileNamesGroupedByDirectory = {}; for (const filePath of Object.keys(filePathToContent)) { const directory = path.dirname(filePath); const fileName = path.basename(filePath); if (!fileNamesGroupedByDirectory[directory]) { fileNamesGroupedByDirectory[directory] = []; } fileNamesGroupedByDirectory[directory].push(fileName); } return fileNamesGroupedByDirectory; } //# sourceMappingURL=php.js.map /***/ }), /***/ 76491: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.poetryFilesToScannedProjects = exports.pipFilesToScannedProjects = void 0; const pip_1 = __webpack_require__(27436); Object.defineProperty(exports, "pipFilesToScannedProjects", ({ enumerable: true, get: function () { return pip_1.pipFilesToScannedProjects; } })); const poetry_1 = __webpack_require__(90864); Object.defineProperty(exports, "poetryFilesToScannedProjects", ({ enumerable: true, get: function () { return poetry_1.poetryFilesToScannedProjects; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 27436: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.pipFilesToScannedProjects = void 0; const dep_graph_1 = __webpack_require__(71479); const Debug = __webpack_require__(6807); const event_loop_spinner_1 = __webpack_require__(77158); const path = __webpack_require__(71017); const semver = __webpack_require__(41009); const common_1 = __webpack_require__(60409); const metadata_parser_1 = __webpack_require__(97176); const requirements_parser_1 = __webpack_require__(13157); const debug = Debug("snyk"); class PythonDepGraphBuilder { constructor(name, requirements, metadata) { this.visitedMap = new Set(); this.requirements = requirements; this.metadata = metadata; this.builder = new dep_graph_1.DepGraphBuilder({ name: "pip" }, { name }); } async build() { for (const dep of this.requirements) { await this.addDependenciesToDepGraph(this.builder.rootNodeId, dep); } return this.builder.build(); } // depth-first search for dependencies and assigning them to the dep graph builder async addDependenciesToDepGraph(root, req) { var _a; if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } const metadata = this.findMetadata(req); if (!metadata) { return; } const extrasId = ((_a = req.extras) === null || _a === void 0 ? void 0 : _a.length) ? `:${req.extras}` : ""; const nodeId = `${metadata.name}@${metadata.version}${extrasId}`; if (!this.visitedMap.has(nodeId)) { this.visitedMap.add(nodeId); this.builder.addPkgNode({ name: metadata.name, version: metadata.version }, nodeId); for (const dep of metadata.dependencies) { if (this.shouldTraverse(req, dep)) { await this.addDependenciesToDepGraph(nodeId, dep); } } } this.builder.connectDep(root, nodeId); } // test extras and environment markers to determine whether a dependency is optional // if it is optional only traverse if the requirement asked for those optionals shouldTraverse(req, dep) { var _a; // always traverse deps with no extra environment markers (they're non-optional) if (!dep.extraEnvMarkers || dep.extraEnvMarkers.length === 0) { return true; } // determine if dep was required with extras, and those extras match the deps env markers const intersection = (_a = req.extras) === null || _a === void 0 ? void 0 : _a.filter((i) => { var _a; return (_a = dep.extraEnvMarkers) === null || _a === void 0 ? void 0 : _a.includes(i); }); // yes! this is an optional dependency that was asked for if (intersection && intersection.length > 0) { return true; } return false; // no! stop here we don't want to traverse optional dependencies } // find the best match for a dependency in found metadata files findMetadata(dep) { const nameMatches = this.metadata[dep.name.toLowerCase()]; if (!nameMatches || nameMatches.length === 0) { return null; } if (nameMatches.length === 1 || !dep.version) { return nameMatches[0]; } for (const meta of nameMatches) { if (semver.satisfies(meta.version, `${dep.specifier}${dep.version}`, true)) { return meta; } } // fallback to the first metadata file if no match is found return nameMatches[0]; } } /** * Creates a dep graph for every requirements.txt file that was found */ async function pipFilesToScannedProjects(filePathToContent) { const scanResults = []; const requirements = {}; const metadataItems = {}; for (const filepath of Object.keys(filePathToContent)) { const fileBaseName = path.basename(filepath); if (fileBaseName === "requirements.txt") { requirements[filepath] = (0, requirements_parser_1.getRequirements)(filePathToContent[filepath]); } else if (fileBaseName === "METADATA") { try { const packageInfo = (0, metadata_parser_1.getPackageInfo)(filePathToContent[filepath]); if (!metadataItems[packageInfo.name.toLowerCase()]) { metadataItems[packageInfo.name.toLowerCase()] = []; } metadataItems[packageInfo.name.toLowerCase()].push(packageInfo); } catch (err) { debug(err.message); } } } if (Object.keys(metadataItems).length === 0) { return scanResults; } // pre-sort each package name by version, descending for (const name of Object.keys(metadataItems)) { metadataItems[name].sort((v1, v2) => { return (0, common_1.compareVersions)(v1.version, v2.version); }); } for (const requirementsFile of Object.keys(requirements)) { if (requirements[requirementsFile].length === 0) { continue; } const builder = new PythonDepGraphBuilder(requirementsFile, requirements[requirementsFile], metadataItems); const depGraph = await builder.build(); if (!depGraph) { continue; } const depGraphFact = { type: "depGraph", data: depGraph, }; scanResults.push({ facts: [depGraphFact], identity: { type: "pip", targetFile: requirementsFile, }, }); } return scanResults; } exports.pipFilesToScannedProjects = pipFilesToScannedProjects; //# sourceMappingURL=pip.js.map /***/ }), /***/ 90864: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.poetryFilesToScannedProjects = void 0; const path = __webpack_require__(71017); const lockFileParser = __webpack_require__(34580); async function poetryFilesToScannedProjects(filePathToContent) { const scanResults = []; const filePairs = findManifestLockPairsInSameDirectory(filePathToContent); const shouldIncludeDevDependencies = false; for (const pathPair of filePairs) { const depGraph = await lockFileParser.buildDepGraph(filePathToContent[pathPair.manifest], filePathToContent[pathPair.lock], shouldIncludeDevDependencies); if (!depGraph) { continue; } const depGraphFact = { type: "depGraph", data: depGraph, }; const testedFilesFact = { type: "testedFiles", data: [path.basename(pathPair.manifest), path.basename(pathPair.lock)], }; scanResults.push({ facts: [depGraphFact, testedFilesFact], identity: { type: depGraph.pkgManager.name, targetFile: pathPair.manifest, }, }); } return scanResults; } exports.poetryFilesToScannedProjects = poetryFilesToScannedProjects; function findManifestLockPairsInSameDirectory(filePathToContent) { const fileNamesGroupedByDirectory = groupFilesByDirectory(filePathToContent); const manifestLockPathPairs = []; for (const directoryPath of Object.keys(fileNamesGroupedByDirectory)) { const filesInDirectory = fileNamesGroupedByDirectory[directoryPath]; if (filesInDirectory.length !== 2) { // either a missing file or too many files, ignore continue; } const hasManifest = filesInDirectory.includes("pyproject.toml"); const hasLockFile = filesInDirectory.includes("poetry.lock"); if (hasManifest && hasLockFile) { manifestLockPathPairs.push({ manifest: path.join(directoryPath, "pyproject.toml"), lock: path.join(directoryPath, "poetry.lock"), }); } } return manifestLockPathPairs; } // assumption: we only care about manifest+lock files if they are in the same directory function groupFilesByDirectory(filePathToContent) { const fileNamesGroupedByDirectory = {}; for (const filePath of Object.keys(filePathToContent)) { const directory = path.dirname(filePath); const fileName = path.basename(filePath); if (!fileNamesGroupedByDirectory[directory]) { fileNamesGroupedByDirectory[directory] = []; } fileNamesGroupedByDirectory[directory].push(fileName); } return fileNamesGroupedByDirectory; } //# sourceMappingURL=poetry.js.map /***/ }), /***/ 9286: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getApplicationFiles = exports.getAppFilesRootDir = void 0; const path = __webpack_require__(71017); function getAppFilesRootDir(filePaths) { const appFiles = []; const splitPaths = []; if (!filePaths.length) { return [path.sep, appFiles]; } for (const filePath of filePaths) { appFiles.push({ path: filePath }); splitPaths.push(filePath.split("/").filter(Boolean)); } // Find the shortest path length to prevent out-of-bounds access const minLength = Math.min(...splitPaths.map((path) => path.length)); // Find the common parts of the paths const commonParts = []; for (let i = 0; i < minLength - 1; i++) { const currentPart = splitPaths[0][i]; if (splitPaths.every((path) => path[i] === currentPart)) { commonParts.push(currentPart); } else { break; } } // Join the common parts to form the common directory const rootDir = "/" + commonParts.join("/"); // Remove the common path prefix from each appFile appFiles.forEach((file) => { const prefix = rootDir === path.sep ? rootDir : `${rootDir}${path.sep}`; if (file.path.startsWith(prefix)) { file.path = file.path.substring(prefix.length); // Remove rootDir from path } }); return [rootDir || path.sep, appFiles]; } exports.getAppFilesRootDir = getAppFilesRootDir; function getApplicationFiles(filePathToContent, language, identityType) { const scanResults = []; const [appFilesRootDir, appFiles] = getAppFilesRootDir(Object.keys(filePathToContent)); if (appFiles.length) { scanResults.push({ facts: [ { type: "applicationFiles", data: [ { language, fileHierarchy: appFiles, }, ], }, ], identity: { type: identityType, targetFile: appFilesRootDir, }, }); } return scanResults; } exports.getApplicationFiles = getApplicationFiles; //# sourceMappingURL=runtime-common.js.map /***/ }), /***/ 95710: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.pullIfNotLocal = exports.extractImageDetails = exports.getImageArchive = void 0; const Debug = __webpack_require__(6807); const fs = __webpack_require__(57147); const mkdirp = __webpack_require__(38545); const path = __webpack_require__(71017); const docker_1 = __webpack_require__(42980); const image_1 = __webpack_require__(92748); const debug = Debug("snyk"); async function getInspectResult(docker, targetImage) { const info = await docker.inspectImage(targetImage); return JSON.parse(info.stdout)[0]; } function cleanupCallback(imageFolderPath, imageName) { return () => { const fullImagePath = path.join(imageFolderPath, imageName); if (fs.existsSync(fullImagePath)) { fs.unlinkSync(fullImagePath); } try { fs.rmdirSync(imageFolderPath); } catch (err) { debug(`Can't remove folder ${imageFolderPath}, got error ${err.message}`); } }; } async function pullWithDockerBinary(docker, targetImage, saveLocation, username, password, platform) { let pullAndSaveSuccessful = false; try { if (username || password) { debug("using local docker binary credentials. the credentials you provided will be ignored"); } await docker.pullCli(targetImage, { platform }); await docker.save(targetImage, saveLocation); return (pullAndSaveSuccessful = true); } catch (err) { debug(`couldn't pull ${targetImage} using docker binary: ${err.message}`); handleDockerPullError(err.stderr, platform); return pullAndSaveSuccessful; } } function handleDockerPullError(err, platform) { if (err && err.includes("unknown operating system or architecture")) { throw new Error("Unknown operating system or architecture"); } if (err.includes("operating system is not supported")) { throw new Error(`Operating system is not supported`); } const unknownManifestConditions = [ "no matching manifest for", "manifest unknown", ]; if (unknownManifestConditions.some((value) => err.includes(value))) { if (platform) { throw new Error(`The image does not exist for ${platform}`); } throw new Error(`The image does not exist for the current platform`); } if (err.includes("invalid reference format")) { throw new Error(`invalid image format`); } if (err.includes("unknown flag: --platform")) { throw new Error('"--platform" is only supported on a Docker daemon with version later than 17.09'); } if (err === '"--platform" is only supported on a Docker daemon with experimental features enabled') { throw new Error(err); } } async function pullFromContainerRegistry(docker, targetImage, imageSavePath, username, password, platform) { const { hostname, imageName, tag } = extractImageDetails(targetImage); debug(`Attempting to pull: registry: ${hostname}, image: ${imageName}, tag: ${tag}`); try { return await docker.pull(hostname, imageName, tag, imageSavePath, username, password, platform); } catch (err) { handleDockerPullError(err.message); throw err; } } async function pullImage(docker, targetImage, saveLocation, imageSavePath, username, password, platform) { if (await docker_1.Docker.binaryExists()) { const pullAndSaveSuccessful = await pullWithDockerBinary(docker, targetImage, saveLocation, username, password, platform); if (pullAndSaveSuccessful) { return new image_1.ImageName(targetImage); } } const { indexDigest, manifestDigest } = await pullFromContainerRegistry(docker, targetImage, imageSavePath, username, password, platform); const imageName = new image_1.ImageName(targetImage, { manifest: manifestDigest, index: indexDigest, }); return imageName; } /** * In the case that an `ImageType.Identifier` is detected we need to produce * an image archive, either by saving the image if it's already loaded into * the local docker daemon, or by pulling the image from a remote registry and * saving it to the filesystem directly. * * Users may also provide us with a URL to an image in a Docker compatible * remote registry. * * @param {string} targetImage - The image to test, this could be in one of * the following forms: * * [registry/]/[:tag] * * /[:tag] * * [:tag] * In the case that a registry is not provided, the plugin will default * this to Docker Hub. If a tag is not provided this will default to * `latest`. * @param {string} [username] - Optional username for private repo auth. * @param {string} [password] - Optional password for private repo auth. * @param {string} [platform] - Optional platform parameter to pull specific image arch. */ async function getImageArchive(targetImage, imageSavePath, username, password, platform) { const docker = new docker_1.Docker(); mkdirp.sync(imageSavePath); const destination = { name: imageSavePath, removeCallback: cleanupCallback(imageSavePath, "image.tar"), }; const saveLocation = path.join(destination.name, "image.tar"); let inspectResult; try { inspectResult = await getInspectResult(docker, targetImage); } catch (_a) { debug(`${targetImage} does not exist locally, proceeding to pull image.`); } if (inspectResult === undefined) { const imageName = await pullImage(docker, targetImage, saveLocation, imageSavePath, username, password, platform); return { imageName, path: saveLocation, removeArchive: destination.removeCallback, }; } if (platform !== undefined && inspectResult && !isLocalImageSameArchitecture(platform, inspectResult.Architecture)) { const imageName = await pullImage(docker, targetImage, saveLocation, imageSavePath, username, password, platform); return { imageName, path: saveLocation, removeArchive: destination.removeCallback, }; } else { await docker.save(targetImage, saveLocation); const imageName = new image_1.ImageName(targetImage); return { imageName, path: saveLocation, removeArchive: destination.removeCallback, }; } } exports.getImageArchive = getImageArchive; function isImagePartOfURL(targetImage) { // Based on the Docker spec, if the image contains a hostname, then the hostname should contain // a `.` or `:` before the first instance of a `/`. ref: https://stackoverflow.com/a/37867949 if (!targetImage.includes("/")) { return false; } const partBeforeFirstForwardSlash = targetImage.split("/")[0]; return (partBeforeFirstForwardSlash.includes(".") || partBeforeFirstForwardSlash.includes(":") || partBeforeFirstForwardSlash === "localhost"); } function extractHostnameFromTargetImage(targetImage) { // We need to detect if the `targetImage` is part of a URL. If not, the default hostname will be // used (registry-1.docker.io). ref: https://stackoverflow.com/a/37867949 const defaultHostname = "registry-1.docker.io"; if (!isImagePartOfURL(targetImage)) { return { hostname: defaultHostname, remainder: targetImage }; } const dockerFriendlyRegistryHostname = "docker.io/"; if (targetImage.startsWith(dockerFriendlyRegistryHostname)) { return { hostname: defaultHostname, remainder: targetImage.substring(dockerFriendlyRegistryHostname.length), }; } const i = targetImage.indexOf("/"); return { hostname: targetImage.substring(0, i), remainder: targetImage.substring(i + 1), }; } function extractImageNameAndTag(remainder, targetImage) { const defaultTag = "latest"; if (!remainder.includes("@")) { const [imageName, tag] = remainder.split(":"); return { imageName: appendDefaultRepoPrefixIfRequired(imageName, targetImage), tag: tag || defaultTag, }; } const [imageName, tag] = remainder.split("@"); return { imageName: appendDefaultRepoPrefixIfRequired(dropTagIfSHAIsPresent(imageName), targetImage), tag: tag || defaultTag, }; } function appendDefaultRepoPrefixIfRequired(imageName, targetImage) { const defaultRepoPrefix = "library/"; if (isImagePartOfURL(targetImage) || imageName.includes("/")) { return imageName; } return defaultRepoPrefix + imageName; } function dropTagIfSHAIsPresent(imageName) { if (!imageName.includes(":")) { return imageName; } return imageName.split(":")[0]; } function extractImageDetails(targetImage) { const { hostname, remainder } = extractHostnameFromTargetImage(targetImage); const { imageName, tag } = extractImageNameAndTag(remainder, targetImage); return { hostname, imageName, tag }; } exports.extractImageDetails = extractImageDetails; function isLocalImageSameArchitecture(platformOption, inspectResultArchitecture) { let platformArchitecture; try { // Note: this is using the same flag/input pattern as the new Docker buildx: eg. linux/arm64/v8 platformArchitecture = platformOption.split("/")[1]; } catch (error) { debug(`Error parsing platform flag: '${error.message}'`); return false; } return platformArchitecture === inspectResultArchitecture; } async function pullIfNotLocal(targetImage, options) { const docker = new docker_1.Docker(); try { await docker.inspectImage(targetImage); return; } catch (err) { // image doesn't exist locally } await docker.pullCli(targetImage); } exports.pullIfNotLocal = pullIfNotLocal; //# sourceMappingURL=image-inspector.js.map /***/ }), /***/ 55269: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.analyzeStatically = void 0; const static_analyzer_1 = __webpack_require__(28531); Object.defineProperty(exports, "analyzeStatically", ({ enumerable: true, get: function () { return static_analyzer_1.analyze; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 69975: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.detectStatically = void 0; const static_1 = __webpack_require__(2625); Object.defineProperty(exports, "detectStatically", ({ enumerable: true, get: function () { return static_1.detect; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 36556: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.tryOracleRelease = exports.tryCentosRelease = exports.tryRedHatRelease = exports.tryAlpineRelease = exports.tryDebianVersion = exports.tryLsbRelease = exports.tryOSRelease = void 0; async function tryOSRelease(text) { if (!text) { return null; } const idRes = text.match(/^ID=(.+)$/m); if (!idRes) { throw new Error("Failed to parse /etc/os-release"); } const name = idRes[1].replace(/"/g, ""); const versionRes = text.match(/^VERSION_ID=(.+)$/m); let version = versionRes ? versionRes[1].replace(/"/g, "") : "unstable"; if (name === "ol") { version = version.split(".")[0]; } let prettyName = ""; const prettyNameRes = text.match(/^PRETTY_NAME=(.+)$/m); if (prettyNameRes) { prettyName = prettyNameRes[1].replace(/"/g, ""); } return { name, version, prettyName }; } exports.tryOSRelease = tryOSRelease; async function tryLsbRelease(text) { if (!text) { return null; } const idRes = text.match(/^DISTRIB_ID=(.+)$/m); const versionRes = text.match(/^DISTRIB_RELEASE=(.+)$/m); if (!idRes || !versionRes) { throw new Error("Failed to parse /etc/lsb-release"); } const name = idRes[1].replace(/"/g, "").toLowerCase(); const version = versionRes[1].replace(/"/g, ""); return { name, version, prettyName: "" }; } exports.tryLsbRelease = tryLsbRelease; async function tryDebianVersion(text) { if (!text) { return null; } text = text.trim(); if (text.length < 2) { throw new Error("Failed to parse /etc/debian_version"); } return { name: "debian", version: text.split(".")[0], prettyName: "" }; } exports.tryDebianVersion = tryDebianVersion; async function tryAlpineRelease(text) { if (!text) { return null; } text = text.trim(); if (text.length < 2) { throw new Error("Failed to parse /etc/alpine-release"); } return { name: "alpine", version: text, prettyName: "" }; } exports.tryAlpineRelease = tryAlpineRelease; async function tryRedHatRelease(text) { if (!text) { return null; } const idRes = text.match(/^(\S+)/m); const versionRes = text.match(/(\d+)\./m); if (!idRes || !versionRes) { throw new Error("Failed to parse /etc/redhat-release"); } const name = text.indexOf("Red Hat") !== -1 ? "rhel" : idRes[1].replace(/"/g, "").toLowerCase(); const version = versionRes[1].replace(/"/g, ""); return { name, version, prettyName: "" }; } exports.tryRedHatRelease = tryRedHatRelease; async function tryCentosRelease(text) { if (!text) { return null; } const idRes = text.match(/^(\S+)/m); const versionRes = text.match(/(\d+)\./m); if (!idRes || !versionRes) { throw new Error("Failed to parse /etc/centos-release"); } const name = idRes[1].replace(/"/g, "").toLowerCase(); const version = versionRes[1].replace(/"/g, ""); return { name, version, prettyName: "" }; } exports.tryCentosRelease = tryCentosRelease; async function tryOracleRelease(text) { if (!text) { return null; } const idRes = text.match(/^(\S+)/m); const versionRes = text.match(/(\d+\.\d+)/m); if (!idRes || !versionRes) { throw new Error("Failed to parse /etc/oracle-release"); } const name = idRes[1].replace(/"/g, "").toLowerCase(); const version = versionRes[1].replace(/"/g, "").split(".")[0]; return { name, version, prettyName: "" }; } exports.tryOracleRelease = tryOracleRelease; //# sourceMappingURL=release-analyzer.js.map /***/ }), /***/ 2625: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.detect = void 0; const Debug = __webpack_require__(6807); const os_release_1 = __webpack_require__(17835); const types_1 = __webpack_require__(93677); const release_analyzer_1 = __webpack_require__(36556); const debug = Debug("snyk"); const releaseDetectors = { [types_1.OsReleaseFilePath.Linux]: release_analyzer_1.tryOSRelease, // Fallback for the case where the same file exists in different location or is a symlink to the other location [types_1.OsReleaseFilePath.LinuxFallback]: release_analyzer_1.tryOSRelease, // Generic fallback [types_1.OsReleaseFilePath.Lsb]: release_analyzer_1.tryLsbRelease, // Fallbacks for specific older distributions [types_1.OsReleaseFilePath.Debian]: release_analyzer_1.tryDebianVersion, [types_1.OsReleaseFilePath.Alpine]: release_analyzer_1.tryAlpineRelease, [types_1.OsReleaseFilePath.Oracle]: release_analyzer_1.tryOracleRelease, [types_1.OsReleaseFilePath.RedHat]: release_analyzer_1.tryRedHatRelease, [types_1.OsReleaseFilePath.Centos]: release_analyzer_1.tryCentosRelease, }; async function detect(extractedLayers, dockerfileAnalysis) { /** * We want to detect whether the OS release file existed, but it just could not be parsed successfully. * This is so that we can distinguish between images with multiple "os-release" files - some of them * may fail to parse while others will succeed. This will depend purely on the order of our handlers. * We want to run all handlers and only then decide if detection succeeded or not. */ let hadOsReleaseFile = false; let osRelease = null; for (const [type, handler] of Object.entries(releaseDetectors)) { const osReleaseFile = (0, os_release_1.getOsReleaseStatic)(extractedLayers, type); if (!osReleaseFile) { continue; } hadOsReleaseFile = true; try { osRelease = await handler(osReleaseFile); } catch (err) { debug(`Malformed OS release file: ${err.message}`); } if (osRelease) { break; } } if (!osRelease && hadOsReleaseFile) { throw new Error("Failed to parse OS release file"); } if (!osRelease) { if (dockerfileAnalysis && dockerfileAnalysis.baseImage === "scratch") { // If the docker file was build from a scratch image // then we don't have a known OS osRelease = { name: "scratch", version: "0.0", prettyName: "" }; } else { osRelease = { name: "unknown", version: "0.0", prettyName: "" }; } } // Oracle Linux identifies itself as "ol" if (osRelease.name.trim() === "ol") { osRelease.name = "oracle"; } // Support round version. ie change SLES 15 to SLES 15.0 if (osRelease.name.trim() === "sles" && osRelease.version && !osRelease.version.includes(".")) { osRelease.version += ".0"; } return osRelease; } exports.detect = detect; //# sourceMappingURL=static.js.map /***/ }), /***/ 86555: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.analyze = void 0; const types_1 = __webpack_require__(36293); function analyze(targetImage, apkDbFileContent) { return Promise.resolve({ Image: targetImage, AnalyzeType: types_1.AnalysisType.Apk, Analysis: parseFile(apkDbFileContent), }); } exports.analyze = analyze; function parseFile(text) { const pkgs = []; let curPkg = null; for (const line of text.split("\n")) { curPkg = parseLine(line, curPkg, pkgs); } return pkgs; } function parseLine(text, curPkg, pkgs) { const key = text.charAt(0); const value = text.substr(2).trim(); switch (key) { case "P": // Package curPkg = { Name: value, Version: "", Source: undefined, Provides: [], Deps: {}, AutoInstalled: undefined, }; pkgs.push(curPkg); break; case "V": // Version curPkg.Version = value; break; case "p": // Provides for (let name of value.split(" ")) { name = name.split("=")[0]; curPkg.Provides.push(name); } break; case "r": // Depends case "D": // Depends // tslint:disable-next-line:no-duplicate-variable for (let name of value.split(" ")) { if (name.charAt(0) !== "!") { name = name.split("=")[0]; curPkg.Deps[name] = true; } } break; case "o": // Origin curPkg.Source = value; break; } return curPkg; } //# sourceMappingURL=apk.js.map /***/ }), /***/ 21332: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.purl = exports.analyzeDistroless = exports.analyze = void 0; const packageurl_js_1 = __webpack_require__(38382); const types_1 = __webpack_require__(36293); function analyze(targetImage, aptFiles, osRelease) { const pkgs = parseDpkgFile(aptFiles.dpkgFile, osRelease); if (aptFiles.extFile) { setAutoInstalledPackages(aptFiles.extFile, pkgs); } return Promise.resolve({ Image: targetImage, AnalyzeType: types_1.AnalysisType.Apt, Analysis: pkgs, }); } exports.analyze = analyze; function analyzeDistroless(targetImage, aptFiles, osRelease) { const analyzedPackages = []; for (const fileContent of aptFiles) { const currentPackages = parseDpkgFile(fileContent, osRelease); analyzedPackages.push(...currentPackages); } return Promise.resolve({ Image: targetImage, AnalyzeType: types_1.AnalysisType.Apt, Analysis: analyzedPackages, }); } exports.analyzeDistroless = analyzeDistroless; function parseDpkgFile(text, osRelease) { const pkgs = []; let curPkg = null; for (const line of text.split("\n")) { curPkg = parseDpkgLine(line, curPkg, pkgs); if (curPkg) { curPkg.Purl = purl(curPkg, osRelease); } } return pkgs; } const debianCodenames = new Map([ ["8", "jessie"], ["9", "stretch"], ["10", "buster"], ["11", "bullseye"], ["12", "bookworm"], ["13", "trixie"], ["unstable", "sid"], ]); function purl(curPkg, osRelease) { var _a; let vendor = ""; if (!curPkg.Name || !curPkg.Version) { return undefined; } const qualifiers = {}; if (curPkg.Source && curPkg.SourceVersion) { qualifiers.upstream = `${curPkg.Source}@${curPkg.SourceVersion}`; } else if (curPkg.Source) { qualifiers.upstream = curPkg.Source; } if (osRelease) { const codenameOrVersion = (_a = debianCodenames.get(osRelease.version)) !== null && _a !== void 0 ? _a : osRelease.version; qualifiers.distro = `${osRelease.name}-${codenameOrVersion}`; vendor = osRelease.name; } return new packageurl_js_1.PackageURL("deb", vendor, curPkg.Name, curPkg.Version, // make sure that we pass in undefined if there are no qualifiers, because // the packageurl-js library doesn't handle that properly... Object.keys(qualifiers).length !== 0 ? qualifiers : undefined, undefined).toString(); } exports.purl = purl; function parseDpkgLine(text, curPkg, pkgs) { const [key, value] = text.split(": "); switch (key) { case "Package": curPkg = { Name: value, Version: "", Source: undefined, SourceVersion: undefined, Provides: [], Deps: {}, AutoInstalled: undefined, }; pkgs.push(curPkg); break; case "Version": curPkg.Version = value; break; case "Source": /** * The value may look something like this: * libgcc6 (1.3.0-b1) * () * * For example, Syft matches these values with a regex: * https://github.com/anchore/syft/blob/1764e1c3f6bd66781f8350d957a1f95e4d9ad3de/syft/pkg/cataloger/deb/parse_dpkg_db.go#L169-L173 */ const parts = value.split(" "); curPkg.Source = parts[0]; if (parts.length > 1) { curPkg.SourceVersion = parts[1] .trim() .replace("(", "") .replace(")", ""); } break; case "Provides": for (let name of value.split(",")) { name = name.trim().split(" ")[0]; curPkg.Provides.push(name); } break; case "Pre-Depends": case "Depends": for (const depElem of value.split(",")) { for (let name of depElem.split("|")) { name = name.trim().split(" ")[0]; curPkg.Deps[name] = true; } } break; } return curPkg; } function setAutoInstalledPackages(text, pkgs) { const autoPkgs = parseExtFile(text); for (const pkg of pkgs) { if (autoPkgs[pkg.Name]) { pkg.AutoInstalled = true; } } } function parseExtFile(text) { const pkgMap = {}; let curPkgName = null; for (const line of text.split("\n")) { curPkgName = parseExtLine(line, curPkgName, pkgMap); } return pkgMap; } function parseExtLine(text, curPkgName, pkgMap) { const [key, value] = text.split(": "); switch (key) { case "Package": curPkgName = value; break; case "Auto-Installed": if (parseInt(value, 10) === 1) { pkgMap[curPkgName] = true; } break; } return curPkgName; } //# sourceMappingURL=apt.js.map /***/ }), /***/ 851: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.mapRpmSqlitePackages = exports.analyze = void 0; const rpm_parser_1 = __webpack_require__(76713); const packageurl_js_1 = __webpack_require__(38382); const types_1 = __webpack_require__(36293); function analyze(targetImage, pkgs, repositories, osRelease) { return Promise.resolve({ Image: targetImage, AnalyzeType: types_1.AnalysisType.Rpm, Analysis: pkgs.map((pkgInfo) => { return { Name: pkgInfo.name, Version: (0, rpm_parser_1.formatRpmPackageVersion)(pkgInfo), Source: undefined, Provides: [], Deps: {}, AutoInstalled: undefined, Purl: purl(pkgInfo, repositories, osRelease), }; }), }); } exports.analyze = analyze; function purl(pkg, repos, osRelease) { let vendor = ""; const qualifiers = {}; if (pkg.module) { const [modName, modVersion] = pkg.module.split(":"); qualifiers.module = modName + ":" + modVersion; } if (repos.length > 0) { qualifiers.repositories = repos.join(","); } if (pkg.epoch) { qualifiers.epoch = String(pkg.epoch); } if (osRelease) { qualifiers.distro = `${osRelease.name}-${osRelease.version}`; vendor = osRelease.name; } return new packageurl_js_1.PackageURL(types_1.AnalysisType.Rpm.toLowerCase(), vendor, pkg.name, (0, rpm_parser_1.formatRpmPackageVersion)(pkg), // make sure that we pass in undefined if there are no qualifiers, because // the packageurl-js library doesn't handle that properly... Object.keys(qualifiers).length !== 0 ? qualifiers : undefined, undefined).toString(); } function mapRpmSqlitePackages(targetImage, rpmPackages, repositories, osRelease) { let analysis = []; if (rpmPackages) { analysis = rpmPackages.map((pkg) => { return { Name: pkg.name, Version: (0, rpm_parser_1.formatRpmPackageVersion)(pkg), Source: undefined, Provides: [], Deps: {}, AutoInstalled: undefined, Purl: purl(pkg, repositories, osRelease), }; }); } return { Image: targetImage, AnalyzeType: types_1.AnalysisType.Rpm, Analysis: analysis, }; } exports.mapRpmSqlitePackages = mapRpmSqlitePackages; //# sourceMappingURL=rpm.js.map /***/ }), /***/ 28531: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.analyze = void 0; const Debug = __webpack_require__(6807); const archiveExtractor = __webpack_require__(18141); const go_parser_1 = __webpack_require__(5998); const inputs_1 = __webpack_require__(29484); const static_1 = __webpack_require__(97770); const static_2 = __webpack_require__(52851); const static_3 = __webpack_require__(23426); const static_4 = __webpack_require__(236); const filePatternStatic = __webpack_require__(89589); const static_5 = __webpack_require__(92212); const static_6 = __webpack_require__(5809); const static_7 = __webpack_require__(96704); const static_8 = __webpack_require__(92578); const static_9 = __webpack_require__(88795); const static_10 = __webpack_require__(98157); const static_11 = __webpack_require__(45330); const option_utils_1 = __webpack_require__(48587); const applications_1 = __webpack_require__(19551); const java_1 = __webpack_require__(3823); const python_1 = __webpack_require__(76491); const runtime_common_1 = __webpack_require__(9286); const osReleaseDetector = __webpack_require__(69975); const apk_1 = __webpack_require__(86555); const apt_1 = __webpack_require__(21332); const rpm_1 = __webpack_require__(851); const debug = Debug("snyk"); async function analyze(targetImage, dockerfileAnalysis, imageType, imagePath, globsToFind, options) { const staticAnalysisActions = [ static_1.getApkDbFileContentAction, static_2.getDpkgFileContentAction, static_2.getExtFileContentAction, static_11.getRpmDbFileContentAction, static_11.getRpmSqliteDbFileContentAction, ...static_7.getOsReleaseActions, static_3.getNodeBinariesFileContentAction, static_3.getOpenJDKBinariesFileContentAction, static_4.getDpkgPackageFileContentAction, static_10.getRedHatRepositoriesContentAction, ]; const checkForGlobs = shouldCheckForGlobs(globsToFind); if (checkForGlobs) { staticAnalysisActions.push(filePatternStatic.generateExtractAction(globsToFind.include, globsToFind.exclude)); } const appScan = !(0, option_utils_1.isTrue)(options["exclude-app-vulns"]); const nodeModulesScan = !(0, option_utils_1.isTrue)(options["exclude-node-modules"]); // A runtime logic enabler flag. Is off by default. const collectApplicationFiles = (0, option_utils_1.isTrue)(options["collect-application-files"]); if (appScan) { staticAnalysisActions.push(...[ static_6.getNodeAppFileContentAction, static_8.getPhpAppFileContentAction, static_9.getPoetryAppFileContentAction, static_9.getPipAppFileContentAction, static_5.getJarFileContentAction, go_parser_1.getGoModulesContentAction, ]); if (collectApplicationFiles) { staticAnalysisActions.push(static_6.getNodeJsTsAppFileContentAction, static_9.getPythonAppFileContentAction); } } const { imageId, manifestLayers, extractedLayers, rootFsLayers, autoDetectedUserInstructions, platform, imageLabels, imageCreationTime, } = await archiveExtractor.extractImageContent(imageType, imagePath, staticAnalysisActions, options); const [apkDbFileContent, aptDbFileContent, rpmDbFileContent, rpmSqliteDbFileContent,] = await Promise.all([ (0, static_1.getApkDbFileContent)(extractedLayers), (0, static_2.getAptDbFileContent)(extractedLayers), (0, static_11.getRpmDbFileContent)(extractedLayers), (0, static_11.getRpmSqliteDbFileContent)(extractedLayers), ]); const distrolessAptFiles = (0, static_4.getAptFiles)(extractedLayers); const manifestFiles = []; if (checkForGlobs) { const matchingFiles = filePatternStatic.getMatchingFiles(extractedLayers); manifestFiles.push(...matchingFiles); } let osRelease; try { osRelease = await osReleaseDetector.detectStatically(extractedLayers, dockerfileAnalysis); } catch (err) { debug(`Could not detect OS release: ${err.message}`); throw new Error("Failed to detect OS release"); } const redHatRepositories = (0, static_10.getRedHatRepositoriesFromExtractedLayers)(extractedLayers); let results; try { results = await Promise.all([ (0, apk_1.analyze)(targetImage, apkDbFileContent), (0, apt_1.analyze)(targetImage, aptDbFileContent, osRelease), (0, rpm_1.analyze)(targetImage, rpmDbFileContent, redHatRepositories, osRelease), (0, rpm_1.mapRpmSqlitePackages)(targetImage, rpmSqliteDbFileContent, redHatRepositories, osRelease), (0, apt_1.analyzeDistroless)(targetImage, distrolessAptFiles, osRelease), ]); } catch (err) { debug(`Could not detect installed OS packages: ${err.message}`); throw new Error("Failed to detect installed OS packages"); } const binaries = (0, static_3.getBinariesHashes)(extractedLayers); const applicationDependenciesScanResults = []; if (appScan) { const nodeDependenciesScanResults = await (0, applications_1.nodeFilesToScannedProjects)((0, inputs_1.getFileContent)(extractedLayers, static_6.getNodeAppFileContentAction.actionName), nodeModulesScan); let nodeApplicationFilesScanResults = []; if (collectApplicationFiles) { nodeApplicationFilesScanResults = (0, runtime_common_1.getApplicationFiles)((0, inputs_1.getFileContent)(extractedLayers, static_6.getNodeJsTsAppFileContentAction.actionName), "node", "npm"); } const phpDependenciesScanResults = await (0, applications_1.phpFilesToScannedProjects)((0, inputs_1.getFileContent)(extractedLayers, static_8.getPhpAppFileContentAction.actionName)); const poetryDependenciesScanResults = await (0, applications_1.poetryFilesToScannedProjects)((0, inputs_1.getFileContent)(extractedLayers, static_9.getPoetryAppFileContentAction.actionName)); const pipDependenciesScanResults = await (0, python_1.pipFilesToScannedProjects)((0, inputs_1.getFileContent)(extractedLayers, static_9.getPipAppFileContentAction.actionName)); let pythonApplicationFilesScanResults = []; if (collectApplicationFiles) { pythonApplicationFilesScanResults = (0, runtime_common_1.getApplicationFiles)((0, inputs_1.getFileContent)(extractedLayers, static_9.getPythonAppFileContentAction.actionName), "python", "python"); } const desiredLevelsOfUnpacking = getNestedJarsDesiredDepth(options); const jarFingerprintScanResults = await (0, java_1.jarFilesToScannedResults)((0, inputs_1.getBufferContent)(extractedLayers, static_5.getJarFileContentAction.actionName), targetImage, desiredLevelsOfUnpacking); const goModulesScanResult = await (0, go_parser_1.goModulesToScannedProjects)((0, inputs_1.getElfFileContent)(extractedLayers, go_parser_1.getGoModulesContentAction.actionName)); applicationDependenciesScanResults.push(...nodeDependenciesScanResults, ...nodeApplicationFilesScanResults, ...phpDependenciesScanResults, ...poetryDependenciesScanResults, ...pipDependenciesScanResults, ...pythonApplicationFilesScanResults, ...jarFingerprintScanResults, ...goModulesScanResult); } return { imageId, osRelease, platform, results, binaries, imageLayers: manifestLayers, rootFsLayers, applicationDependenciesScanResults, manifestFiles, autoDetectedUserInstructions, imageLabels, imageCreationTime, }; } exports.analyze = analyze; function getNestedJarsDesiredDepth(options) { const nestedJarsOption = options["nested-jars-depth"] || options["shaded-jars-depth"]; let nestedJarsDepth = 1; const depthNumber = Number(nestedJarsOption); if (!isNaN(depthNumber) && depthNumber >= 0) { nestedJarsDepth = depthNumber; } return nestedJarsDepth; } function shouldCheckForGlobs(globsToFind) { return globsToFind.include.length > 0; } //# sourceMappingURL=static-analyzer.js.map /***/ }), /***/ 36293: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AnalysisType = void 0; var AnalysisType; (function (AnalysisType) { AnalysisType["Apk"] = "Apk"; AnalysisType["Apt"] = "Apt"; AnalysisType["Rpm"] = "Rpm"; AnalysisType["Binaries"] = "binaries"; AnalysisType["Linux"] = "linux"; })(AnalysisType = exports.AnalysisType || (exports.AnalysisType = {})); //# sourceMappingURL=types.js.map /***/ }), /***/ 29098: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.bufferToSha1 = void 0; const crypto = __webpack_require__(6113); const types_1 = __webpack_require__(93677); const HASH_ENCODING = "hex"; async function bufferToSha1(buffer) { const hash = crypto.createHash(types_1.HashAlgorithm.Sha1); const chunkSize = 100 * 1024 * 1024; // 100 MB return new Promise((resolve, reject) => { try { for (let offset = 0; offset < buffer.length; offset += chunkSize) { const end = Math.min(offset + chunkSize, buffer.length); const chunk = buffer.slice(offset, end); hash.update(chunk); } const digest = hash.digest(HASH_ENCODING); resolve(digest); } catch (err) { reject(err); } }); } exports.bufferToSha1 = bufferToSha1; //# sourceMappingURL=buffer-utils.js.map /***/ }), /***/ 95997: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildTree = void 0; /** @deprecated Should implement a new function to build a dependency graph instead. */ function buildTree(targetImage, packageFormat, depInfosList, targetOS) { // A tag can only occur in the last section of a docker image name, so // check any colon separator after the final '/'. If there are no '/', // which is common when using Docker's official images such as // "debian:stretch", just check for ':' const finalSlash = targetImage.lastIndexOf("/"); const hasVersion = (finalSlash >= 0 && targetImage.slice(finalSlash).includes(":")) || targetImage.includes(":"); // Defaults for simple images from dockerhub, like "node" or "centos" let imageName = targetImage; let imageVersion = "latest"; // If we have a version, split on the last ':' to avoid the optional // port on a hostname (i.e. localhost:5000) if (hasVersion) { const versionSeparator = targetImage.lastIndexOf(":"); imageName = targetImage.slice(0, versionSeparator); imageVersion = targetImage.slice(versionSeparator + 1); } if (imageName.endsWith(".tar")) { imageVersion = ""; } const shaString = "@sha256"; if (imageName.endsWith(shaString)) { imageName = imageName.slice(0, imageName.length - shaString.length); imageVersion = ""; } const root = { // don't use the real image name to avoid scanning it as an issue name: "docker-image|" + imageName, version: imageVersion, targetOS, packageFormatVersion: packageFormat + ":0.0.1", dependencies: {}, }; const depsMap = depInfosList.reduce((acc, depInfo) => { const name = depInfo.Name; acc[name] = depInfo; return acc; }, {}); const virtualDepsMap = depInfosList.reduce((acc, depInfo) => { const providesNames = depInfo.Provides || []; for (const name of providesNames) { acc[name] = depInfo; } return acc; }, {}); const depsCounts = {}; for (const depInfo of depInfosList) { countDepsRecursive(depInfo.Name, new Set(), depsMap, virtualDepsMap, depsCounts); } const DEP_FREQ_THRESHOLD = 100; const tooFrequentDepNames = Object.keys(depsCounts).filter((depName) => { return depsCounts[depName] > DEP_FREQ_THRESHOLD; }); const attachDeps = (depInfos) => { const depNamesToSkip = new Set(tooFrequentDepNames); for (const depInfo of depInfos) { const subtree = buildTreeRecursive(depInfo.Name, new Set(), depsMap, virtualDepsMap, depNamesToSkip); if (subtree) { root.dependencies[subtree.name] = subtree; } } }; // attach (as direct deps) pkgs not marked auto-installed: const manuallyInstalledDeps = depInfosList.filter((depInfo) => { return !depInfo.AutoInstalled; }); attachDeps(manuallyInstalledDeps); // attach (as direct deps) pkgs marked as auto-installed, // but not dependant upon: const notVisitedDeps = depInfosList.filter((depInfo) => { const depName = depInfo.Name; return !depsMap[depName]._visited; }); attachDeps(notVisitedDeps); // attach all the "too frequent" deps to the root: if (tooFrequentDepNames.length > 0) { const tooFrequentDeps = tooFrequentDepNames.map((name) => { return depsMap[name]; }); const metaSubtree = { name: "meta-common-packages", version: "meta", dependencies: {}, }; for (const depInfo of tooFrequentDeps) { const pkg = { name: depFullName(depInfo), version: depInfo.Version, sourceVersion: depInfo.SourceVersion, dependencies: {}, }; // The existence of the "meta" package breaks upgrade // logic for linux pkg managers if (["deb", "apk", "rpm"].includes(packageFormat)) { root.dependencies[pkg.name] = pkg; } else { metaSubtree.dependencies[pkg.name] = pkg; } } if (Object.keys(metaSubtree.dependencies).length > 0) { root.dependencies[metaSubtree.name] = metaSubtree; } } return root; } exports.buildTree = buildTree; function buildTreeRecursive(depName, ancestors, depsMap, virtualDepsMap, depNamesToSkip) { const depInfo = depsMap[depName] || virtualDepsMap[depName]; if (!depInfo) { return null; } // "realName" as the argument depName might be a virtual pkg const realName = depInfo.Name; const fullName = depFullName(depInfo); if (ancestors.has(fullName) || depNamesToSkip.has(realName)) { return null; } const tree = { name: fullName, version: depInfo.Version, purl: depInfo.Purl, dependencies: {}, }; if (depInfo._visited) { return tree; } depInfo._visited = true; const newAncestors = new Set(ancestors).add(fullName); const deps = depInfo.Deps || {}; for (const name of Object.keys(deps)) { const subTree = buildTreeRecursive(name, newAncestors, depsMap, virtualDepsMap, depNamesToSkip); if (subTree) { if (!tree.dependencies) { tree.dependencies = {}; } if (!tree.dependencies[subTree.name]) { tree.dependencies[subTree.name] = subTree; } } } return tree; } function countDepsRecursive(depName, ancestors, depsMap, virtualDepsMap, depCounts) { const depInfo = depsMap[depName] || virtualDepsMap[depName]; if (!depInfo) { return; } // "realName" as the argument depName might be a virtual pkg const realName = depInfo.Name; if (ancestors.has(realName)) { return; } depCounts[realName] = (depCounts[realName] || 0) + 1; const newAncestors = new Set(ancestors).add(realName); const deps = depInfo.Deps || {}; for (const name of Object.keys(deps)) { countDepsRecursive(name, newAncestors, depsMap, virtualDepsMap, depCounts); } } function depFullName(depInfo) { let fullName = depInfo.Name; if (depInfo.Source) { fullName = depInfo.Source + "/" + fullName; } return fullName; } //# sourceMappingURL=index.js.map /***/ }), /***/ 75613: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.formatRemediations = exports.display = void 0; const chalk_1 = __webpack_require__(32589); const os = __webpack_require__(22037); const dep_graph_1 = __webpack_require__(71479); const BREAK_LINE = os.EOL; const SECTION_PADDING_TO_FORMAT_METADATA = 19; async function display(scanResults, testResults, errors, options) { const result = []; let index = 0; for (const testResult of testResults) { const formattedIssue = []; for (const issue of testResult.issues) { formattedIssue.push(formatIssue(testResult, issue)); } result.push(formattedIssue.join(BREAK_LINE)); result.push(includeSectionSeparator()); const scanResult = scanResults[index]; const metadata = formatMetadataSection(scanResult, testResult); result.push(metadata); result.push(includeSectionSeparator()); const summary = formatSummary(testResult); result.push(summary); result.push(includeSectionSeparator()); const remediations = formatRemediations(testResult); if (remediations) { result.push(remediations); result.push(includeSectionSeparator()); } const suggestions = formatSuggestions(options); if (suggestions) { result.push(suggestions); result.push(includeSectionSeparator()); } const userCTA = formatUserCTA(options); if (userCTA) { result.push(userCTA); } index += 1; } return result.join(BREAK_LINE); } exports.display = display; function includeSectionSeparator() { return BREAK_LINE; } function formatIssue(testResult, issue) { const result = []; const issueData = testResult.issuesData[issue.issueId]; const severity = capitalize(issueData.severity); const pkg = issue.pkgName; const color = getColor(issueData.severity); const header = color(`✗ ${severity} severity vulnerability found in ${pkg}`); const description = ` Description: ${issueData.title}`; const info = ` Info: https://snyk.io/vuln/${issue.issueId}`; const introduced = ` Introduced through: ${formatIntroduced(issueData.from)}`; const from = formatFrom(issueData.from); const fixedIn = formatFixedIn(issue); result.push(header); result.push(description); result.push(info); result.push(introduced); result.push(from); if (fixedIn) { result.push(fixedIn); } result.push(""); return result.join(BREAK_LINE); } function capitalize(word) { return word[0].toUpperCase() + word.slice(1); } function formatIntroduced(fromList) { const result = []; for (const from of fromList) { result.push(from[0]); } return result.join(", "); } function formatFrom(fromList) { const result = []; let counter = 0; const max = 3; for (const localFrom of fromList) { if (counter >= max) { break; } counter += 1; result.push(` From: ${localFrom.join(" > ")}`); } if (fromList.length > max) { result.push(` and ${(fromList.length = max)} more...`); } return result.join(BREAK_LINE); } function formatFixedIn(issue) { if (!issue.fixInfo || !issue.fixInfo.nearestFixedInVersion) { return undefined; } return chalk_1.default.bold.green(` Fixed in: ${issue.fixInfo.nearestFixedInVersion}`); } function formatMetadataSection(scanResult, testResult) { var _a; const result = []; result.push(formatMetadataLine("Organization:", testResult.org)); const packageManager = scanResult.identity.type; result.push(formatMetadataLine("Package manager:", packageManager)); const target = scanResult.target; const projectName = target.image; const image = target.image.replace("docker-image|", ""); result.push(formatMetadataLine("Project name:", projectName)); result.push(formatMetadataLine("Docker image:", image)); if (testResult.docker && testResult.docker.baseImage) { result.push(formatMetadataLine("Base image:", testResult.docker.baseImage)); } if (testResult.licensesPolicy) { result.push(formatMetadataLine("Licenses:", chalk_1.default.green("enabled"))); } const platform = (_a = scanResult.identity.args) === null || _a === void 0 ? void 0 : _a.platform; if (platform) { result.push(formatMetadataLine("Platform:", platform)); } return result.join(BREAK_LINE); } function formatMetadataLine(header, info = "") { return `${chalk_1.default.green(padding(header, SECTION_PADDING_TO_FORMAT_METADATA))} ${info}`; } function formatSummary(testResult) { var _a; const depGraph = (0, dep_graph_1.createFromJSON)(testResult.depGraphData); const pkgCount = ((_a = depGraph === null || depGraph === void 0 ? void 0 : depGraph.getDepPkgs()) === null || _a === void 0 ? void 0 : _a.length) || 0; const pathOrDepsText = `${pkgCount} dependencies`; const testedInfoText = `Tested ${pathOrDepsText} for known issues`; const vulnPathsText = formatVulnSummaryText(testResult.issues); let summaryText = `${testedInfoText}, ${vulnPathsText}`; if (testResult.issues.length === 0) { summaryText = chalk_1.default.green(`✓ ${summaryText}`); } return summaryText; } function formatVulnSummaryText(issues) { if (issues.length > 0) { return chalk_1.default.bold.red(`found ${issues.length} issues.`); } return "no vulnerable paths found."; } function getColor(severity) { let color; switch (severity) { case "low": color = chalk_1.default.bold.blue; break; case "medium": color = chalk_1.default.bold.yellow; break; case "high": color = chalk_1.default.bold.red; break; default: color = chalk_1.default.whiteBright; break; } return color; } function formatRemediations(res) { if (!res.docker || !res.docker.baseImageRemediation) { return ""; } const { advice, message } = res.docker.baseImageRemediation; const out = []; if (advice) { for (const item of advice) { out.push(formatString(item)(item.message)); } } else if (message) { out.push(message); } else { return ""; } return `${out.join(BREAK_LINE)}`; } exports.formatRemediations = formatRemediations; function formatString({ color, bold }) { let formatter = chalk_1.default; if (color && formatter[color]) { formatter = formatter[color]; } if (bold) { formatter = formatter.bold; } return formatter; } function formatSuggestions(options) { if (options.isDockerUser) { return ""; } const dockerSuggestion = []; if (options.config && options.config.disableSuggestions !== "true") { const optOutSuggestions = "To remove this message in the future, please run `snyk config set disableSuggestions=true`"; if (!options.file) { dockerSuggestion.push(chalk_1.default.bold.white("Pro tip: use `--file` option to get base image remediation advice.")); dockerSuggestion.push(chalk_1.default.bold.white(`Example: $ snyk container test ${options.path} --file=path/to/Dockerfile`)); dockerSuggestion.push(BREAK_LINE); dockerSuggestion.push(optOutSuggestions); } else if (!options["exclude-base-image-vulns"]) { dockerSuggestion.push(chalk_1.default.bold.white("Pro tip: use `--exclude-base-image-vulns` to exclude from display Docker base image vulnerabilities.")); dockerSuggestion.push(BREAK_LINE); dockerSuggestion.push(optOutSuggestions); } } return dockerSuggestion.join(BREAK_LINE); } function formatUserCTA(options) { if (options.isDockerUser) { return "For more free scans that keep your images secure, sign up to Snyk at https://dockr.ly/3ePqVcp"; } return ""; } function padding(s, padding) { const padLength = padding - s.length; if (padLength <= 0) { return s; } return s + " ".repeat(padLength); } //# sourceMappingURL=display.js.map /***/ }), /***/ 42980: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Docker = void 0; const docker_registry_v2_client_1 = __webpack_require__(28310); const snyk_docker_pull_1 = __webpack_require__(39106); const Debug = __webpack_require__(6807); const Modem = __webpack_require__(89168); const fs_1 = __webpack_require__(57147); const subProcess = __webpack_require__(15476); const debug = Debug("snyk"); class Docker { static async binaryExists() { try { await subProcess.execute("docker", ["version"]); return true; } catch (e) { return false; } } async pull(registry, repo, tag, imageSavePath, username, password, platform) { const dockerPull = new snyk_docker_pull_1.DockerPull(); const platformTokens = platform ? platform.split("/") : undefined; let os = "linux"; let architecture = "amd64"; let variant; if (platformTokens) { const platformTokensLen = platformTokens.length; if (platformTokensLen <= 1) { throw Error("Invalid platform string. Please provide a platform name that follows os/arch[/variant] format."); } os = platformTokens[0]; architecture = platformTokens[1]; variant = platformTokens[2]; } const opt = { username, password, loadImage: false, platform: platformTokens ? { os, architecture, variant } : undefined, imageSavePath, reqOptions: { acceptManifest: [ docker_registry_v2_client_1.contentTypes.OCI_MANIFEST_V1, docker_registry_v2_client_1.contentTypes.OCI_INDEX_V1, docker_registry_v2_client_1.contentTypes.MANIFEST_V2, docker_registry_v2_client_1.contentTypes.MANIFEST_LIST_V2, ].join(","), }, }; return await dockerPull.pull(registry, repo, tag, opt); } async pullCli(targetImage, options) { const args = ["pull", targetImage]; if (options === null || options === void 0 ? void 0 : options.platform) { args.push(`--platform=${options.platform}`); } return subProcess.execute("docker", args); } async save(targetImage, destination) { const request = { path: `/images/${targetImage}/get?`, method: "GET", isStream: true, statusCodes: { 200: true, 400: "bad request", 404: "not found", 500: "server error", }, }; debug(`Docker.save: targetImage: ${targetImage}, destination: ${destination}`); const modem = new Modem(); return new Promise((resolve, reject) => { modem.dial(request, (err, stream) => { if (err) { return reject(err); } const writeStream = (0, fs_1.createWriteStream)(destination); writeStream.on("error", (err) => { reject(err); }); writeStream.on("finish", () => { resolve(); }); stream.on("error", (err) => { reject(err); }); stream.on("end", () => { writeStream.end(); }); stream.pipe(writeStream); }); }); } async inspectImage(targetImage) { return subProcess.execute("docker", ["inspect", targetImage]); } } exports.Docker = Docker; //# sourceMappingURL=docker.js.map /***/ }), /***/ 79652: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseDockerfile = exports.updateDockerfileBaseImageName = exports.getDockerfileBaseImageName = exports.getPackagesFromDockerfile = exports.instructionDigest = exports.readDockerfileAndAnalyse = exports.analyseDockerfile = void 0; const dockerfile_ast_1 = __webpack_require__(20871); const fs = __webpack_require__(57147); const path_1 = __webpack_require__(71017); const instruction_parser_1 = __webpack_require__(50387); Object.defineProperty(exports, "getDockerfileBaseImageName", ({ enumerable: true, get: function () { return instruction_parser_1.getDockerfileBaseImageName; } })); Object.defineProperty(exports, "getPackagesFromDockerfile", ({ enumerable: true, get: function () { return instruction_parser_1.getPackagesFromDockerfile; } })); Object.defineProperty(exports, "instructionDigest", ({ enumerable: true, get: function () { return instruction_parser_1.instructionDigest; } })); const instruction_updater_1 = __webpack_require__(37641); Object.defineProperty(exports, "updateDockerfileBaseImageName", ({ enumerable: true, get: function () { return instruction_updater_1.updateDockerfileBaseImageName; } })); async function readDockerfileAndAnalyse(dockerfilePath) { if (!dockerfilePath) { return undefined; } const contents = await readFile((0, path_1.normalize)(dockerfilePath)); return analyseDockerfile(contents); } exports.readDockerfileAndAnalyse = readDockerfileAndAnalyse; async function analyseDockerfile(contents) { const dockerfile = dockerfile_ast_1.DockerfileParser.parse(contents); const baseImageResult = (0, instruction_parser_1.getDockerfileBaseImageName)(dockerfile); const dockerfilePackages = (0, instruction_parser_1.getPackagesFromDockerfile)(dockerfile); const dockerfileLayers = (0, instruction_parser_1.getLayersFromPackages)(dockerfilePackages); return { baseImage: baseImageResult.baseImage, dockerfilePackages, dockerfileLayers, error: baseImageResult.error, }; } exports.analyseDockerfile = analyseDockerfile; async function readFile(path) { return new Promise((resolve, reject) => { fs.readFile(path, "utf8", (err, data) => { return err ? reject(err) : resolve(data); }); }); } function parseDockerfile(content) { return dockerfile_ast_1.DockerfileParser.parse(content); } exports.parseDockerfile = parseDockerfile; //# sourceMappingURL=index.js.map /***/ }), /***/ 50387: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getPackagesFromRunInstructions = exports.instructionDigest = exports.getPackagesFromDockerfile = exports.getLayersFromPackages = exports.getDockerfileBaseImageName = void 0; const types_1 = __webpack_require__(93677); const types_2 = __webpack_require__(13939); // Naive regex; see tests for cases // tslint:disable-next-line:max-line-length const installRegex = /(rpm\s+-i|rpm\s+--install|apk\s+((--update|-u|--no-cache)\s+)*add(\s+(--update|-u|--no-cache))*|apt-get\s+((--assume-yes|--yes|-y)\s+)*install(\s+(--assume-yes|--yes|-y))*|apt\s+((--assume-yes|--yes|-y)\s+)*install|yum\s+install|aptitude\s+install)\s+/; function getPackagesFromDockerfile(dockerfile) { const runInstructions = getRunInstructionsFromDockerfile(dockerfile); return getPackagesFromRunInstructions(runInstructions); } exports.getPackagesFromDockerfile = getPackagesFromDockerfile; function getRunInstructionsFromDockerfile(dockerfile) { return dockerfile .getInstructions() .filter((instruction) => instruction.getInstruction().toUpperCase() === "RUN") .map((instruction) => getInstructionExpandVariables(instruction, dockerfile, types_1.UnresolvedDockerfileVariableHandling.Continue)); } /* * This is fairly ugly because a single RUN could contain multiple install * commands, which in turn may install multiple packages, so we've got a * 3-level nested array (RUN instruction[] -> install[] -> package[]) * * We also need to account for the multiple ways to split commands, and * arbitrary whitespace */ function getPackagesFromRunInstructions(runInstructions) { return runInstructions.reduce((dockerfilePackages, instruction) => { const cleanedInstruction = cleanInstruction(instruction); const commands = cleanedInstruction.split(/\s?(;|&&)\s?/); const installCommands = commands.filter((command) => installRegex.test(command)); if (installCommands.length) { // Get the packages per install command and flatten them for (const command of installCommands) { const packages = command .replace(installRegex, "") .split(/\s+/) .filter((arg) => arg && !arg.startsWith("-")); packages.forEach((pkg) => { var _a; // Use package name without version as the key let name = pkg.split("=")[0]; if (name.startsWith("$")) { name = name.slice(1); } const installCommand = ((_a = installCommands .find((cmd) => cmd.indexOf(name) !== -1)) === null || _a === void 0 ? void 0 : _a.replace(/\s+/g, " ").trim()) || "Unknown"; dockerfilePackages[name] = { instruction, installCommand, }; }); } } return dockerfilePackages; }, {}); } exports.getPackagesFromRunInstructions = getPackagesFromRunInstructions; /** * Return the instruction text without any of the image prefixes * @param instruction the full RUN instruction extracted from image */ function cleanInstruction(instruction) { let cleanedInstruction = instruction; const runDefs = ["RUN ", "/bin/sh ", "-c "]; const argsPrefixRegex = /^\|\d .*?=/; for (const runDef of runDefs) { if (cleanedInstruction.startsWith(runDef)) { cleanedInstruction = cleanedInstruction.slice(runDef.length); if (runDef === runDefs[0] && argsPrefixRegex.test(cleanedInstruction)) { const match = installRegex.exec(cleanedInstruction); if (match) { cleanedInstruction = cleanedInstruction.slice(match.index); } } } } return cleanedInstruction; } /** * Return the specified text with variables expanded * @param instruction the instruction associated with this string * @param dockerfile Dockerfile to use for expanding the variables * @param unresolvedVariableHandling Strategy for reacting to unresolved vars * @param text a string with variables to expand, if not specified * the instruction text is used */ function getInstructionExpandVariables(instruction, dockerfile, unresolvedVariableHandling, text) { let str = text || instruction.toString(); const resolvedVariables = {}; for (const variable of instruction.getVariables()) { const line = variable.getRange().start.line; const name = variable.getName(); resolvedVariables[name] = dockerfile.resolveVariable(name, line); } for (const variable of Object.keys(resolvedVariables)) { if (unresolvedVariableHandling === types_1.UnresolvedDockerfileVariableHandling.Abort && !resolvedVariables[variable]) { str = ""; break; } // The $ is a special regexp character that should be escaped with a backslash // Support both notations either with $variable_name or ${variable_name} // The global search "g" flag is used to match and replace all occurrences str = str.replace(RegExp(`\\$\{${variable}\}|\\$${variable}`, "g"), resolvedVariables[variable] || ""); } return str; } /** * Return the image name of the last from stage, after resolving all aliases * @param dockerfile Dockerfile to use for retrieving the last stage image name */ function getDockerfileBaseImageName(dockerfile) { const froms = dockerfile.getFROMs(); // collect stages names const stagesNames = froms.reduce((stagesNames, fromInstruction) => { const fromName = fromInstruction.getImage(); const args = fromInstruction.getArguments(); // the FROM expanded base name const expandedName = getInstructionExpandVariables(fromInstruction, dockerfile, types_1.UnresolvedDockerfileVariableHandling.Abort, fromName); const hasUnresolvedVariables = expandedName.split(":").some((name) => !name) || expandedName.split("@").some((name) => !name); if (args.length > 2 && args[1].getValue().toUpperCase() === "AS") { // the AS alias name const aliasName = args[2].getValue(); // support nested referral if (!expandedName) { stagesNames.aliases[aliasName] = null; } else { stagesNames.aliases[aliasName] = stagesNames.aliases[expandedName] || expandedName; } } const hasUnresolvedAlias = Object.keys(stagesNames.aliases).includes(expandedName) && !stagesNames.aliases[expandedName]; if (expandedName === "" || hasUnresolvedVariables || hasUnresolvedAlias) { return { ...stagesNames, last: undefined, }; } // store the resolved stage name stagesNames.last = stagesNames.aliases[expandedName] || expandedName; return stagesNames; }, { last: undefined, aliases: {} }); if (stagesNames.last) { return { baseImage: stagesNames.last, }; } if (!froms.length) { return { error: { code: types_2.DockerFileAnalysisErrorCode.BASE_IMAGE_NAME_NOT_FOUND, }, }; } return { error: { code: types_2.DockerFileAnalysisErrorCode.BASE_IMAGE_NON_RESOLVABLE, }, }; } exports.getDockerfileBaseImageName = getDockerfileBaseImageName; function instructionDigest(instruction) { return Buffer.from(instruction).toString("base64"); } exports.instructionDigest = instructionDigest; function getLayersFromPackages(dockerfilePkgs) { return Object.keys(dockerfilePkgs).reduce((res, pkg) => { const { instruction } = dockerfilePkgs[pkg]; res[instructionDigest(instruction)] = { instruction }; return res; }, {}); } exports.getLayersFromPackages = getLayersFromPackages; //# sourceMappingURL=instruction-parser.js.map /***/ }), /***/ 37641: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.updateDockerfileBaseImageName = void 0; const dockerfile_ast_1 = __webpack_require__(20871); const os_1 = __webpack_require__(22037); const instruction_parser_1 = __webpack_require__(50387); const types_1 = __webpack_require__(13939); /** * Updates the image name of the last from stage, after resolving all aliases * @param contents Contents of the Dockerfile to update * @param newBaseImageName New base image name Dockerfile contents should be updated to */ function updateDockerfileBaseImageName(contents, newBaseImageName) { const dockerfile = dockerfile_ast_1.DockerfileParser.parse(contents); const result = (0, instruction_parser_1.getDockerfileBaseImageName)(dockerfile); if (result.error) { return { contents, error: { code: types_1.UpdateDockerfileBaseImageNameErrorCode.BASE_IMAGE_NAME_NOT_FOUND, }, }; } const currentBaseImageName = result.baseImage; const fromRanges = dockerfile .getFROMs() .filter((from) => from.getImage() === currentBaseImageName) .map((from) => from.getImageRange()); const argRanges = dockerfile .getARGs() .filter((arg) => { var _a; return ((_a = arg.getProperty()) === null || _a === void 0 ? void 0 : _a.getValue()) === currentBaseImageName; }) .map((arg) => { var _a; return (_a = arg.getProperty()) === null || _a === void 0 ? void 0 : _a.getValueRange(); }); const ranges = fromRanges.concat(argRanges); if (ranges.length === 0) { /** * This happens when the image is split over multiple FROM and ARG statements * making it difficult to update Dockerfiles that fall into these edge cases. * e.g.: * ARG REPO=repo * ARG TAG=tag * FROM ${REPO}:${TAG} */ return { contents, error: { code: types_1.UpdateDockerfileBaseImageNameErrorCode.BASE_IMAGE_NAME_FRAGMENTED, }, }; } const lines = contents.split(os_1.EOL); for (const range of ranges) { const lineNumber = range.start.line; const start = range.start.character; const end = range.end.character; const content = lines[lineNumber]; const updated = content.substring(0, start) + newBaseImageName + content.substring(end); lines[lineNumber] = updated; } const updatedContents = lines.join(os_1.EOL); const updatedDockerfile = dockerfile_ast_1.DockerfileParser.parse(updatedContents); if (dockerfile.getInstructions().length !== updatedDockerfile.getInstructions().length) { return { contents, error: { code: types_1.UpdateDockerfileBaseImageNameErrorCode.DOCKERFILE_GENERATION_FAILED, }, }; } return { contents: updatedContents, }; } exports.updateDockerfileBaseImageName = updateDockerfileBaseImageName; //# sourceMappingURL=instruction-updater.js.map /***/ }), /***/ 13939: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UpdateDockerfileBaseImageNameErrorCode = exports.DockerFileAnalysisErrorCode = void 0; var DockerFileAnalysisErrorCode; (function (DockerFileAnalysisErrorCode) { DockerFileAnalysisErrorCode["BASE_IMAGE_NAME_NOT_FOUND"] = "BASE_IMAGE_NAME_NOT_FOUND"; DockerFileAnalysisErrorCode["BASE_IMAGE_NON_RESOLVABLE"] = "BASE_IMAGE_NON_RESOLVABLE"; })(DockerFileAnalysisErrorCode = exports.DockerFileAnalysisErrorCode || (exports.DockerFileAnalysisErrorCode = {})); var UpdateDockerfileBaseImageNameErrorCode; (function (UpdateDockerfileBaseImageNameErrorCode) { UpdateDockerfileBaseImageNameErrorCode["BASE_IMAGE_NAME_FRAGMENTED"] = "BASE_IMAGE_NAME_FRAGMENTED"; UpdateDockerfileBaseImageNameErrorCode["BASE_IMAGE_NAME_NOT_FOUND"] = "BASE_IMAGE_NAME_NOT_FOUND"; UpdateDockerfileBaseImageNameErrorCode["DOCKERFILE_GENERATION_FAILED"] = "DOCKERFILE_GENERATION_FAILED"; })(UpdateDockerfileBaseImageNameErrorCode = exports.UpdateDockerfileBaseImageNameErrorCode || (exports.UpdateDockerfileBaseImageNameErrorCode = {})); //# sourceMappingURL=types.js.map /***/ }), /***/ 12518: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isResultEmpty = exports.applyCallbacks = void 0; const stream_1 = __webpack_require__(12781); const stream_utils_1 = __webpack_require__(54540); async function applyCallbacks(matchedActions, fileContentStream, streamSize) { const result = {}; const actionsToAwait = matchedActions.map((action) => { // Using a pass through allows us to read the stream multiple times. const streamCopy = new stream_1.PassThrough(); fileContentStream.pipe(streamCopy); // Queue the promise but don't await on it yet: we want consumers to start around the same time. const promise = action.callback !== undefined ? action.callback(streamCopy, streamSize) : // If no callback was provided for this action then return as string by default. (0, stream_utils_1.streamToString)(streamCopy); return promise.then((content) => { // Assign the result once the Promise is complete. if (content) { result[action.actionName] = content; } }); }); await Promise.all(actionsToAwait); return result; } exports.applyCallbacks = applyCallbacks; function isResultEmpty(result) { return Object.keys(result).length === 0; } exports.isResultEmpty = isResultEmpty; //# sourceMappingURL=callbacks.js.map /***/ }), /***/ 40637: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getImageIdFromManifest = exports.getManifestLayers = exports.extractArchive = void 0; const path_1 = __webpack_require__(71017); const types_1 = __webpack_require__(93677); var layer_1 = __webpack_require__(71544); Object.defineProperty(exports, "extractArchive", ({ enumerable: true, get: function () { return layer_1.extractArchive; } })); function getManifestLayers(manifest) { return manifest.Layers.map((layer) => (0, path_1.normalize)(layer)); } exports.getManifestLayers = getManifestLayers; function getImageIdFromManifest(manifest) { try { const imageId = manifest.Config.split(".")[0]; if (imageId.includes(":")) { // imageId includes the algorithm prefix return imageId; } return `${types_1.HashAlgorithm.Sha256}:${imageId}`; } catch (err) { throw new Error("Failed to extract image ID from archive manifest"); } } exports.getImageIdFromManifest = getImageIdFromManifest; //# sourceMappingURL=index.js.map /***/ }), /***/ 71544: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.extractArchive = void 0; const Debug = __webpack_require__(6807); const fs_1 = __webpack_require__(57147); const gunzip = __webpack_require__(65923); const path_1 = __webpack_require__(71017); const tar_stream_1 = __webpack_require__(53871); const __1 = __webpack_require__(18141); const stream_utils_1 = __webpack_require__(54540); const layer_1 = __webpack_require__(56423); const debug = Debug("snyk"); /** * Retrieve the products of files content from the specified docker-archive. * @param dockerArchiveFilesystemPath Path to image file saved in docker-archive format. * @param extractActions Array of pattern-callbacks pairs. * @param options PluginOptions * @returns Array of extracted files products sorted by the reverse order of the layers from last to first. */ async function extractArchive(dockerArchiveFilesystemPath, extractActions, _options) { return new Promise((resolve, reject) => { const tarExtractor = (0, tar_stream_1.extract)(); const layers = {}; let manifest; let imageConfig; tarExtractor.on("entry", async (header, stream, next) => { if (header.type === "file") { const normalizedName = (0, path_1.normalize)(header.name); if (isTarFile(normalizedName)) { try { layers[normalizedName] = await (0, layer_1.extractImageLayer)(stream, extractActions); } catch (error) { debug(`Error extracting layer content from: '${error.message}'`); reject(new Error("Error reading tar archive")); } } else if (isManifestFile(normalizedName)) { const manifestArray = await getManifestFile(stream); manifest = manifestArray[0]; } else if (isImageConfigFile(normalizedName)) { imageConfig = await getManifestFile(stream); } } stream.resume(); // auto drain the stream next(); // ready for next entry }); tarExtractor.on("finish", () => { try { resolve(getLayersContentAndArchiveManifest(manifest, imageConfig, layers)); } catch (error) { debug(`Error getting layers and manifest content from docker archive: ${error.message}`); reject(new __1.InvalidArchiveError("Invalid Docker archive")); } }); tarExtractor.on("error", (error) => reject(error)); (0, fs_1.createReadStream)(dockerArchiveFilesystemPath) .pipe(gunzip()) .pipe(tarExtractor); }); } exports.extractArchive = extractArchive; function getLayersContentAndArchiveManifest(manifest, imageConfig, layers) { // skip (ignore) non-existent layers // get the layers content without the name // reverse layers order from last to first const layersWithNormalizedNames = manifest.Layers.map((layersName) => (0, path_1.normalize)(layersName)); const filteredLayers = layersWithNormalizedNames .filter((layersName) => layers[layersName]) .map((layerName) => layers[layerName]) .reverse(); if (filteredLayers.length === 0) { throw new Error("We found no layers in the provided image"); } return { layers: filteredLayers, manifest, imageConfig, }; } /** * Note: consumes the stream. */ async function getManifestFile(stream) { return (0, stream_utils_1.streamToJson)(stream); } function isManifestFile(name) { return name === "manifest.json"; } function isImageConfigFile(name) { const configRegex = new RegExp("[A-Fa-f0-9]{64}\\.json"); return configRegex.test(name); } function isTarFile(name) { // For both "docker save" and "skopeo copy" style archives the // layers are represented as tar archives whose names end in .tar. // For Docker this is "layer.tar", for Skopeo - ".tar". return (0, path_1.basename)(name).endsWith(".tar"); } //# sourceMappingURL=layer.js.map /***/ }), /***/ 92748: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getImageNames = exports.ImageDigest = exports.ImageName = void 0; class ImageName { constructor(targetImage, digests = {}) { // this regex has been copied from // https://github.com/distribution/distribution/blob/fb2188868d771aa27e5781a32bf78d4c113c18a6/reference/regexp.go#L101 // (code has been modified to print the regex), and then adjusted to // Javascript. The required modifications were replacing `[:xdigit:]` with // `[a-fA-F0-9]` and escaping the slashes. // Note that the digest matched in this Regex will match digests that have // uppercase-letters, while the regex used in validateDigest does NOT match // uppercase-letters. This simply matches the behaviour from the upstream // `reference` and `go-digest `packages. // // we're matching pattern: (optional)/(mandatory):(optional)@(optional) // This Regex contains three capture groups: // 1) The repository / image name // 2) tag // 3) digest const re = /^((?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])(?:(?:\.(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]))+)?(?::[0-9]+)?\/)?[a-z0-9]+(?:(?:(?:[._]|__|[-]*)[a-z0-9]+)+)?(?:(?:\/[a-z0-9]+(?:(?:(?:[._]|__|[-]*)[a-z0-9]+)+)?)+)?)(?::([\w][\w.-]{0,127}))?(?:@([A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*[:][A-Fa-f0-9]{32,}))?$/gi; const groups = re.exec(targetImage); if (groups === null) { if (targetImage === "") { throw new Error("image name is empty"); } if (re.exec(targetImage.toLowerCase()) !== null) { throw new Error("image repository contains uppercase letter"); } throw new Error("invalid image reference format"); } const parsedGroups = { name: groups[1], tag: groups[2], digest: groups[3], }; this.name = parsedGroups.name; const NameTotalLengthMax = 255; if (this.name.length > NameTotalLengthMax) { throw new Error("image repository name is more than 255 characters"); } this.tag = parsedGroups.tag || parsedGroups.digest ? parsedGroups.tag : "latest"; this.digests = {}; if (digests.index) { this.digests.index = new ImageDigest(digests.index); } if (digests.manifest) { this.digests.manifest = new ImageDigest(digests.manifest); } if (parsedGroups.digest) { const digest = new ImageDigest(parsedGroups.digest); if (this.digests.manifest !== digest && this.digests.index !== digest) { this.digests.unknown = digest; } } } getAllNames() { const names = []; if (this.tag) { names.push(this.name + ":" + this.tag); } if (this.digests.manifest) { names.push(this.name + "@" + this.digests.manifest.toString()); } if (this.digests.index) { names.push(this.name + "@" + this.digests.index.toString()); } if (this.digests.unknown) { names.push(this.name + "@" + this.digests.unknown.toString()); } return names; } } exports.ImageName = ImageName; const ALGORITHM = { sha256: 64, sha384: 96, sha512: 128, }; class ImageDigest { constructor(digest) { // this function matches the implementation // https://github.com/opencontainers/go-digest/blob/b0b31a459546bae38a6c9676e9c5f35861e58894/digest.go#L103 const i = digest.indexOf(":"); if (i <= 0 || i + 1 === digest.length) { throw new Error("invalid digest format"); } const alg = digest.slice(0, i); this.hex = digest.slice(i + 1); // make sure the algorithm is valid, and that we get the same // amount of hex characters as we expect for the given algorithm. this.alg = alg; if (this.alg === undefined || !Object.keys(ALGORITHM).includes(this.alg)) { throw new Error(`unsupported digest algorithm: ${alg}`); } if (this.hex.length !== ALGORITHM[this.alg]) { throw new Error(`digest algorithm ${this.alg} suggested length ${ALGORITHM[this.alg]}, but got digest with length ${this.hex.length}`); } if (!new RegExp(`^[a-f0-9]{${ALGORITHM[this.alg]}}`).test(this.hex)) { throw new Error(`digest contains invalid characters`); } } toString() { return this.alg + ":" + this.hex; } } exports.ImageDigest = ImageDigest; function getImageNames(options, imageName) { if (imageName) { return imageName.getAllNames(); } const names = []; if (options === null || options === void 0 ? void 0 : options.imageNameAndTag) { const imageName = new ImageName(options.imageNameAndTag); names.push(...imageName.getAllNames()); } if ((options === null || options === void 0 ? void 0 : options.imageNameAndDigest) && (options === null || options === void 0 ? void 0 : options.imageNameAndDigest) !== (options === null || options === void 0 ? void 0 : options.imageNameAndTag)) { const imageName = new ImageName(options.imageNameAndDigest); names.push(...imageName.getAllNames()); } return names; } exports.getImageNames = getImageNames; //# sourceMappingURL=image.js.map /***/ }), /***/ 18141: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getContentAsString = exports.getContentAsBuffer = exports.isWhitedOutFile = exports.getUserInstructionLayersFromConfig = exports.getDetectedLayersInfoFromConfig = exports.getPlatformFromConfig = exports.getRootFsLayersFromConfig = exports.extractImageContent = exports.InvalidArchiveError = void 0; const path = __webpack_require__(71017); const instruction_parser_1 = __webpack_require__(50387); const types_1 = __webpack_require__(93677); const dockerExtractor = __webpack_require__(40637); const kanikoExtractor = __webpack_require__(40635); const ociExtractor = __webpack_require__(27044); class InvalidArchiveError extends Error { constructor(message) { super(); this.name = "InvalidArchiveError"; this.message = message; } } exports.InvalidArchiveError = InvalidArchiveError; class ArchiveExtractor { constructor(extractor, path, actions, options) { this.fileSystemPath = path; this.extractActions = actions; this.extractor = extractor; this.options = options; } getExtractor() { return this.extractor; } async getLayersAndManifest() { return await this.extractor.extractArchive(this.fileSystemPath, this.extractActions, this.options); } getImageIdFromManifest(manifest) { return this.extractor.getImageIdFromManifest(manifest); } getManifestLayers(manifest) { return this.extractor.getManifestLayers(manifest); } } /** * Given a path on the file system to a image archive, open it up to inspect the layers * and look for specific files. File content can be transformed with a custom callback function if needed. * @param fileSystemPath Path to an existing archive. * @param extractActions This denotes a file pattern to look for and how to transform the file if it is found. * By default the file is returned raw if no processing is desired. */ async function extractImageContent(imageType, fileSystemPath, extractActions, options) { const extractors = new Map([ [ types_1.ImageType.DockerArchive, new ArchiveExtractor(dockerExtractor, fileSystemPath, extractActions, options), ], [ types_1.ImageType.OciArchive, new ArchiveExtractor(ociExtractor, fileSystemPath, extractActions, options), ], [ types_1.ImageType.KanikoArchive, new ArchiveExtractor(kanikoExtractor, fileSystemPath, extractActions, options), ], ]); let extractor; let archiveContent; if (!extractors.has(imageType)) { // default to Docker extractor if image type is unknown imageType = types_1.ImageType.DockerArchive; } extractor = extractors.get(imageType); try { archiveContent = await extractor.getLayersAndManifest(); } catch (err) { if (err instanceof InvalidArchiveError) { // fallback to the other extractor if layer extraction failed [archiveContent, extractor] = await extractArchiveContentFallback(extractors); } else { throw err; } } return { imageId: extractor.getImageIdFromManifest(archiveContent.manifest), manifestLayers: extractor.getManifestLayers(archiveContent.manifest), imageCreationTime: archiveContent.imageConfig.created, extractedLayers: layersWithLatestFileModifications(archiveContent.layers), rootFsLayers: getRootFsLayersFromConfig(archiveContent.imageConfig), autoDetectedUserInstructions: getDetectedLayersInfoFromConfig(archiveContent.imageConfig), platform: getPlatformFromConfig(archiveContent.imageConfig), imageLabels: archiveContent.imageConfig.config.Labels, }; } exports.extractImageContent = extractImageContent; async function extractArchiveContentFallback(extractors) { for (const extractor of extractors.values()) { try { return [await extractor.getLayersAndManifest(), extractor]; } catch (error) { continue; } } throw new InvalidArchiveError(`Unsupported archive type. Please use a Docker archive, OCI image layout, or Kaniko-compatible tarball.`); } function getRootFsLayersFromConfig(imageConfig) { try { return imageConfig.rootfs.diff_ids; } catch (err) { throw new Error("Failed to extract rootfs array from image config"); } } exports.getRootFsLayersFromConfig = getRootFsLayersFromConfig; function getPlatformFromConfig(imageConfig) { return (imageConfig === null || imageConfig === void 0 ? void 0 : imageConfig.os) && (imageConfig === null || imageConfig === void 0 ? void 0 : imageConfig.architecture) ? `${imageConfig.os}/${imageConfig.architecture}` : undefined; } exports.getPlatformFromConfig = getPlatformFromConfig; function getDetectedLayersInfoFromConfig(imageConfig) { const runInstructions = getUserInstructionLayersFromConfig(imageConfig) .filter((instruction) => !instruction.empty_layer && instruction.created_by) .map((instruction) => instruction.created_by.replace("# buildkit", "")); const dockerfilePackages = (0, instruction_parser_1.getPackagesFromRunInstructions)(runInstructions); const dockerfileLayers = (0, instruction_parser_1.getLayersFromPackages)(dockerfilePackages); return { dockerfilePackages, dockerfileLayers }; } exports.getDetectedLayersInfoFromConfig = getDetectedLayersInfoFromConfig; function getUserInstructionLayersFromConfig(imageConfig) { const diffInHours = (d1, d2) => Math.abs(d1 - d2) / 1000 / (60 * 60); const maxDiffInHours = 5; const history = imageConfig.history; if (!history) { return []; } const lastInstructionTime = new Date(history.slice(-1)[0].created); const userInstructionLayers = history.filter((layer) => { return (diffInHours(new Date(layer.created), lastInstructionTime) <= maxDiffInHours); }); // should only happen if there are no layers created by user instructions if (userInstructionLayers.length === history.length) { return []; } return userInstructionLayers; } exports.getUserInstructionLayersFromConfig = getUserInstructionLayersFromConfig; function layersWithLatestFileModifications(layers) { const extractedLayers = {}; const removedFilesToIgnore = new Set(); // TODO: This removes the information about the layer name, maybe we would need it in the future? for (const layer of layers) { // go over extracted files products found in this layer for (const filename of Object.keys(layer)) { // if finding a deleted file - trimming to its original file name for excluding it from extractedLayers // + not adding this file if (isWhitedOutFile(filename)) { removedFilesToIgnore.add(filename.replace(/.wh./, "")); continue; } // not adding previously found to be whited out files to extractedLayers if (removedFilesToIgnore.has(filename)) { continue; } // not adding path that has removed path as parent if (isFileInARemovedFolder(filename, removedFilesToIgnore)) { continue; } // file not already in extractedLayers if (!Reflect.has(extractedLayers, filename)) { extractedLayers[filename] = layer[filename]; } } } return extractedLayers; } function isWhitedOutFile(filename) { return filename.match(/.wh./gm); } exports.isWhitedOutFile = isWhitedOutFile; function isBufferType(type) { return type.buffer !== undefined; } function isStringType(type) { return type.substring !== undefined; } function getContentAsBuffer(extractedLayers, extractAction) { const content = getContent(extractedLayers, extractAction); return content !== undefined && isBufferType(content) ? content : undefined; } exports.getContentAsBuffer = getContentAsBuffer; function getContentAsString(extractedLayers, extractAction) { const content = getContent(extractedLayers, extractAction); return content !== undefined && isStringType(content) ? content : undefined; } exports.getContentAsString = getContentAsString; function getContent(extractedLayers, extractAction) { const fileNames = Object.keys(extractedLayers); const fileNamesProducedByTheExtractAction = fileNames.filter((name) => extractAction.actionName in extractedLayers[name]); const firstFileNameMatch = fileNamesProducedByTheExtractAction.find((match) => extractAction.filePathMatches(match)); return firstFileNameMatch !== undefined ? extractedLayers[firstFileNameMatch][extractAction.actionName] : undefined; } function isFileInFolder(file, folder) { const folderPath = path.normalize(folder); const filePath = path.normalize(file); return filePath.startsWith(path.join(folderPath, path.sep)); } function isFileInARemovedFolder(filename, removedFilesToIgnore) { return Array.from(removedFilesToIgnore).some((removedFile) => isFileInFolder(filename, removedFile)); } //# sourceMappingURL=index.js.map /***/ }), /***/ 40635: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getImageIdFromManifest = exports.getManifestLayers = exports.extractArchive = void 0; const path_1 = __webpack_require__(71017); const types_1 = __webpack_require__(93677); var layer_1 = __webpack_require__(188); Object.defineProperty(exports, "extractArchive", ({ enumerable: true, get: function () { return layer_1.extractArchive; } })); function getManifestLayers(manifest) { return manifest.Layers.map((layer) => (0, path_1.normalize)(layer)); } exports.getManifestLayers = getManifestLayers; function getImageIdFromManifest(manifest) { try { const imageId = manifest.Config; if (imageId.includes(":")) { // imageId includes the algorithm prefix return imageId; } return `${types_1.HashAlgorithm.Sha256}:${imageId}`; } catch (err) { throw new Error("Failed to extract image ID from archive manifest"); } } exports.getImageIdFromManifest = getImageIdFromManifest; //# sourceMappingURL=index.js.map /***/ }), /***/ 188: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.extractArchive = void 0; const Debug = __webpack_require__(6807); const fs_1 = __webpack_require__(57147); const gunzip = __webpack_require__(65923); const path_1 = __webpack_require__(71017); const tar_stream_1 = __webpack_require__(53871); const __1 = __webpack_require__(18141); const stream_utils_1 = __webpack_require__(54540); const layer_1 = __webpack_require__(56423); const debug = Debug("snyk"); /** * Retrieve the products of files content from the specified kaniko-archive. * @param kanikoArchiveFilesystemPath Path to image file saved in kaniko-archive format. * @param extractActions Array of pattern-callbacks pairs. * @param options PluginOptions * @returns Array of extracted files products sorted by the reverse order of the layers from last to first. */ async function extractArchive(kanikoArchiveFilesystemPath, extractActions, _options) { return new Promise((resolve, reject) => { const tarExtractor = (0, tar_stream_1.extract)(); const layers = {}; let manifest; let imageConfig; tarExtractor.on("entry", async (header, stream, next) => { if (header.type === "file") { const normalizedName = (0, path_1.normalize)(header.name); if (isTarGzFile(normalizedName)) { try { layers[normalizedName] = await (0, layer_1.extractImageLayer)(stream, extractActions); } catch (error) { debug(`Error extracting layer content from: '${error.message}'`); reject(new Error("Error reading tar.gz archive")); } } else if (isManifestFile(normalizedName)) { const manifestArray = await getManifestFile(stream); manifest = manifestArray[0]; } else if (isImageConfigFile(normalizedName)) { imageConfig = await getManifestFile(stream); } } stream.resume(); // auto drain the stream next(); // ready for next entry }); tarExtractor.on("finish", () => { try { resolve(getLayersContentAndArchiveManifest(manifest, imageConfig, layers)); } catch (error) { debug(`Error getting layers and manifest content from Kaniko archive: ${error.message}`); reject(new __1.InvalidArchiveError("Invalid Kaniko archive")); } }); tarExtractor.on("error", (error) => reject(error)); (0, fs_1.createReadStream)(kanikoArchiveFilesystemPath) .pipe(gunzip()) .pipe(tarExtractor); }); } exports.extractArchive = extractArchive; function getLayersContentAndArchiveManifest(manifest, imageConfig, layers) { // skip (ignore) non-existent layers // get the layers content without the name // reverse layers order from last to first const layersWithNormalizedNames = manifest.Layers.map((layersName) => (0, path_1.normalize)(layersName)); const filteredLayers = layersWithNormalizedNames .filter((layersName) => layers[layersName]) .map((layerName) => layers[layerName]) .reverse(); if (filteredLayers.length === 0) { throw new Error("We found no layers in the provided image"); } return { layers: filteredLayers, manifest, imageConfig, }; } /** * Note: consumes the stream. */ async function getManifestFile(stream) { return (0, stream_utils_1.streamToJson)(stream); } function isManifestFile(name) { return name === "manifest.json"; } function isImageConfigFile(name) { const configRegex = new RegExp("sha256:[A-Fa-f0-9]{64}"); return configRegex.test(name); } function isTarGzFile(name) { return (0, path_1.basename)(name).endsWith(".tar.gz"); } //# sourceMappingURL=layer.js.map /***/ }), /***/ 56423: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.extractImageLayer = void 0; const Debug = __webpack_require__(6807); const gunzip = __webpack_require__(65923); const path = __webpack_require__(71017); const tar_stream_1 = __webpack_require__(53871); const _1 = __webpack_require__(18141); const callbacks_1 = __webpack_require__(12518); const debug = Debug("snyk"); /** * Extract key files from the specified TAR stream. * @param layerTarStream image layer as a Readable TAR stream. Note: consumes the stream. * @param extractActions array of pattern, callbacks pairs * @returns extracted file products */ async function extractImageLayer(layerTarStream, extractActions) { return new Promise((resolve, reject) => { const result = {}; const tarExtractor = (0, tar_stream_1.extract)(); tarExtractor.on("entry", async (headers, stream, next) => { if (headers.type === "file") { const absoluteFileName = path.join(path.sep, headers.name); const matchedActions = extractActions.filter((action) => action.filePathMatches(absoluteFileName)); if (matchedActions.length > 0) { try { const callbackResult = await (0, callbacks_1.applyCallbacks)(matchedActions, stream, headers.size); if (!(0, callbacks_1.isResultEmpty)(callbackResult) || (0, _1.isWhitedOutFile)(absoluteFileName)) { result[absoluteFileName] = callbackResult; } } catch (error) { // An ExtractAction has thrown an uncaught exception, likely a bug in the code! debug(`Exception thrown while applying callbacks during image layer extraction: ${error.message}`); reject(error); } } else if ((0, _1.isWhitedOutFile)(absoluteFileName)) { result[absoluteFileName] = {}; } } stream.resume(); // auto drain the stream next(); // ready for next entry }); tarExtractor.on("finish", () => { // all layer level entries read resolve(result); }); tarExtractor.on("error", (error) => reject(error)); layerTarStream.pipe(gunzip()).pipe(tarExtractor); }); } exports.extractImageLayer = extractImageLayer; //# sourceMappingURL=layer.js.map /***/ }), /***/ 27044: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getImageIdFromManifest = exports.getManifestLayers = exports.extractArchive = void 0; var layer_1 = __webpack_require__(29633); Object.defineProperty(exports, "extractArchive", ({ enumerable: true, get: function () { return layer_1.extractArchive; } })); function getManifestLayers(manifest) { return manifest.layers.map((layer) => layer.digest); } exports.getManifestLayers = getManifestLayers; function getImageIdFromManifest(manifest) { try { return manifest.config.digest; } catch (err) { throw new Error("Failed to extract image ID from archive manifest"); } } exports.getImageIdFromManifest = getImageIdFromManifest; //# sourceMappingURL=index.js.map /***/ }), /***/ 29633: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.extractArchive = void 0; const Debug = __webpack_require__(6807); const fs_1 = __webpack_require__(57147); const gunzip = __webpack_require__(65923); const path_1 = __webpack_require__(71017); const stream_1 = __webpack_require__(12781); const tar_stream_1 = __webpack_require__(53871); const __1 = __webpack_require__(18141); const stream_utils_1 = __webpack_require__(54540); const layer_1 = __webpack_require__(56423); const debug = Debug("snyk"); const MEDIATYPE_DOCKER_MANIFEST_V2 = "application/vnd.docker.distribution.manifest.v2+json"; const MEDIATYPE_DOCKER_MANIFEST_LIST_V2 = "application/vnd.docker.distribution.manifest.list.v2+json"; const MEDIATYPE_OCI_MANIFEST_V1 = "application/vnd.oci.image.manifest.v1+json"; const MEDIATYPE_OCI_MANIFEST_LIST_V1 = "application/vnd.oci.image.index.v1+json"; /** * Retrieve the products of files content from the specified oci-archive. * @param ociArchiveFilesystemPath Path to image file saved in oci-archive format. * @param extractActions Array of pattern-callbacks pairs. * @param options PluginOptions * @returns Array of extracted files products sorted by the reverse order of the layers from last to first. */ async function extractArchive(ociArchiveFilesystemPath, extractActions, options) { return new Promise((resolve, reject) => { const tarExtractor = (0, tar_stream_1.extract)(); const layers = {}; const manifests = {}; const configs = []; let mainIndexFile; const indexFiles = {}; tarExtractor.on("entry", async (header, stream, next) => { if (header.type === "file") { const normalizedHeaderName = (0, path_1.normalize)(header.name); if (isMainIndexFile(normalizedHeaderName)) { mainIndexFile = await (0, stream_utils_1.streamToJson)(stream); } else { const jsonStream = new stream_1.PassThrough(); const layerStream = new stream_1.PassThrough(); stream.pipe(jsonStream); stream.pipe(layerStream); const promises = [ (0, stream_utils_1.streamToJson)(jsonStream).catch(() => undefined), (0, layer_1.extractImageLayer)(layerStream, extractActions).catch(() => undefined), ]; const [manifest, layer] = await Promise.all(promises); // header format is /blobs/hash_name/hash_value // we're extracting hash_name:hash_value format to match manifest digest const headerParts = normalizedHeaderName.split(path_1.sep); const hashName = headerParts[1]; const hashValue = headerParts[headerParts.length - 1]; const digest = `${hashName}:${hashValue}`; if (isArchiveManifest(manifest)) { manifests[digest] = manifest; } else if (isImageIndexFile(manifest)) { indexFiles[digest] = manifest; } else if (isImageConfigFile(manifest)) { configs.push(manifest); } if (layer !== undefined) { layers[digest] = layer; } } } stream.resume(); // auto drain the stream next(); // ready for next entry }); tarExtractor.on("finish", () => { try { resolve(getLayersContentAndArchiveManifest(mainIndexFile, manifests, indexFiles, configs, layers, options)); } catch (error) { debug(`Error getting layers and manifest content from oci archive: '${error.message}'`); reject(new __1.InvalidArchiveError("Invalid OCI archive")); } }); tarExtractor.on("error", (error) => { reject(error); }); (0, fs_1.createReadStream)(ociArchiveFilesystemPath) .pipe(gunzip()) .pipe(tarExtractor); }); } exports.extractArchive = extractArchive; function getLayersContentAndArchiveManifest(imageIndex, manifestCollection, indexFiles, configs, layers, options) { const platform = (options === null || options === void 0 ? void 0 : options.platform) || (configs.length === 1 ? (0, __1.getPlatformFromConfig)(configs[0]) : "linux/amd64"); const platformInfo = getOciPlatformInfoFromOptionString(platform); // get manifest file first const manifest = getManifest(imageIndex, manifestCollection, indexFiles, platformInfo); // filter empty layers // get the layers content without the name // reverse layers order from last to first const filteredLayers = manifest.layers .filter((layer) => layers[layer.digest]) .map((layer) => layers[layer.digest]) .reverse(); if (filteredLayers.length === 0) { throw new Error("We found no layers in the provided image"); } const imageConfig = getImageConfig(configs, platformInfo); if (imageConfig === undefined) { throw new Error("Could not find the image config in the provided image"); } return { layers: filteredLayers, manifest, imageConfig, }; } function getManifest(imageIndex, manifestCollection, indexFiles, platformInfo) { if (!imageIndex) { return manifestCollection[Object.keys(manifestCollection)[0]]; } const allManifests = getAllManifestsIndexItems(imageIndex, indexFiles); const manifestInfo = getImageManifestInfo(allManifests, platformInfo); if (manifestInfo === undefined) { throw new Error("Image does not support type of CPU architecture or operating system"); } return manifestCollection[manifestInfo.digest]; } function getAllManifestsIndexItems(imageIndex, indexFiles) { const allManifestsInfo = []; for (const manifest of imageIndex.manifests) { if (manifest.mediaType === MEDIATYPE_OCI_MANIFEST_V1 || manifest.mediaType === MEDIATYPE_DOCKER_MANIFEST_V2) { // an archive manifest file allManifestsInfo.push(manifest); } else if (manifest.mediaType === MEDIATYPE_OCI_MANIFEST_LIST_V1 || manifest.mediaType === MEDIATYPE_DOCKER_MANIFEST_LIST_V2) { // nested index const index = indexFiles[manifest.digest]; allManifestsInfo.push(...getAllManifestsIndexItems(index, indexFiles)); } } return allManifestsInfo; } function isArchiveManifest(manifest) { return (manifest !== undefined && manifest.layers && Array.isArray(manifest.layers)); } function isImageConfigFile(json) { return json !== undefined && json.architecture && json.rootfs; } function isImageIndexFile(json) { return (((json === null || json === void 0 ? void 0 : json.mediaType) === MEDIATYPE_OCI_MANIFEST_LIST_V1 || (json === null || json === void 0 ? void 0 : json.mediaType) === MEDIATYPE_DOCKER_MANIFEST_LIST_V2) && Array.isArray(json === null || json === void 0 ? void 0 : json.manifests)); } function isMainIndexFile(name) { return name === "index.json"; } function getOciPlatformInfoFromOptionString(platform) { const [os, architecture, variant] = platform.split("/"); return { os, architecture, variant, }; } function getImageManifestInfo(manifests, platformInfo) { // manifests do not always have a plaform, this is the case for OCI // images built with Docker when no platform is specified if (manifests.length === 1 && !manifests[0].platform) { return manifests[0]; } return getBestMatchForPlatform(manifests, platformInfo, (target) => { var _a, _b, _c; return { os: (_a = target.platform) === null || _a === void 0 ? void 0 : _a.os, architecture: (_b = target.platform) === null || _b === void 0 ? void 0 : _b.architecture, variant: (_c = target.platform) === null || _c === void 0 ? void 0 : _c.variant, }; }); } function getImageConfig(manifests, platformInfo) { return getBestMatchForPlatform(manifests, platformInfo, (target) => { return { os: target.os, architecture: target.architecture, }; }); } function getBestMatchForPlatform(manifests, platformInfo, extractPlatformInfoFromManifest) { const matches = manifests.filter((item) => { const { os, architecture } = extractPlatformInfoFromManifest(item); return os === platformInfo.os && architecture === platformInfo.architecture; }); if (matches.length > 1) { return matches.find((item) => { const { variant } = extractPlatformInfoFromManifest(item); return variant === platformInfo.variant; }); } return matches[0] || undefined; } //# sourceMappingURL=layer.js.map /***/ }), /***/ 19103: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.constructOCIDisributionMetadata = void 0; const docker_reference_1 = __webpack_require__(3687); function constructOCIDisributionMetadata({ imageName, manifestDigest, indexDigest, }) { try { const ref = (0, docker_reference_1.parseAll)(imageName); if (!ref.domain || !ref.repository) { return; } const metadata = { registryHost: ref.domain, repository: ref.repository, manifestDigest, indexDigest, imageTag: ref.tag, }; if (!ociDistributionMetadataIsValid(metadata)) { return; } return metadata; } catch (_a) { return; } } exports.constructOCIDisributionMetadata = constructOCIDisributionMetadata; function ociDistributionMetadataIsValid(data) { // 255 byte limit is enforced by RFC 1035. if (Buffer.byteLength(data.registryHost) > 255) { return false; } // 2048 byte limit is enforced by Snyk for platform stability. // Longer strings may be valid, but nothing close to this limit has been observed by Snyk at time of writing. if (Buffer.byteLength(data.repository) > 2048 || !repositoryNameIsValid(data.repository)) { return false; } if (!digestIsValid(data.manifestDigest)) { return false; } if (data.indexDigest && !digestIsValid(data.indexDigest)) { return false; } if (data.imageTag && !tagIsValid(data.imageTag)) { return false; } return true; } // Regular Expression Source: OCI Distribution Spec V1 // https://github.com/opencontainers/distribution-spec/blob/570d0262abe8ec5e59d8e3fbbd7be4bd784b200e/spec.md?plain=1#L141 const repositoryNameIsValid = (name) => /^[a-z0-9]+((\.|_|__|-+)[a-z0-9]+)*(\/[a-z0-9]+((\.|_|__|-+)[a-z0-9]+)*)*$/.test(name); // Regular Expression Source: OCI Image Spec V1 // https://github.com/opencontainers/image-spec/blob/d60099175f88c47cd379c4738d158884749ed235/descriptor.md?plain=1#L143 const digestIsValid = (digest) => /^sha256:[a-f0-9]{64}$/.test(digest); // Regular Expression Source: OCI Image Spec V1 // https://github.com/opencontainers/distribution-spec/blob/3940529fe6c0a068290b27fb3cd797cf0528bed6/spec.md?plain=1#L160 const tagIsValid = (tag) => /^[a-zA-Z0-9_][a-zA-Z0-9._-]{0,127}$/.test(tag); //# sourceMappingURL=oci-distribution-metadata.js.map /***/ }), /***/ 86666: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); //# sourceMappingURL=facts.js.map /***/ }), /***/ 6803: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.determinePaths = exports.readRawBuildInfo = exports.extractModuleInformation = exports.GoBinary = void 0; const depGraph = __webpack_require__(71479); const event_loop_spinner_1 = __webpack_require__(77158); // NOTE: Paths will always be normalized to POSIX even on Windows. // This makes it easier to ignore differences between Linux and Windows. const path_1 = __webpack_require__(71017); const varint = __webpack_require__(94676); const _1 = __webpack_require__(5998); const go_module_1 = __webpack_require__(79160); const pclntab_1 = __webpack_require__(77162); class GoBinary { constructor(goElfBinary) { [this.name, this.modules] = extractModuleInformation(goElfBinary); const pclnTab = goElfBinary.body.sections.find((section) => section.name === ".gopclntab"); // some CGo built binaries might not contain a pclnTab, which means we // cannot scan the files. // TODO: from a technical perspective, it would be enough to only report the // modules, as the only remediation path is to upgrade a full module // anyways. From a product perspective, it's not clear (yet). if (pclnTab === undefined) { throw Error("no pcln table present in Go binary"); } this.matchFilesToModules(new pclntab_1.LineTable(pclnTab.data).go12MapFiles()); } async depGraph() { const goModulesDepGraph = new depGraph.DepGraphBuilder({ name: _1.DEP_GRAPH_TYPE }, { name: this.name }); for (const module of this.modules) { for (const pkg of module.packages) { if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } const nodeId = `${pkg}@${module.version}`; goModulesDepGraph.addPkgNode({ name: pkg, version: module.version }, nodeId); goModulesDepGraph.connectDep(goModulesDepGraph.rootNodeId, nodeId); } } return goModulesDepGraph.build(); } // matchFilesToModules goes through all files, extracts the package name and // adds it to the relevant module in the GoBinary. matchFilesToModules(files) { const normalizedFiles = files.map((file) => path_1.posix.normalize(file)); const { modCachePath, vendorPath } = determinePaths(this.modules, normalizedFiles); for (const fileName of normalizedFiles) { if (fileName === "") { continue; } let moduleName = (mod) => mod.fullName(); let pkgFile = ""; if (vendorPath && fileName.startsWith(vendorPath)) { moduleName = (mod) => mod.name; pkgFile = trimPrefix(fileName, vendorPath); } else if (modCachePath && fileName.startsWith(modCachePath)) { moduleName = (mod) => mod.fullName(); pkgFile = trimPrefix(fileName, modCachePath); } else if (!vendorPath && !modCachePath) { // is trimmed pkgFile = fileName; } else { // skip file, probably a file from the Go source. continue; } // Try to find the module that matches our file name, and if found, // extract the package name out of it. // Go source files will not be matched by any module, so they will be // skipped automatically. for (const module of this.modules) { const modFullName = moduleName(module); if (pkgFile.startsWith(modFullName)) { // For example, the filename "github.com/my/pkg@v0.0.1/a/a.go" will be // split into "github.com/my/pkg@v0.0.1/" and "a/a.go". We then get // the package name from the package and file section, and add the // normalized module name (without the version) in front. This will // result in the package name "github.com/my/pkg/a". const parts = pkgFile.split(modFullName); if (parts.length !== 2 || parts[0] !== "") { throw { fileName: pkgFile, moduleName: modFullName, }; } // for files in the "root" of a module // (github.com/my/pkg@v0.0.1/a.go), the path.parse expression returns // just a slash. This would result in a package name with a trailing // slash, which is incorrect. let dirName = path_1.posix.parse(parts[1]).dir; if (dirName === path_1.posix.sep) { dirName = ""; } const pkgName = module.name + dirName; if (!module.packages.includes(pkgName)) { module.packages.push(pkgName); } } } } } } exports.GoBinary = GoBinary; function extractModuleInformation(binary) { const mod = readRawBuildInfo(binary); if (!mod) { throw Error("binary contains empty module info"); } const [pathDirective, mainModuleLine, ...versionsLines] = mod .replace("\r", "") .split("\n"); const lineSplit = mainModuleLine.split("\t"); let name = lineSplit[1]; if (lineSplit[0] !== "mod") { // If the binary has no mod directive, it is a binary from the Go // distribution, like the "go" command, "vet", "gofmt" or others. In that // case, we use "go-distribution@" plus the path directive ("cmd/vet" for // example) as the name. Using the "@" ensures that customers cannot create // name-clashes with these as "@" is an invalid character in Go modules. name = "go-distribution@" + pathDirective.split("\t")[1]; } const modules = []; versionsLines.forEach((versionLine) => { const [depType, name, ver] = versionLine.split("\t"); if (!name || !ver) { return; } if (depType === "dep") { modules.push(new go_module_1.GoModule(name, ver)); } else if (depType === "=>") { // we've found a replace directive. These are always for the previous // line/ module, so we simply need to replace the last module we added. const last = modules.length - 1; modules[last].name = name; modules[last].version = ver; } }); return [name, modules]; } exports.extractModuleInformation = extractModuleInformation; // Source // https://cs.opensource.google/go/go/+/refs/tags/go1.18.5:src/debug/buildinfo/buildinfo.go;l=142 /** * Function finds and returns the Go version and * module version information in the executable binary * @param binary */ function readRawBuildInfo(binary) { const buildInfoMagic = "\xff Go buildinf:"; // Read the first 64kB of dataAddr to find the build info blob. // On some platforms, the blob will be in its own section, and DataStart // returns the address of that section. On others, it's somewhere in the // data segment; the linker puts it near the beginning. const dataAddr = dataStart(binary); let data = readData(binary.body.programs, dataAddr, 64 * 1024) || Buffer.from([]); const buildInfoAlign = 16; const buildInfoSize = 32; while (true) { const i = data.toString("binary").indexOf(buildInfoMagic); if (i < 0 || data.length - i < buildInfoSize) { throw Error("not a Go executable"); } if (i % buildInfoAlign === 0 && data.length - i >= buildInfoSize) { data = data.subarray(i); break; } data = data.subarray((i + buildInfoAlign - 1) & ~buildInfoAlign); } // Decode the blob. // The first 14 bytes are buildInfoMagic. // The next two bytes indicate pointer size in bytes (4 or 8) and endianness // (0 for little, 1 for big). // Two virtual addresses to Go strings follow that: runtime.buildVersion, // and runtime.modinfo. // On 32-bit platforms, the last 8 bytes are unused. // If the endianness has the 2 bit set, then the pointers are zero // and the 32-byte header is followed by varint-prefixed string data // for the two string values we care about. const ptrSize = data[14]; if ((data[15] & 2) !== 0) { data = data.subarray(32); [, data] = decodeString(data); const [mod] = decodeString(data); return mod; } else { const bigEndian = data[15] !== 0; let readPtr; if (ptrSize === 4) { if (bigEndian) { readPtr = (buffer) => buffer.readUInt32BE(0); } else { readPtr = (buffer) => buffer.readUInt32LE(0); } } else { if (bigEndian) { readPtr = (buffer) => Number(buffer.readBigUInt64BE()); } else { readPtr = (buffer) => Number(buffer.readBigUInt64LE()); } } // The build info blob left by the linker is identified by // a 16-byte header, consisting of buildInfoMagic (14 bytes), // the binary's pointer size (1 byte), // and whether the binary is big endian (1 byte). // Now we attempt to read info after metadata. // From 16th byte to 16th + ptrSize there is a header that points // to go version const version = readString(binary, ptrSize, readPtr, readPtr(data.slice(16, 16 + ptrSize))); if (version === "") { throw Error("no version found in go binary"); } // Go version header was right after metadata. // Modules header right after go version // Read next `ptrSize` bytes, this point to the // place where modules info is stored const mod = readString(binary, ptrSize, readPtr, readPtr(data.slice(16 + ptrSize, 16 + 2 * ptrSize))); // This verifies that what we got are actually go modules // First 16 bytes are unicodes as last 16 // Mirrors go version source code if (mod.length >= 33 && mod[mod.length - 17] === "\n") { return mod.slice(16, mod.length - 16); } else { throw Error("binary is not built with go module support"); } } } exports.readRawBuildInfo = readRawBuildInfo; function decodeString(data) { const num = varint.decode(data); const size = varint.decode.bytes; if (size <= 0 || num >= data.length - size) { return ["", Buffer.from([])]; } const res = data.subarray(size, num + size); const rest = data.subarray(num + size); return [res.toString("binary"), rest]; } // Source // https://github.com/golang/go/blob/46f99ce7ea97d11b0a1a079da8dda0f51df2a2d2/src/cmd/go/internal/version/exe.go#L105 /** * Find start of section that contains module version data * @param binary */ function dataStart(binary) { for (const section of binary.body.sections) { if (section.name === ".go.buildinfo") { return section.addr; } } for (const program of binary.body.programs) { if (program.type === "load" && program.flags.w === true) { return program.vaddr; } } return 0; } // Source // https://github.com/golang/go/blob/46f99ce7ea97d11b0a1a079da8dda0f51df2a2d2/src/cmd/go/internal/version/exe.go#L87 /** * Read at most `size` of bytes from `program` that contains byte at `addr` * @param programs * @param addr * @param size */ function readData(programs, addr, size) { for (const program of programs) { const vaddr = program.vaddr; const filesz = program.filesz; if (vaddr <= addr && addr <= vaddr + filesz - 1) { let n = vaddr + filesz - addr; if (n > size) { n = size; } const from = addr - vaddr; // offset from the beginning of the program return program.data.slice(from, from + n); } } return undefined; } // Source // https://github.com/golang/go/blob/46f99ce7ea97d11b0a1a079da8dda0f51df2a2d2/src/cmd/go/internal/version/version.go#L189 /** * Function returns the string at address addr in the executable x * @param binaryFile * @param ptrSize * @param readPtr * @param addr */ function readString(binaryFile, ptrSize, readPtr, addr) { const hdr = readData(binaryFile.body.programs, addr, 2 * ptrSize); if (!hdr || hdr.length < 2 * ptrSize) { return ""; } const dataAddr = readPtr(hdr); const dataLen = readPtr(hdr.slice(ptrSize)); const data = readData(binaryFile.body.programs, dataAddr, dataLen); if (!data || data.length < dataLen) { return ""; } return data.toString("binary"); } function isTrimmed(files) { // the easiest way to detect trimmed binaries: the filenames will all be // relative. // There usually is a `build` line in the Go binary's metadata that denotes // whether `trimpath` has been used or not, but there are binaries out there // that have trimmed paths without that annotation (for example // kyverno@v1.8.1). return files.every((file) => !file.startsWith(path_1.posix.sep)); } // determinePaths returns the modCachePath and vendorPath for a binary. // goModCachePath is the path at which the modules are downloaded to. When // building a Go binary, this is usually either $GOMODCACHE or // $GOROOT/pkg/mod. // The vendorPath is the path where vendored files are located, which is usually // the main module's location + "/vendor". // // Binaries built with `-trimpath` will have all paths trimmed away, meaning // that both returned values will be empty. function determinePaths(modules, files) { const normalizedFiles = files.map((file) => path_1.posix.normalize(file)); if (isTrimmed(normalizedFiles)) { return { modCachePath: "", vendorPath: "" }; } return { modCachePath: determineGoModCachePath(modules, normalizedFiles), vendorPath: determineVendorPath(modules, normalizedFiles), }; } exports.determinePaths = determinePaths; function determineVendorPath(modules, files) { // to determine the vendor path, we search for a file that contains // `vendor/`. This file also contains the "root" of the // repository, e.g. `/app/vendor/`. This means that the `main` // package is located somewhere in `/app/...`. // We check for other files in that root to make sure that we really got the // right vendor folder, and not just a random folder named `vendor` somewhere. for (const [, mod] of Object.entries(modules)) { // use path.join so that we will always get linux-style paths even if // the plugin runs on Windows. This is necessary because the Go binaries // always contain linux-style path separators. const vendoredModulePath = path_1.posix.join("vendor", mod.name) + path_1.posix.sep; const file = files.find((file) => file.includes(vendoredModulePath)); if (file) { // make sure that we find other files in that path not in the vendor // folder. const mainModulePath = file.split(vendoredModulePath)[0]; const success = files.find((file) => file.includes(mainModulePath) && !file.includes(vendoredModulePath)); if (success) { return path_1.posix.join(mainModulePath, "vendor") + path_1.posix.sep; } } } return ""; } function determineGoModCachePath(modules, files) { // files in the go mod cache path always contain the module name and version. for (const [, mod] of Object.entries(modules)) { const file = files.find((file) => file.includes(path_1.posix.sep + mod.fullName())); if (file) { return file.split(mod.fullName())[0]; } } return ""; } function trimPrefix(s, prefix) { if (s.startsWith(prefix)) { return s.substring(prefix.length); } return s; } //# sourceMappingURL=go-binary.js.map /***/ }), /***/ 79160: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GoModule = void 0; class GoModule { constructor(name, version) { this.packages = []; this.name = name; this.version = version; } // fullName returns the module's name and version, separated with an `@`. This // reflects how Go stores them on disk (except for vendored paths). fullName() { return this.name + "@" + this.version; } } exports.GoModule = GoModule; //# sourceMappingURL=go-module.js.map /***/ }), /***/ 5998: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.goModulesToScannedProjects = exports.getGoModulesContentAction = exports.DEP_GRAPH_TYPE = void 0; const Debug = __webpack_require__(6807); const elf = __webpack_require__(18); const event_loop_spinner_1 = __webpack_require__(77158); // NOTE: Paths will always be normalized to POSIX even on Windows. // This makes it easier to ignore differences between Linux and Windows. const path_1 = __webpack_require__(71017); const go_binary_1 = __webpack_require__(6803); const debug = Debug("snyk"); const ignoredPaths = [ path_1.posix.normalize("/boot"), path_1.posix.normalize("/dev"), path_1.posix.normalize("/etc"), path_1.posix.normalize("/home"), path_1.posix.normalize("/media"), path_1.posix.normalize("/mnt"), path_1.posix.normalize("/proc"), path_1.posix.normalize("/root"), path_1.posix.normalize("/run"), path_1.posix.normalize("/sbin"), path_1.posix.normalize("/sys"), path_1.posix.normalize("/tmp"), path_1.posix.normalize("/var"), ]; exports.DEP_GRAPH_TYPE = "gomodules"; function filePathMatches(filePath) { const normalizedPath = path_1.posix.normalize(filePath); const dirName = path_1.posix.dirname(normalizedPath); return (!path_1.posix.parse(normalizedPath).ext && !ignoredPaths.some((ignorePath) => dirName.startsWith(ignorePath))); } exports.getGoModulesContentAction = { actionName: "gomodules", filePathMatches, callback: findGoBinaries, }; async function findGoBinaries(stream, streamSize) { return new Promise((resolve, reject) => { const encoding = "binary"; const buildIdMagic = "Go"; const elfHeaderMagic = "\x7FELF"; const buildInfoMagic = "\xff Go buildinf:"; // ELF section headers and so ".go.buildinfo" & ".note.go.buildid" blobs are available in the first 64kb const elfBuildInfoSize = 64 * 1024; const buffer = Buffer.alloc(streamSize !== null && streamSize !== void 0 ? streamSize : elfBuildInfoSize); let bytesWritten = 0; stream.on("end", () => { try { // Discard if (bytesWritten === 0) { return resolve(undefined); } const binaryFile = elf.parse(buffer); const goBuildInfo = binaryFile.body.sections.find((section) => section.name === ".go.buildinfo"); // Could be found in file headers const goBuildId = binaryFile.body.sections.find((section) => section.name === ".note.go.buildid"); if (!goBuildInfo && !goBuildId) { return resolve(undefined); } else if (goBuildInfo) { const info = goBuildInfo.data .slice(0, buildInfoMagic.length) .toString(encoding); if (info === buildInfoMagic) { // to make sure we got a Go binary with module support, we try // reading it. Will throw an error if not. (0, go_binary_1.readRawBuildInfo)(binaryFile); return resolve(binaryFile); } return resolve(undefined); } else if (goBuildId) { const strings = goBuildId.data .toString() .split(/\0+/g) .filter(Boolean); const go = strings[strings.length - 2]; const buildIdParts = strings[strings.length - 1].split(path_1.posix.sep); // Build ID's precise form is actionID/[.../]contentID. // Usually the buildID is simply actionID/contentID, but with exceptions. // https://github.com/golang/go/blob/master/src/cmd/go/internal/work/buildid.go#L23 if (go === buildIdMagic && buildIdParts.length >= 2) { // to make sure we got a Go binary with module support, we try // reading it. Will throw an error if not. (0, go_binary_1.readRawBuildInfo)(binaryFile); return resolve(binaryFile); } return resolve(undefined); } } catch (error) { // catching exception during elf file parse shouldn't fail the archive iteration // it either we recognize file as binary or not return resolve(undefined); } }); stream.on("error", (error) => { reject(error); }); stream.once("data", (chunk) => { const first4Bytes = chunk.toString(encoding, 0, 4); if (first4Bytes === elfHeaderMagic) { Buffer.from(chunk).copy(buffer, bytesWritten, 0); bytesWritten += chunk.length; // Listen to next chunks only if it's an ELF executable stream.addListener("data", (chunk) => { Buffer.from(chunk).copy(buffer, bytesWritten, 0); bytesWritten += chunk.length; }); } }); }); } /** * Build depGraphs for each Go executable * @param filePathToContent */ async function goModulesToScannedProjects(filePathToContent) { const scanResults = []; for (const [filePath, goBinary] of Object.entries(filePathToContent)) { if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } try { const depGraph = await new go_binary_1.GoBinary(goBinary).depGraph(); if (!depGraph) { continue; } const depGraphFact = { type: "depGraph", data: depGraph, }; scanResults.push({ facts: [depGraphFact], identity: { type: exports.DEP_GRAPH_TYPE, // TODO: The path will contain forward slashes on Linux or backslashes on Windows. // So if you scanned the exact same image but from two different machines, // we'd generate two different identities. // These two identities would create two different Projects if monitored... so is this a bug? // If we enforce forward-slashes in every case, would that create duplicate Projects // for existing users who are using the current "backslashes on Windows" behaviour? targetFile: filePath, }, }); } catch (err) { debug(`Go binary scan for file ${filePath} failed: ${err.message}`); } } return scanResults; } exports.goModulesToScannedProjects = goModulesToScannedProjects; //# sourceMappingURL=index.js.map /***/ }), /***/ 77162: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LineTable = void 0; // lineTable maps to the Go type https://pkg.go.dev/debug/gosym#LineTable class LineTable { // https://pkg.go.dev/debug/gosym#NewLineTable, but only what we need to read out the files. constructor(b) { // the Go type contains some exported fields, but as we don't require anything, we don't export it. // We only store what we require, so some fields are missing when compared to the Go implementation. this.version = pclnVersion.unknown; this.fileMap = new Map(); // Check header: 4-byte magic, two zeros, pc quantum, pointer size. if (b.length < 16 || b[4] !== 0 || b[5] !== 0 || // pc quantum (b[6] !== 1 && b[6] !== 2 && b[6] !== 4) || // pointer size (b[7] !== 4 && b[7] !== 8)) { throw new Error("unknown header format"); } // determine the endianness and the PCLN Table version const leMagic = b.readUInt32LE(0); const beMagic = b.readUInt32BE(0); if (leMagic === LineTable.go12magic) { this.binary = littleEndian; this.version = pclnVersion.v12; } else if (beMagic === LineTable.go12magic) { this.binary = bigEndian; this.version = pclnVersion.v12; } else if (leMagic === LineTable.go116magic) { this.binary = littleEndian; this.version = pclnVersion.v116; } else if (beMagic === LineTable.go116magic) { this.binary = bigEndian; this.version = pclnVersion.v116; } else if (leMagic === LineTable.go118magic) { this.binary = littleEndian; this.version = pclnVersion.v118; } else if (beMagic === LineTable.go118magic) { this.binary = bigEndian; this.version = pclnVersion.v118; } else if (beMagic === LineTable.go120magic) { this.binary = bigEndian; this.version = pclnVersion.v120; } else if (leMagic === LineTable.go120magic) { this.binary = littleEndian; this.version = pclnVersion.v118; } else { throw new Error(`unknown / unsupported Go version`); } this.ptrsize = b[7]; const uintptr = (b) => { if (this.ptrsize === 4) { return this.binary.Uint32(b); } return this.binary.Uint64(b); }; const offset = (word) => { return uintptr(b.slice(8 + word * this.ptrsize)); }; const data = (word) => { return b.slice(Number(offset(word))); // TODO: int conversion? }; switch (this.version) { case pclnVersion.v118: case pclnVersion.v120: this.nfiletab = Number(offset(1)); this.filetab = data(5); this.funcdata = data(7); break; case pclnVersion.v116: this.nfiletab = Number(offset(1)); this.filetab = data(4); this.funcdata = data(6); break; case pclnVersion.v12: const nfunctab = Number(this.uintptr(b.slice(8))); this.funcdata = b; const functab = b.slice(8 + this.ptrsize); const functabsize = (nfunctab * 2 + 1) * this.functabFieldSize(); const fileoff = this.binary.Uint32(functab.slice(functabsize)); this.filetab = b.slice(Number(fileoff)); this.nfiletab = Number(this.binary.Uint32(this.filetab)); break; default: throw new Error("unreachable"); } } // go12MapFiles returns a list of files that have been found in the symbol table. // In the original Go implementation, this function takes a map and object, but // we don't need to construct a map and don't need the object. // https://cs.opensource.google/go/go/+/refs/tags/go1.18.5:src/debug/gosym/pclntab.go;l=669 go12MapFiles() { this.initFileMap(); const files = []; for (const file of Object.keys(this.fileMap)) { files.push(file); } return files; } // uintptr returns the pointer-sized value encoded at b. // The pointer size is dictated by the table being read. uintptr(b) { if (this.ptrsize === 4) { return BigInt(this.binary.Uint32(b)); } return this.binary.Uint64(b); } // functabFieldSize returns the sivze in bytes of a single functab field. // https://cs.opensource.google/go/go/+/refs/tags/go1.18.5:src/debug/gosym/pclntab.go;l=377 functabFieldSize() { if (this.version >= pclnVersion.v118) { return 4; } return this.ptrsize; } // string returns a Go string found at offset. // https://cs.opensource.google/go/go/+/refs/tags/go1.18.5:src/debug/gosym/pclntab.go;l=372 string(offset) { return this.stringFrom(this.funcdata, offset); } // initFileMap initializes the map from file name to file number. // We technically don't need the number, but match Go's implementation 1:1 instead. // https://cs.opensource.google/go/go/+/refs/tags/go1.18.5:src/debug/gosym/pclntab.go;l=641 initFileMap() { if (this.fileMap.size > 0) { return; } const files = new Map(); if (this.version === pclnVersion.v12) { for (let i = 1; i < this.nfiletab; i++) { const fileName = this.string(Number(this.binary.Uint32(this.filetab.slice(4 * i)))); files[fileName] = i; } } else { let pos = 0; for (let i = 0; i < this.nfiletab; i++) { const fileName = this.stringFrom(this.filetab, pos); files[fileName] = pos; pos += fileName.length + 1; } } this.fileMap = files; } // stringFrom returns a Go string found at offset from a position. // https://cs.opensource.google/go/go/+/refs/tags/go1.18.5:src/debug/gosym/pclntab.go;l=361 stringFrom(arr, offset) { const i = arr.slice(offset).indexOf(0); const s = arr.slice(offset, offset + i).toString("ascii"); return s; } } exports.LineTable = LineTable; LineTable.go12magic = 0xfffffffb; LineTable.go116magic = 0xfffffffa; LineTable.go118magic = 0xfffffff0; LineTable.go120magic = 0xfffffff1; var pclnVersion; (function (pclnVersion) { pclnVersion[pclnVersion["unknown"] = 0] = "unknown"; pclnVersion[pclnVersion["v11"] = 1] = "v11"; pclnVersion[pclnVersion["v12"] = 2] = "v12"; pclnVersion[pclnVersion["v116"] = 3] = "v116"; pclnVersion[pclnVersion["v118"] = 4] = "v118"; pclnVersion[pclnVersion["v120"] = 5] = "v120"; })(pclnVersion || (pclnVersion = {})); const bigEndian = { Uint32(b) { return BigInt(b.readUInt32BE(0)); }, Uint64(b) { return b.readBigUInt64BE(0); }, }; const littleEndian = { Uint32(b) { return BigInt(b.readUInt32LE(0)); }, Uint64(b) { return b.readBigUInt64LE(0); }, }; //# sourceMappingURL=pclntab.js.map /***/ }), /***/ 89313: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fullImageSavePath = void 0; const path = __webpack_require__(71017); const tmp = __webpack_require__(85816); const uuid_1 = __webpack_require__(96771); function fullImageSavePath(imageSavePath) { let imagePath = tmp.dirSync().name; if (imageSavePath) { imagePath = path.normalize(imageSavePath); } return path.join(imagePath, (0, uuid_1.v4)()); } exports.fullImageSavePath = fullImageSavePath; //# sourceMappingURL=image-save-path.js.map /***/ }), /***/ 38932: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getArchivePath = exports.getImageType = void 0; const path_1 = __webpack_require__(71017); const types_1 = __webpack_require__(93677); function getImageType(targetImage) { const imageIdentifier = targetImage.split(":")[0]; switch (imageIdentifier) { case "docker-archive": return types_1.ImageType.DockerArchive; case "oci-archive": return types_1.ImageType.OciArchive; case "kaniko-archive": return types_1.ImageType.KanikoArchive; default: if (imageIdentifier.endsWith(".tar")) { return types_1.ImageType.UnspecifiedArchiveType; } else { return types_1.ImageType.Identifier; } } } exports.getImageType = getImageType; function getArchivePath(targetImage) { const possibleArchiveTypes = [ "docker-archive", "oci-archive", "kaniko-archive", ]; for (const archiveType of possibleArchiveTypes) { if (targetImage.startsWith(archiveType)) { return (0, path_1.normalize)(targetImage.substring(`${archiveType}:`.length)); } } if (targetImage.endsWith(".tar")) { return (0, path_1.normalize)(targetImage); } throw new Error('The provided archive path is missing a prefix, for example "docker-archive:", "oci-archive:" or "kaniko-archive"'); } exports.getArchivePath = getArchivePath; //# sourceMappingURL=image-type.js.map /***/ }), /***/ 61165: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseDockerfile = exports.UpdateDockerfileBaseImageNameErrorCode = exports.updateDockerfileBaseImageName = exports.DockerFileAnalysisErrorCode = exports.analyseDockerfile = exports.facts = exports.extractContent = exports.dockerFile = exports.display = exports.scan = void 0; const display_1 = __webpack_require__(75613); Object.defineProperty(exports, "display", ({ enumerable: true, get: function () { return display_1.display; } })); const dockerFile = __webpack_require__(79652); exports.dockerFile = dockerFile; const dockerfile_1 = __webpack_require__(79652); Object.defineProperty(exports, "analyseDockerfile", ({ enumerable: true, get: function () { return dockerfile_1.analyseDockerfile; } })); Object.defineProperty(exports, "parseDockerfile", ({ enumerable: true, get: function () { return dockerfile_1.parseDockerfile; } })); Object.defineProperty(exports, "updateDockerfileBaseImageName", ({ enumerable: true, get: function () { return dockerfile_1.updateDockerfileBaseImageName; } })); const types_1 = __webpack_require__(13939); Object.defineProperty(exports, "DockerFileAnalysisErrorCode", ({ enumerable: true, get: function () { return types_1.DockerFileAnalysisErrorCode; } })); Object.defineProperty(exports, "UpdateDockerfileBaseImageNameErrorCode", ({ enumerable: true, get: function () { return types_1.UpdateDockerfileBaseImageNameErrorCode; } })); const facts = __webpack_require__(86666); exports.facts = facts; const scan_1 = __webpack_require__(79863); Object.defineProperty(exports, "extractContent", ({ enumerable: true, get: function () { return scan_1.extractContent; } })); Object.defineProperty(exports, "scan", ({ enumerable: true, get: function () { return scan_1.scan; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 97770: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getApkDbFileContent = exports.getApkDbFileContentAction = void 0; const path_1 = __webpack_require__(71017); const extractor_1 = __webpack_require__(18141); const stream_utils_1 = __webpack_require__(54540); exports.getApkDbFileContentAction = { actionName: "apk-db", filePathMatches: (filePath) => filePath === (0, path_1.normalize)("/lib/apk/db/installed"), callback: stream_utils_1.streamToString, }; function getApkDbFileContent(extractedLayers) { const apkDb = (0, extractor_1.getContentAsString)(extractedLayers, exports.getApkDbFileContentAction); return apkDb || ""; } exports.getApkDbFileContent = getApkDbFileContent; //# sourceMappingURL=static.js.map /***/ }), /***/ 52851: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getAptDbFileContent = exports.getExtFileContentAction = exports.getDpkgFileContentAction = void 0; const path_1 = __webpack_require__(71017); const extractor_1 = __webpack_require__(18141); const stream_utils_1 = __webpack_require__(54540); exports.getDpkgFileContentAction = { actionName: "dpkg", filePathMatches: (filePath) => filePath === (0, path_1.normalize)("/var/lib/dpkg/status"), callback: stream_utils_1.streamToString, }; exports.getExtFileContentAction = { actionName: "ext", filePathMatches: (filePath) => filePath === (0, path_1.normalize)("/var/lib/apt/extended_states"), callback: stream_utils_1.streamToString, }; function getAptDbFileContent(extractedLayers) { const dpkgContent = (0, extractor_1.getContentAsString)(extractedLayers, exports.getDpkgFileContentAction); const dpkgFile = dpkgContent || ""; const extContent = (0, extractor_1.getContentAsString)(extractedLayers, exports.getExtFileContentAction); const extFile = extContent || ""; return { dpkgFile, extFile, }; } exports.getAptDbFileContent = getAptDbFileContent; //# sourceMappingURL=static.js.map /***/ }), /***/ 23426: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getBinariesHashes = exports.getNodeBinariesFileContentAction = exports.getOpenJDKBinariesFileContentAction = void 0; const stream_utils_1 = __webpack_require__(54540); exports.getOpenJDKBinariesFileContentAction = { actionName: "java", filePathMatches: (filePath) => filePath.endsWith("java"), callback: stream_utils_1.streamToSha256, }; exports.getNodeBinariesFileContentAction = { actionName: "node", filePathMatches: (filePath) => filePath.endsWith("node"), callback: stream_utils_1.streamToSha256, }; const binariesExtractActions = [ exports.getNodeBinariesFileContentAction, exports.getOpenJDKBinariesFileContentAction, ]; function getBinariesHashes(extractedLayers) { const hashes = new Set(); for (const fileName of Object.keys(extractedLayers)) { for (const actionName of Object.keys(extractedLayers[fileName])) { for (const action of binariesExtractActions) { if (actionName !== action.actionName) { continue; } if (!(typeof extractedLayers[fileName][actionName] === "string")) { throw new Error("expected string"); } hashes.add(extractedLayers[fileName][actionName]); } } } return [...hashes]; } exports.getBinariesHashes = getBinariesHashes; //# sourceMappingURL=index.js.map /***/ }), /***/ 236: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getAptFiles = exports.getDpkgPackageFileContentAction = void 0; const path_1 = __webpack_require__(71017); const stream_utils_1 = __webpack_require__(54540); exports.getDpkgPackageFileContentAction = { actionName: "dpkg", filePathMatches: (filePath) => filePath.startsWith((0, path_1.normalize)("/var/lib/dpkg/status.d/")), callback: stream_utils_1.streamToString, // TODO replace with a parser for apt data extractor }; function getAptFiles(extractedLayers) { const files = []; for (const fileName of Object.keys(extractedLayers)) { if (!("dpkg" in extractedLayers[fileName])) { continue; } files.push(extractedLayers[fileName].dpkg.toString("utf8")); } return files; } exports.getAptFiles = getAptFiles; //# sourceMappingURL=static.js.map /***/ }), /***/ 89589: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getMatchingFiles = exports.generateExtractAction = void 0; const minimatch = __webpack_require__(91171); const path = __webpack_require__(71017); const stream_utils_1 = __webpack_require__(54540); function generatePathMatcher(globsInclude, globsExclude) { return (filePath) => { let exclude = false; for (const g of globsExclude) { if (!exclude && minimatch(filePath, g)) { exclude = true; } } if (!exclude) { for (const g of globsInclude) { if (minimatch(filePath, g)) { return true; } } } return false; }; } function generateExtractAction(globsInclude, globsExclude) { return { actionName: "find-files-by-pattern", filePathMatches: generatePathMatcher(globsInclude, globsExclude), callback: (dataStream, streamSize) => (0, stream_utils_1.streamToString)(dataStream, streamSize, "base64"), }; } exports.generateExtractAction = generateExtractAction; function getMatchingFiles(extractedLayers) { const manifestFiles = []; for (const filePath of Object.keys(extractedLayers)) { for (const actionName of Object.keys(extractedLayers[filePath])) { if (actionName !== "find-files-by-pattern") { continue; } if (typeof extractedLayers[filePath][actionName] !== "string") { throw new Error("expected a string"); } manifestFiles.push({ name: path.basename(filePath), path: path.dirname(filePath), contents: extractedLayers[filePath][actionName], }); } } return manifestFiles; } exports.getMatchingFiles = getMatchingFiles; //# sourceMappingURL=static.js.map /***/ }), /***/ 29484: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getBufferContent = exports.getElfFileContent = exports.getFileContent = exports.getContent = void 0; function getContent(extractedLayers, searchedAction, contentTypeValidation) { const foundAppFiles = {}; for (const filePath of Object.keys(extractedLayers)) { for (const actionName of Object.keys(extractedLayers[filePath])) { if (actionName !== searchedAction) { continue; } if (!contentTypeValidation(extractedLayers[filePath][actionName])) { throw new Error("unexpected content type"); } foundAppFiles[filePath] = extractedLayers[filePath][actionName]; } } return foundAppFiles; } exports.getContent = getContent; function isStringType(type) { return typeof type === "string"; } function getFileContent(extractedLayers, searchedAction) { let foundAppFiles; try { foundAppFiles = getContent(extractedLayers, searchedAction, isStringType); } catch (_a) { throw new Error("expected string"); } return foundAppFiles; } exports.getFileContent = getFileContent; function isElfType(type) { const elf = type; return !!(elf.body && elf.body.programs && elf.body.sections); } function getElfFileContent(extractedLayers, searchedAction) { let foundAppFiles; try { foundAppFiles = getContent(extractedLayers, searchedAction, isElfType); } catch (_a) { throw new Error("elf file expected to contain programs and sections"); } return foundAppFiles; } exports.getElfFileContent = getElfFileContent; function isTypeBuffer(type) { return Buffer.isBuffer(type); } function getBufferContent(extractedLayers, searchedAction) { let foundAppFiles; try { foundAppFiles = getContent(extractedLayers, searchedAction, isTypeBuffer); } catch (_a) { throw new Error("expected Buffer"); } return foundAppFiles; } exports.getBufferContent = getBufferContent; //# sourceMappingURL=index.js.map /***/ }), /***/ 92212: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getJarFileContentAction = void 0; const path = __webpack_require__(71017); const stream_utils_1 = __webpack_require__(54540); const ignoredPaths = ["/usr/lib", "gradle/cache"]; const javaArchiveFileFormats = [".jar", ".war"]; function filePathMatches(filePath) { const dirName = path.dirname(filePath); const fileExtension = filePath.slice(-4); return (javaArchiveFileFormats.includes(fileExtension) && !ignoredPaths.some((ignorePath) => dirName.includes(path.normalize(ignorePath)))); } exports.getJarFileContentAction = { actionName: "jar", filePathMatches, callback: stream_utils_1.streamToBuffer, }; //# sourceMappingURL=static.js.map /***/ }), /***/ 5809: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getNodeJsTsAppFileContentAction = exports.getNodeAppFileContentAction = void 0; const path_1 = __webpack_require__(71017); const stream_utils_1 = __webpack_require__(54540); const nodeAppFiles = ["package.json", "package-lock.json", "yarn.lock"]; const deletedAppFiles = nodeAppFiles.map((file) => ".wh." + file); const nodeJsTsAppFileSuffixes = [ ".js", ".ts", "package.json", "package-lock.json", ]; const excludedNodeJsTsAppFileSuffixes = [".d.ts"]; function filePathMatches(filePath) { const fileName = (0, path_1.basename)(filePath); return nodeAppFiles.includes(fileName) || deletedAppFiles.includes(fileName); } exports.getNodeAppFileContentAction = { actionName: "node-app-files", filePathMatches, callback: stream_utils_1.streamToString, }; function nodeJsTsAppFilePathMatches(filePath) { return (!filePath.includes("node_modules/") && // "/usr/" should not include 1st party code !filePath.startsWith("/usr/") && nodeJsTsAppFileSuffixes.some((suffix) => filePath.endsWith(suffix)) && !excludedNodeJsTsAppFileSuffixes.some((excludedSuffix) => filePath.endsWith(excludedSuffix))); } exports.getNodeJsTsAppFileContentAction = { actionName: "node-js-ts-app-files", filePathMatches: nodeJsTsAppFilePathMatches, callback: stream_utils_1.streamToString, }; //# sourceMappingURL=static.js.map /***/ }), /***/ 17835: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getOsReleaseStatic = void 0; const static_1 = __webpack_require__(96704); Object.defineProperty(exports, "getOsReleaseStatic", ({ enumerable: true, get: function () { return static_1.getOsRelease; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 96704: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getOsRelease = exports.getOsReleaseActions = void 0; const path_1 = __webpack_require__(71017); const extractor_1 = __webpack_require__(18141); const stream_utils_1 = __webpack_require__(54540); const types_1 = __webpack_require__(93677); const getOsReleaseAction = { actionName: "os-release", filePathMatches: (filePath) => filePath === (0, path_1.normalize)(types_1.OsReleaseFilePath.Linux), callback: stream_utils_1.streamToString, }; const getFallbackOsReleaseAction = { actionName: "os-release-fallback", filePathMatches: (filePath) => filePath === (0, path_1.normalize)(types_1.OsReleaseFilePath.LinuxFallback), callback: stream_utils_1.streamToString, }; const getLsbReleaseAction = { actionName: "lsb-release", filePathMatches: (filePath) => filePath === (0, path_1.normalize)(types_1.OsReleaseFilePath.Lsb), callback: stream_utils_1.streamToString, }; const getDebianVersionAction = { actionName: "debian-version", filePathMatches: (filePath) => filePath === (0, path_1.normalize)(types_1.OsReleaseFilePath.Debian), callback: stream_utils_1.streamToString, }; const getAlpineReleaseAction = { actionName: "alpine-release", filePathMatches: (filePath) => filePath === (0, path_1.normalize)(types_1.OsReleaseFilePath.Alpine), callback: stream_utils_1.streamToString, }; const getRedHatReleaseAction = { actionName: "redhat-release", filePathMatches: (filePath) => filePath === (0, path_1.normalize)(types_1.OsReleaseFilePath.RedHat), callback: stream_utils_1.streamToString, }; const getCentosReleaseAction = { actionName: "centos-release", filePathMatches: (filePath) => filePath === (0, path_1.normalize)(types_1.OsReleaseFilePath.Centos), callback: stream_utils_1.streamToString, }; const getOracleReleaseAction = { actionName: "oracle-release", filePathMatches: (filePath) => filePath === (0, path_1.normalize)(types_1.OsReleaseFilePath.Oracle), callback: stream_utils_1.streamToString, }; const osReleaseActionMap = { [types_1.OsReleaseFilePath.Linux]: getOsReleaseAction, [types_1.OsReleaseFilePath.LinuxFallback]: getFallbackOsReleaseAction, [types_1.OsReleaseFilePath.Lsb]: getLsbReleaseAction, [types_1.OsReleaseFilePath.Debian]: getDebianVersionAction, [types_1.OsReleaseFilePath.Alpine]: getAlpineReleaseAction, [types_1.OsReleaseFilePath.RedHat]: getRedHatReleaseAction, [types_1.OsReleaseFilePath.Centos]: getCentosReleaseAction, [types_1.OsReleaseFilePath.Oracle]: getOracleReleaseAction, }; exports.getOsReleaseActions = [ getOsReleaseAction, getFallbackOsReleaseAction, getLsbReleaseAction, getDebianVersionAction, getAlpineReleaseAction, getRedHatReleaseAction, getCentosReleaseAction, getOracleReleaseAction, ]; function getOsRelease(extractedLayers, releasePath) { const osRelease = (0, extractor_1.getContentAsString)(extractedLayers, osReleaseActionMap[releasePath]); return osRelease || ""; } exports.getOsRelease = getOsRelease; //# sourceMappingURL=static.js.map /***/ }), /***/ 92578: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getPhpAppFileContentAction = void 0; const path_1 = __webpack_require__(71017); const stream_utils_1 = __webpack_require__(54540); const phpAppFiles = ["composer.json", "composer.lock"]; const deletedAppFiles = phpAppFiles.map((file) => ".wh." + file); function filePathMatches(filePath) { const fileName = (0, path_1.basename)(filePath); return phpAppFiles.includes(fileName) || deletedAppFiles.includes(fileName); } exports.getPhpAppFileContentAction = { actionName: "php-app-files", filePathMatches, callback: stream_utils_1.streamToString, }; //# sourceMappingURL=static.js.map /***/ }), /***/ 88795: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getPythonAppFileContentAction = exports.getPipAppFileContentAction = exports.getPoetryAppFileContentAction = void 0; const path_1 = __webpack_require__(71017); const stream_utils_1 = __webpack_require__(54540); const poetryManifestFiles = ["pyproject.toml", "poetry.lock"]; const pipManifestFiles = ["requirements.txt"]; const pythonMetadataFilesRegex = /\/lib\/python.*?\/(?:dist|site)-packages\/.*?\.dist-info\/METADATA/; const deletedPoetryAppFiles = poetryManifestFiles.map((file) => ".wh." + file); const deletedPipAppFiles = pipManifestFiles.map((file) => ".wh." + file); const pythonApplicationFileSuffixes = [".py", "requirements.txt", "Pipfile"]; function poetryFilePathMatches(filePath) { const fileName = (0, path_1.basename)(filePath); return (poetryManifestFiles.includes(fileName) || deletedPoetryAppFiles.includes(fileName)); } exports.getPoetryAppFileContentAction = { actionName: "poetry-app-files", filePathMatches: poetryFilePathMatches, callback: stream_utils_1.streamToString, }; function pipFilePathMatches(filePath) { const fileName = (0, path_1.basename)(filePath); return (pipManifestFiles.includes(fileName) || pythonMetadataFilesRegex.test(filePath) || deletedPipAppFiles.includes(fileName)); } exports.getPipAppFileContentAction = { actionName: "pip-app-files", filePathMatches: pipFilePathMatches, callback: stream_utils_1.streamToString, }; function pythonApplicationFilePathMatches(filePath) { return (!filePath.includes("/site-packages/") && !filePath.includes("/dist-packages/") && // "/usr/" should not include 1st party code !filePath.startsWith("/usr/") && pythonApplicationFileSuffixes.some((suffix) => filePath.endsWith(suffix))); } exports.getPythonAppFileContentAction = { actionName: "python-app-files", filePathMatches: pythonApplicationFilePathMatches, callback: stream_utils_1.streamToString, }; //# sourceMappingURL=static.js.map /***/ }), /***/ 98157: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRedHatRepositoriesFromExtractedLayers = exports.getRedHatRepositoriesContentAction = void 0; const stream_utils_1 = __webpack_require__(54540); exports.getRedHatRepositoriesContentAction = { actionName: "redhat-content-manifests", filePathMatches: isRedHatContentManifest, callback: stream_utils_1.streamToJson, }; function getRedHatRepositoriesFromExtractedLayers(extractedLayers) { const repositories = []; for (const filePath in extractedLayers) { if (isRedHatContentManifest(filePath)) { const contentManifest = extractedLayers[filePath]["redhat-content-manifests"]; if (!contentManifest || !contentManifest.content_sets) { continue; } repositories.push(...contentManifest === null || contentManifest === void 0 ? void 0 : contentManifest.content_sets); } } return [...new Set(repositories)]; } exports.getRedHatRepositoriesFromExtractedLayers = getRedHatRepositoriesFromExtractedLayers; function isRedHatContentManifest(filePath) { return filePath.startsWith("/root/buildinfo/content_manifests/"); } //# sourceMappingURL=static.js.map /***/ }), /***/ 45330: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRpmSqliteDbFileContentAction = exports.getRpmSqliteDbFileContent = exports.getRpmDbFileContent = exports.getRpmDbFileContentAction = void 0; const rpm_parser_1 = __webpack_require__(76713); const Debug = __webpack_require__(6807); const path_1 = __webpack_require__(71017); const extractor_1 = __webpack_require__(18141); const stream_utils_1 = __webpack_require__(54540); const debug = Debug("snyk"); exports.getRpmDbFileContentAction = { actionName: "rpm-db", filePathMatches: (filePath) => filePath === (0, path_1.normalize)("/var/lib/rpm/Packages") || filePath === (0, path_1.normalize)("/usr/lib/sysimage/rpm/Packages"), callback: stream_utils_1.streamToBuffer, }; async function getRpmDbFileContent(extractedLayers) { const rpmDb = (0, extractor_1.getContentAsBuffer)(extractedLayers, exports.getRpmDbFileContentAction); if (!rpmDb) { return []; } try { const parserResponse = await (0, rpm_parser_1.getPackages)(rpmDb); if (parserResponse.error !== undefined) { throw parserResponse.error; } return parserResponse.response; } catch (error) { debug(`An error occurred while analysing RPM packages: ${error.message}`); return []; } } exports.getRpmDbFileContent = getRpmDbFileContent; async function getRpmSqliteDbFileContent(extractedLayers) { const rpmDb = (0, extractor_1.getContentAsBuffer)(extractedLayers, exports.getRpmSqliteDbFileContentAction); if (!rpmDb) { return []; } try { const results = await (0, rpm_parser_1.getPackagesSqlite)(rpmDb); if (results.error) { throw results.error; } return results.response; } catch (error) { debug(`An error occurred while analysing RPM packages: ${error.message}`); return []; } } exports.getRpmSqliteDbFileContent = getRpmSqliteDbFileContent; exports.getRpmSqliteDbFileContentAction = { actionName: "rpm-sqlite-db", filePathMatches: (filePath) => filePath === (0, path_1.normalize)("/var/lib/rpm/rpmdb.sqlite") || filePath === (0, path_1.normalize)("/usr/lib/sysimage/rpm/rpmdb.sqlite") || filePath === (0, path_1.normalize)("/usr/lib/sysimage/rpm/Packages.db"), callback: stream_utils_1.streamToBuffer, }; //# sourceMappingURL=static.js.map /***/ }), /***/ 48587: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isNumber = exports.isTrue = void 0; function isTrue(value) { return String(value).toLowerCase() === "true"; } exports.isTrue = isTrue; function isNumber(value) { return !isNaN(Number(value)); } exports.isNumber = isNumber; //# sourceMappingURL=option-utils.js.map /***/ }), /***/ 45062: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseAnalysisResults = void 0; const types_1 = __webpack_require__(36293); function parseAnalysisResults(targetImage, analysis) { let analysisResult = analysis.results.filter((res) => { return res.Analysis && res.Analysis.length > 0; })[0]; if (!analysisResult) { // Special case when we have no package management // on scratch images or images with unknown package manager analysisResult = { Image: targetImage, AnalyzeType: types_1.AnalysisType.Linux, Analysis: [], }; } let packageFormat; switch (analysisResult.AnalyzeType) { case types_1.AnalysisType.Apt: { packageFormat = "deb"; break; } default: { packageFormat = analysisResult.AnalyzeType.toLowerCase(); } } return { imageId: analysis.imageId, platform: analysis.platform, targetOS: analysis.osRelease, packageFormat, depInfosList: analysisResult.Analysis, imageLayers: analysis.imageLayers, }; } exports.parseAnalysisResults = parseAnalysisResults; //# sourceMappingURL=index.js.map /***/ }), /***/ 60409: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseExtraNames = exports.compareVersions = exports.VERSION_EXTRACTION_REGEX = exports.specifierValidRange = void 0; function specifierValidRange(specifier, version) { specifier = specifier === "==" || specifier === "===" || specifier === "~=" ? specifier.charAt(0) : specifier; if (specifier !== "~") { return specifier; } // the tilde specifier in a requirements file means different things, depending on the // way the version is provided. In order for the semver library to compare as expected, // we need to change the specifier to something it understands. // see https://peps.python.org/pep-0440/#compatible-release const versionPartsLength = version.split(".").length; return versionPartsLength === 2 ? "^" : "~"; } exports.specifierValidRange = specifierValidRange; // This regex is used to extract the "semver" part from the version string. // See the tests for a better understanding (Also the reason why this is exported) exports.VERSION_EXTRACTION_REGEX = /(?(\d+\.)*\d+).*/; function compareArrays(v1, v2) { const max = v1.length > v2.length ? v1.length : v2.length; for (let i = 0; i < max; i++) { if ((v1[i] || 0) < (v2[i] || 0)) { return 1; } if ((v1[i] || 0) > (v2[i] || 0)) { return -1; } } return 0; } /** * This function was taken from a different semver library and slightly modified. * If passed to Array.prototype.sort, versions will be sorted in descending order. */ function compareVersions(version1, version2) { const v1Match = exports.VERSION_EXTRACTION_REGEX.exec(version1); const v2Match = exports.VERSION_EXTRACTION_REGEX.exec(version2); if (v1Match === null || v2Match === null) { return 0; } const v1 = v1Match .groups.VERSION.split(".") .map((part) => Number.parseInt(part, 10)); const v2 = v2Match .groups.VERSION.split(".") .map((part) => Number.parseInt(part, 10)); return compareArrays(v1, v2); } exports.compareVersions = compareVersions; /** * Parse extra names inside extras_list * there can be multiple extras separated by comma * see https://peps.python.org/pep-0508 * * @param extras the contents of an extra list, inside (but not including) the square brackets * @returns string array of names */ function parseExtraNames(extras = "") { const extraNames = new Set(); for (const extra of extras.split(",")) { const name = extra.trim(); if (name) { extraNames.add(name); } } return Array.from(extraNames); } exports.parseExtraNames = parseExtraNames; //# sourceMappingURL=common.js.map /***/ }), /***/ 97176: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PythonInvalidVersionError = exports.parseDependency = exports.getPackageInfo = void 0; const semver = __webpack_require__(41009); const common_1 = __webpack_require__(60409); const provides_extra_1 = __webpack_require__(8018); const PACKAGE_NAME = "Name: "; const PACKAGE_VERSION = "Version: "; const PACKAGE_DEPS = "Requires-Dist: "; const DEP_PARSE_REGEX = /^(?[\w.-]+)((\[(?.*)\])?)(\s?\(?(?<|<=|!=|==|>=|>|~=|===)(?[\w.]+)\)?)?/; function getPackageInfo(fileContent) { const lines = fileContent.split("\n"); const providesExtras = (0, provides_extra_1.findProvidesExtras)(lines); let name = ""; let version = ""; const dependencies = []; for (let line of lines) { line = line.trim(); if (line.length === 0) { continue; } if (line.startsWith(PACKAGE_NAME)) { name = line.substring(PACKAGE_NAME.length); } else if (line.startsWith(PACKAGE_VERSION)) { version = line.substring(PACKAGE_VERSION.length); } else if (line.startsWith(PACKAGE_DEPS)) { const pythonPackage = parseDependency(line.substring(PACKAGE_DEPS.length), providesExtras); if (pythonPackage) { dependencies.push(pythonPackage); } } } const validVersion = getParseableVersion(version); return { name: name.toLowerCase(), version: validVersion, dependencies, }; } exports.getPackageInfo = getPackageInfo; // parse a line containing a dependency package name & extras and (optional) specifier + version function parseDependency(packageDependency, providesExtras) { packageDependency = packageDependency.trim(); const parsedDep = DEP_PARSE_REGEX.exec(packageDependency); if (!(parsedDep === null || parsedDep === void 0 ? void 0 : parsedDep.groups)) { return null; } const { name, extras, version, specifier } = parsedDep.groups; return { name: name.toLowerCase(), version, specifier: (0, common_1.specifierValidRange)(specifier, version), extras: (0, common_1.parseExtraNames)(extras), extraEnvMarkers: parseExtraEnvMarkers(providesExtras, packageDependency), }; } exports.parseDependency = parseDependency; // parse extra environment markers located after the quoted marker // see https://peps.python.org/pep-0508 function parseExtraEnvMarkers(providesExtras, requiresDist) { const extraNames = new Set(); // search string after quoted_marker ; const quotedMarker = requiresDist === null || requiresDist === void 0 ? void 0 : requiresDist.split(";"); if (quotedMarker && quotedMarker.length > 1) { for (const extra of providesExtras) { // search for extra env markers for given provides extras const re = new RegExp(`.*extra.*("|')(?${extra})("|').*`); if (re.exec(quotedMarker[1])) { extraNames.add(extra); } } } return Array.from(extraNames); } function getParseableVersion(versionString) { const validVersion = semver.coerce(versionString); if (!validVersion) { throw new PythonInvalidVersionError(`version ${versionString} is not compatible with semver and cannot be compared`); } if (versionString.indexOf(validVersion.version) === 0 && /^\d+(\.\d+)+$/.test(versionString)) { return versionString; } return validVersion.version; } class PythonInvalidVersionError extends Error { } exports.PythonInvalidVersionError = PythonInvalidVersionError; //# sourceMappingURL=metadata-parser.js.map /***/ }), /***/ 8018: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.findProvidesExtras = void 0; // https://packaging.python.org/en/latest/specifications/core-metadata/#provides-extra-multiple-use const PROVIDES_EXTRA = "Provides-Extra:"; // given the lines of a METADATA file, find all 'Provides-Extra' names function findProvidesExtras(lines) { const extras = new Set(); for (const line of lines) { const l = line.trim(); if (l.startsWith(PROVIDES_EXTRA)) { const extra = l.substring(PROVIDES_EXTRA.length).trim(); extras.add(extra); } } return Array.from(extras); } exports.findProvidesExtras = findProvidesExtras; //# sourceMappingURL=provides-extra.js.map /***/ }), /***/ 13157: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRequirements = void 0; const common_1 = __webpack_require__(60409); // This looks like a crazy regex, but it's long because of the named capture groups // which make the result easier to read. It essentially breaks each line into name, // specifier and version, where only the name is mandatory const VERSION_PARSE_REGEX = /^(?[\w.-]+)((\[(?.*)\])?)((?<|<=|!=|==|>=|>|~=|===)(?[\w.]*))?/; function getRequirements(fileContent) { const lines = fileContent.split("\n"); const parsedLines = lines.map(parseLine).filter((res) => res !== null); return parsedLines; } exports.getRequirements = getRequirements; function parseLine(line) { line = line.trim(); if (line.length === 0) { return null; } const parsedLine = VERSION_PARSE_REGEX.exec(line); if (!(parsedLine === null || parsedLine === void 0 ? void 0 : parsedLine.groups)) { return null; } const { name, extras, specifier, version } = parsedLine.groups; const correctedSpecifier = (0, common_1.specifierValidRange)(specifier, version); return { name: name.toLowerCase(), specifier: correctedSpecifier, version, extras: (0, common_1.parseExtraNames)(extras), }; } //# sourceMappingURL=requirements-parser.js.map /***/ }), /***/ 75319: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildResponse = void 0; const dep_graph_1 = __webpack_require__(71479); // Module that provides functions to collect and build response after all // analyses' are done. const dockerfile_1 = __webpack_require__(79652); async function buildResponse(depsAnalysis, dockerfileAnalysis, excludeBaseImageVulns, names, ociDistributionMetadata) { var _a, _b; const deps = depsAnalysis.depTree.dependencies; const dockerfilePkgs = collectDockerfilePkgs(dockerfileAnalysis, deps); const finalDeps = excludeBaseImageDeps(deps, dockerfilePkgs, excludeBaseImageVulns); /** WARNING! Mutates the depTree.dependencies! */ annotateLayerIds(finalDeps, dockerfilePkgs); /** This must be called after all final changes to the DependencyTree. */ const depGraph = await dep_graph_1.legacy.depTreeToGraph(depsAnalysis.depTree, depsAnalysis.packageFormat); const additionalFacts = []; const hashes = depsAnalysis.binaries; if (hashes && hashes.length > 0) { const keyBinariesHashesFact = { type: "keyBinariesHashes", data: hashes, }; additionalFacts.push(keyBinariesHashesFact); } if (dockerfileAnalysis !== undefined) { const dockerfileAnalysisFact = { type: "dockerfileAnalysis", data: dockerfileAnalysis, }; additionalFacts.push(dockerfileAnalysisFact); } if (depsAnalysis.imageId) { const imageIdFact = { type: "imageId", data: depsAnalysis.imageId, }; additionalFacts.push(imageIdFact); } if (depsAnalysis.imageLayers && depsAnalysis.imageLayers.length > 0) { const imageLayersFact = { type: "imageLayers", data: depsAnalysis.imageLayers, }; additionalFacts.push(imageLayersFact); } if (depsAnalysis.imageLabels) { const imageLabels = { type: "imageLabels", data: depsAnalysis.imageLabels, }; additionalFacts.push(imageLabels); } if (depsAnalysis.imageCreationTime) { const imageCreationTimeFact = { type: "imageCreationTime", data: depsAnalysis.imageCreationTime, }; additionalFacts.push(imageCreationTimeFact); } if (depsAnalysis.rootFsLayers && Array.isArray(depsAnalysis.rootFsLayers) && depsAnalysis.rootFsLayers.length > 0) { const rootFsFact = { type: "rootFs", data: depsAnalysis.rootFsLayers, }; additionalFacts.push(rootFsFact); } if (depsAnalysis.depTree.targetOS.prettyName) { const imageOsReleasePrettyNameFact = { type: "imageOsReleasePrettyName", data: depsAnalysis.depTree.targetOS.prettyName, }; additionalFacts.push(imageOsReleasePrettyNameFact); } const manifestFiles = depsAnalysis.manifestFiles.length > 0 ? depsAnalysis.manifestFiles : undefined; if (manifestFiles) { const imageManifestFilesFact = { type: "imageManifestFiles", data: manifestFiles, }; additionalFacts.push(imageManifestFilesFact); } const autoDetectedPackages = (_a = depsAnalysis.autoDetectedUserInstructions) === null || _a === void 0 ? void 0 : _a.dockerfilePackages; const autoDetectedLayers = (_b = depsAnalysis.autoDetectedUserInstructions) === null || _b === void 0 ? void 0 : _b.dockerfileLayers; if (autoDetectedPackages && Object.keys(autoDetectedPackages).length > 0 && autoDetectedLayers && Object.keys(autoDetectedLayers).length > 0) { const autoDetectedPackagesWithChildren = getUserInstructionDeps(autoDetectedPackages, deps); const autoDetectedUserInstructionsFact = { type: "autoDetectedUserInstructions", data: { dockerfileLayers: autoDetectedLayers, dockerfilePackages: autoDetectedPackagesWithChildren, }, }; additionalFacts.push(autoDetectedUserInstructionsFact); } const applicationDependenciesScanResults = (depsAnalysis.applicationDependenciesScanResults || []).map((appDepsScanResult) => { if (depsAnalysis.imageId) { const imageIdFact = { type: "imageId", data: depsAnalysis.imageId, }; appDepsScanResult.facts.push(imageIdFact); } return { ...appDepsScanResult, target: { image: depGraph.rootPkg.name, }, }; }); const args = depsAnalysis.platform !== undefined ? { platform: depsAnalysis.platform } : undefined; const depGraphFact = { type: "depGraph", data: depGraph, }; if (names) { if (names.length > 0) { const imageNameInfo = { names }; const imageNamesFact = { type: "imageNames", data: imageNameInfo, }; additionalFacts.push(imageNamesFact); } } if (ociDistributionMetadata) { const metadataFact = { type: "ociDistributionMetadata", data: ociDistributionMetadata, }; additionalFacts.push(metadataFact); } const scanResults = [ { facts: [depGraphFact, ...additionalFacts], target: { image: depGraph.rootPkg.name, }, identity: { type: depGraph.pkgManager.name, args, }, }, ...applicationDependenciesScanResults, ]; return { scanResults, }; } exports.buildResponse = buildResponse; function collectDockerfilePkgs(dockerAnalysis, deps) { if (!dockerAnalysis) { return; } return getUserInstructionDeps(dockerAnalysis.dockerfilePackages, deps); } // Iterate over the dependencies list; if one is introduced by the dockerfile, // flatten its dependencies and append them to the list of dockerfile // packages. This gives us a reference of all transitive deps installed via // the dockerfile, and the instruction that installed it. function getUserInstructionDeps(dockerfilePackages, dependencies) { for (const dependencyName in dependencies) { if (dependencies.hasOwnProperty(dependencyName)) { const sourceOrName = dependencyName.split("/")[0]; const dockerfilePackage = dockerfilePackages[sourceOrName]; if (dockerfilePackage) { for (const dep of collectDeps(dependencies[dependencyName])) { dockerfilePackages[dep.split("/")[0]] = { ...dockerfilePackage }; } } } } return dockerfilePackages; } function collectDeps(pkg) { // ES5 doesn't have Object.values, so replace with Object.keys() and map() return pkg.dependencies ? Object.keys(pkg.dependencies) .map((name) => pkg.dependencies[name]) .reduce((allDeps, pkg) => { return [...allDeps, ...collectDeps(pkg)]; }, Object.keys(pkg.dependencies)) : []; } // Skip processing if option disabled or dockerfilePkgs is undefined. We // can't exclude anything in that case, because we can't tell which deps are // from dockerfile and which from base image. function excludeBaseImageDeps(deps, dockerfilePkgs, excludeBaseImageVulns) { if (!excludeBaseImageVulns || !dockerfilePkgs) { return deps; } return extractDockerfileDeps(deps, dockerfilePkgs); } function extractDockerfileDeps(allDeps, dockerfilePkgs) { return Object.keys(allDeps) .filter((depName) => dockerfilePkgs[depName]) .reduce((extractedDeps, depName) => { extractedDeps[depName] = allDeps[depName]; return extractedDeps; }, {}); } function annotateLayerIds(deps, dockerfilePkgs) { if (!dockerfilePkgs) { return; } for (const dep of Object.keys(deps)) { const pkg = deps[dep]; const dockerfilePkg = dockerfilePkgs[dep]; if (dockerfilePkg) { pkg.labels = { ...(pkg.labels || {}), dockerLayerId: (0, dockerfile_1.instructionDigest)(dockerfilePkg.instruction), }; } if (pkg.dependencies) { annotateLayerIds(pkg.dependencies, dockerfilePkgs); } } } //# sourceMappingURL=response-builder.js.map /***/ }), /***/ 79863: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.extractContent = exports.appendLatestTagIfMissing = exports.scan = exports.mergeEnvVarsIntoCredentials = void 0; const fs = __webpack_require__(57147); const path = __webpack_require__(71017); const image_inspector_1 = __webpack_require__(95710); const dockerfile_1 = __webpack_require__(79652); const extractor_1 = __webpack_require__(18141); const image_1 = __webpack_require__(92748); const image_save_path_1 = __webpack_require__(89313); const image_type_1 = __webpack_require__(38932); const option_utils_1 = __webpack_require__(48587); const staticModule = __webpack_require__(60317); const types_1 = __webpack_require__(93677); // Registry credentials may also be provided by env vars. When both are set, flags take precedence. function mergeEnvVarsIntoCredentials(options) { options.username = options.username || process.env.SNYK_REGISTRY_USERNAME; options.password = options.password || process.env.SNYK_REGISTRY_PASSWORD; } exports.mergeEnvVarsIntoCredentials = mergeEnvVarsIntoCredentials; async function getAnalysisParameters(options) { if (!options) { throw new Error("No plugin options provided"); } mergeEnvVarsIntoCredentials(options); if (!options.path) { throw new Error("No image identifier or path provided"); } const nestedJarsDepth = options["nested-jars-depth"] || options["shaded-jars-depth"]; if (((0, option_utils_1.isTrue)(nestedJarsDepth) || (0, option_utils_1.isNumber)(nestedJarsDepth)) && (0, option_utils_1.isTrue)(options["exclude-app-vulns"])) { throw new Error("To use --nested-jars-depth, you must not use --exclude-app-vulns"); } if ((!(0, option_utils_1.isNumber)(nestedJarsDepth) && !(0, option_utils_1.isTrue)(nestedJarsDepth) && typeof nestedJarsDepth !== "undefined") || Number(nestedJarsDepth) < 0) { throw new Error("--nested-jars-depth accepts only numbers bigger than or equal to 0"); } // TODO temporary solution to avoid double results for PHP if exists in `globsToFind` if (options.globsToFind) { options.globsToFind.include = options.globsToFind.include.filter((glob) => !glob.includes("composer")); } const targetImage = appendLatestTagIfMissing(options.path); const dockerfilePath = options.file; const dockerfileAnalysis = await (0, dockerfile_1.readDockerfileAndAnalyse)(dockerfilePath); const imageType = (0, image_type_1.getImageType)(targetImage); return { targetImage, imageType, dockerfileAnalysis, options, }; } async function scan(options) { const { targetImage, imageType, dockerfileAnalysis, options: updatedOptions, } = await getAnalysisParameters(options); switch (imageType) { case types_1.ImageType.DockerArchive: case types_1.ImageType.OciArchive: case types_1.ImageType.KanikoArchive: case types_1.ImageType.UnspecifiedArchiveType: return localArchiveAnalysis(targetImage, imageType, dockerfileAnalysis, updatedOptions); case types_1.ImageType.Identifier: return imageIdentifierAnalysis(targetImage, imageType, dockerfileAnalysis, updatedOptions); default: throw new Error("Unhandled image type for image " + targetImage); } } exports.scan = scan; function getAndValidateArchivePath(targetImage) { const archivePath = (0, image_type_1.getArchivePath)(targetImage); if (!fs.existsSync(archivePath)) { throw new Error("The provided archive path does not exist on the filesystem"); } if (!fs.lstatSync(archivePath).isFile()) { throw new Error("The provided archive path is not a file"); } return archivePath; } async function localArchiveAnalysis(targetImage, imageType, dockerfileAnalysis, options) { var _a, _b, _c, _d, _e, _f; const globToFind = { include: ((_a = options.globsToFind) === null || _a === void 0 ? void 0 : _a.include) || [], exclude: ((_b = options.globsToFind) === null || _b === void 0 ? void 0 : _b.exclude) || [], }; const archivePath = getAndValidateArchivePath(targetImage); const imageIdentifier = options.imageNameAndTag || // The target image becomes the base of the path, e.g. "archive.tar" for "/var/tmp/archive.tar" path.basename(archivePath); let imageName; if ((((_c = options.digests) === null || _c === void 0 ? void 0 : _c.manifest) || ((_d = options.digests) === null || _d === void 0 ? void 0 : _d.index)) && options.imageNameAndTag) { imageName = new image_1.ImageName(options.imageNameAndTag, { manifest: (_e = options.digests) === null || _e === void 0 ? void 0 : _e.manifest, index: (_f = options.digests) === null || _f === void 0 ? void 0 : _f.index, }); } return await staticModule.analyzeStatically(imageIdentifier, dockerfileAnalysis, imageType, archivePath, globToFind, options, imageName); } async function imageIdentifierAnalysis(targetImage, imageType, dockerfileAnalysis, options) { var _a, _b; const globToFind = { include: ((_a = options.globsToFind) === null || _a === void 0 ? void 0 : _a.include) || [], exclude: ((_b = options.globsToFind) === null || _b === void 0 ? void 0 : _b.exclude) || [], }; const imageSavePath = (0, image_save_path_1.fullImageSavePath)(options.imageSavePath); const archiveResult = await (0, image_inspector_1.getImageArchive)(targetImage, imageSavePath, options.username, options.password, options.platform); const imagePath = archiveResult.path; const imageName = archiveResult.imageName; try { return await staticModule.analyzeStatically(targetImage, dockerfileAnalysis, imageType, imagePath, globToFind, options, imageName); } finally { archiveResult.removeArchive(); } } function appendLatestTagIfMissing(targetImage) { if ((0, image_type_1.getImageType)(targetImage) === types_1.ImageType.Identifier && !targetImage.includes(":")) { return `${targetImage}:latest`; } return targetImage; } exports.appendLatestTagIfMissing = appendLatestTagIfMissing; async function extractContent(extractActions, options) { const { targetImage, imageType, options: updatedOptions, } = await getAnalysisParameters(options); const { username, password, platform, imageSavePath } = updatedOptions; let imagePath; switch (imageType) { case types_1.ImageType.DockerArchive: case types_1.ImageType.OciArchive: imagePath = getAndValidateArchivePath(targetImage); break; case types_1.ImageType.Identifier: const imageSavePathFull = (0, image_save_path_1.fullImageSavePath)(imageSavePath); const archiveResult = await (0, image_inspector_1.getImageArchive)(targetImage, imageSavePathFull, username, password, platform); imagePath = archiveResult.path; break; default: throw new Error("Unhandled image type for image " + targetImage); } return (0, extractor_1.extractImageContent)(imageType, imagePath, extractActions, updatedOptions); } exports.extractContent = extractContent; //# sourceMappingURL=scan.js.map /***/ }), /***/ 60317: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.analyzeStatically = void 0; const analyzer = __webpack_require__(55269); const dependency_tree_1 = __webpack_require__(95997); const image_1 = __webpack_require__(92748); const oci_distribution_metadata_1 = __webpack_require__(19103); const option_utils_1 = __webpack_require__(48587); const parser_1 = __webpack_require__(45062); const response_builder_1 = __webpack_require__(75319); async function analyzeStatically(targetImage, dockerfileAnalysis, imageType, imagePath, globsToFind, options, imageName) { var _a; const staticAnalysis = await analyzer.analyzeStatically(targetImage, dockerfileAnalysis, imageType, imagePath, globsToFind, options); const parsedAnalysisResult = (0, parser_1.parseAnalysisResults)(targetImage, staticAnalysis); /** @deprecated Should try to build a dependency graph instead. */ const dependenciesTree = (0, dependency_tree_1.buildTree)(targetImage, parsedAnalysisResult.packageFormat, parsedAnalysisResult.depInfosList, parsedAnalysisResult.targetOS); const analysis = { ...staticAnalysis, depTree: dependenciesTree, imageId: parsedAnalysisResult.imageId, imageLayers: parsedAnalysisResult.imageLayers, packageFormat: parsedAnalysisResult.packageFormat, }; const excludeBaseImageVulns = (0, option_utils_1.isTrue)(options["exclude-base-image-vulns"]); const names = (0, image_1.getImageNames)(options, imageName); let ociDistributionMetadata; if (options.imageNameAndTag && ((_a = options.digests) === null || _a === void 0 ? void 0 : _a.manifest)) { ociDistributionMetadata = (0, oci_distribution_metadata_1.constructOCIDisributionMetadata)({ imageName: options.imageNameAndTag, manifestDigest: options.digests.manifest, indexDigest: options.digests.index, }); } return (0, response_builder_1.buildResponse)(analysis, dockerfileAnalysis, excludeBaseImageVulns, names, ociDistributionMetadata); } exports.analyzeStatically = analyzeStatically; //# sourceMappingURL=static.js.map /***/ }), /***/ 54540: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.streamToJson = exports.streamToSha1 = exports.streamToSha256 = exports.streamToBuffer = exports.streamToString = void 0; const crypto = __webpack_require__(6113); const types_1 = __webpack_require__(93677); const HASH_ENCODING = "hex"; const MEGABYTE = 1 * 1024 * 1024; async function streamToString(stream, streamSize, encoding = "utf8") { const chunks = []; return new Promise((resolve, reject) => { stream.on("end", () => { resolve(Buffer.concat(chunks).toString(encoding)); }); stream.on("error", (error) => reject(error)); stream.on("data", (chunk) => { chunks.push(chunk); }); }); } exports.streamToString = streamToString; async function streamToBuffer(stream) { const chunks = []; return new Promise((resolve, reject) => { stream.on("end", () => { resolve(Buffer.concat(chunks)); }); stream.on("error", (error) => reject(error)); stream.on("data", (chunk) => { chunks.push(Buffer.from(chunk)); }); }); } exports.streamToBuffer = streamToBuffer; async function streamToHash(stream, hashAlgorithm) { return new Promise((resolve, reject) => { const hash = crypto.createHash(hashAlgorithm); hash.setEncoding(HASH_ENCODING); stream.on("end", () => { hash.end(); resolve(hash.read().toString(HASH_ENCODING)); }); stream.on("error", (error) => reject(error)); stream.pipe(hash); }); } async function streamToSha256(stream) { return streamToHash(stream, types_1.HashAlgorithm.Sha256); } exports.streamToSha256 = streamToSha256; async function streamToSha1(stream) { return streamToHash(stream, types_1.HashAlgorithm.Sha1); } exports.streamToSha1 = streamToSha1; /** * Reads up to 2 megabytes from the stream and tries to JSON.parse the result. * Will reject if an error occurs from within the stream or when parsing cannot be done. */ async function streamToJson(stream) { return new Promise((resolve, reject) => { const chunks = []; let bytes = 0; stream.on("end", () => { try { resolve(JSON.parse(chunks.join(""))); } catch (error) { reject(error); } }); stream.on("error", (error) => reject(error)); stream.on("data", (chunk) => { bytes += chunk.length; if (bytes <= 2 * MEGABYTE) { chunks.push(chunk.toString("utf8")); } else { reject(new Error("The stream is too large to parse as JSON")); } }); }); } exports.streamToJson = streamToJson; //# sourceMappingURL=stream-utils.js.map /***/ }), /***/ 15476: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.execute = void 0; const childProcess = __webpack_require__(32081); const shescape_1 = __webpack_require__(66710); function execute(command, args, options) { const spawnOptions = { shell: true, env: { ...process.env } }; if (options && options.cwd) { spawnOptions.cwd = options.cwd; } args = (0, shescape_1.quoteAll)(args, spawnOptions); // Before spawning an external process, we look if we need to restore the system proxy configuration, // which overides the cli internal proxy configuration. if (process.env.SNYK_SYSTEM_HTTP_PROXY !== undefined) { spawnOptions.env.HTTP_PROXY = process.env.SNYK_SYSTEM_HTTP_PROXY; } if (process.env.SNYK_SYSTEM_HTTPS_PROXY !== undefined) { spawnOptions.env.HTTPS_PROXY = process.env.SNYK_SYSTEM_HTTPS_PROXY; } if (process.env.SNYK_SYSTEM_NO_PROXY !== undefined) { spawnOptions.env.NO_PROXY = process.env.SNYK_SYSTEM_NO_PROXY; } return new Promise((resolve, reject) => { let stdout = ""; let stderr = ""; const proc = childProcess.spawn(command, args, spawnOptions); proc.stdout.on("data", (data) => { stdout = stdout + data; }); proc.stderr.on("data", (data) => { stderr = stderr + data; }); proc.on("close", (code) => { const output = { stdout, stderr }; if (code !== 0) { return reject(output); } resolve(output); }); }); } exports.execute = execute; //# sourceMappingURL=sub-process.js.map /***/ }), /***/ 93677: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UnresolvedDockerfileVariableHandling = exports.HashAlgorithm = exports.OsReleaseFilePath = exports.ImageType = void 0; var ImageType; (function (ImageType) { ImageType[ImageType["UnspecifiedArchiveType"] = 0] = "UnspecifiedArchiveType"; ImageType[ImageType["Identifier"] = 1] = "Identifier"; ImageType["DockerArchive"] = "docker-archive"; ImageType["OciArchive"] = "oci-archive"; ImageType["KanikoArchive"] = "kaniko-archive"; })(ImageType = exports.ImageType || (exports.ImageType = {})); var OsReleaseFilePath; (function (OsReleaseFilePath) { OsReleaseFilePath["Linux"] = "/etc/os-release"; OsReleaseFilePath["LinuxFallback"] = "/usr/lib/os-release"; OsReleaseFilePath["Lsb"] = "/etc/lsb-release"; OsReleaseFilePath["Debian"] = "/etc/debian_version"; OsReleaseFilePath["Alpine"] = "/etc/alpine-release"; OsReleaseFilePath["RedHat"] = "/etc/redhat-release"; OsReleaseFilePath["Oracle"] = "/etc/oracle-release"; OsReleaseFilePath["Centos"] = "/etc/centos-release"; })(OsReleaseFilePath = exports.OsReleaseFilePath || (exports.OsReleaseFilePath = {})); var HashAlgorithm; (function (HashAlgorithm) { HashAlgorithm["Sha256"] = "sha256"; HashAlgorithm["Sha1"] = "sha1"; })(HashAlgorithm = exports.HashAlgorithm || (exports.HashAlgorithm = {})); var UnresolvedDockerfileVariableHandling; (function (UnresolvedDockerfileVariableHandling) { UnresolvedDockerfileVariableHandling["Abort"] = "Abort"; UnresolvedDockerfileVariableHandling["Continue"] = "Continue"; })(UnresolvedDockerfileVariableHandling = exports.UnresolvedDockerfileVariableHandling || (exports.UnresolvedDockerfileVariableHandling = {})); //# sourceMappingURL=types.js.map /***/ }), /***/ 90215: /***/ ((module, exports, __webpack_require__) => { /* eslint-env browser */ /** * This is the web browser implementation of `debug()`. */ exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = localstorage(); exports.destroy = (() => { let warned = false; return () => { if (!warned) { warned = true; console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } }; })(); /** * Colors. */ exports.colors = [ '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ // eslint-disable-next-line complexity function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { return true; } // Internet Explorer and Edge do not support colors. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } let m; // Is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // Is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // Is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) || // Double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff); if (!this.useColors) { return; } const c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into let index = 0; let lastC = 0; args[0].replace(/%[a-zA-Z%]/g, match => { if (match === '%%') { return; } index++; if (match === '%c') { // We only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.debug()` when available. * No-op when `console.debug` is not a "function". * If `console.debug` is not available, falls back * to `console.log`. * * @api public */ exports.log = console.debug || console.log || (() => {}); /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (namespaces) { exports.storage.setItem('debug', namespaces); } else { exports.storage.removeItem('debug'); } } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { let r; try { r = exports.storage.getItem('debug'); } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context // The Browser also has localStorage in the global context. return localStorage; } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } module.exports = __webpack_require__(14647)(exports); const {formatters} = module.exports; /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ formatters.j = function (v) { try { return JSON.stringify(v); } catch (error) { return '[UnexpectedJSONParseError]: ' + error.message; } }; /***/ }), /***/ 14647: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. */ function setup(env) { createDebug.debug = createDebug; createDebug.default = createDebug; createDebug.coerce = coerce; createDebug.disable = disable; createDebug.enable = enable; createDebug.enabled = enabled; createDebug.humanize = __webpack_require__(86090); createDebug.destroy = destroy; Object.keys(env).forEach(key => { createDebug[key] = env[key]; }); /** * The currently active debug mode names, and names to skip. */ createDebug.names = []; createDebug.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ createDebug.formatters = {}; /** * Selects a color for a debug namespace * @param {String} namespace The namespace string for the debug instance to be colored * @return {Number|String} An ANSI color code for the given namespace * @api private */ function selectColor(namespace) { let hash = 0; for (let i = 0; i < namespace.length; i++) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; } createDebug.selectColor = selectColor; /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { let prevTime; let enableOverride = null; let namespacesCache; let enabledCache; function debug(...args) { // Disabled? if (!debug.enabled) { return; } const self = debug; // Set `diff` timestamp const curr = Number(new Date()); const ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; args[0] = createDebug.coerce(args[0]); if (typeof args[0] !== 'string') { // Anything else let's inspect with %O args.unshift('%O'); } // Apply any `formatters` transformations let index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { // If we encounter an escaped % then don't increase the array index if (match === '%%') { return '%'; } index++; const formatter = createDebug.formatters[format]; if (typeof formatter === 'function') { const val = args[index]; match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // Apply env-specific formatting (colors, etc.) createDebug.formatArgs.call(self, args); const logFn = self.log || createDebug.log; logFn.apply(self, args); } debug.namespace = namespace; debug.useColors = createDebug.useColors(); debug.color = createDebug.selectColor(namespace); debug.extend = extend; debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. Object.defineProperty(debug, 'enabled', { enumerable: true, configurable: false, get: () => { if (enableOverride !== null) { return enableOverride; } if (namespacesCache !== createDebug.namespaces) { namespacesCache = createDebug.namespaces; enabledCache = createDebug.enabled(namespace); } return enabledCache; }, set: v => { enableOverride = v; } }); // Env-specific initialization logic for debug instances if (typeof createDebug.init === 'function') { createDebug.init(debug); } return debug; } function extend(namespace, delimiter) { const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); newDebug.log = this.log; return newDebug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { createDebug.save(namespaces); createDebug.namespaces = namespaces; createDebug.names = []; createDebug.skips = []; let i; const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); const len = split.length; for (i = 0; i < len; i++) { if (!split[i]) { // ignore empty strings continue; } namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); } else { createDebug.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @return {String} namespaces * @api public */ function disable() { const namespaces = [ ...createDebug.names.map(toNamespace), ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) ].join(','); createDebug.enable(''); return namespaces; } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { if (name[name.length - 1] === '*') { return true; } let i; let len; for (i = 0, len = createDebug.skips.length; i < len; i++) { if (createDebug.skips[i].test(name)) { return false; } } for (i = 0, len = createDebug.names.length; i < len; i++) { if (createDebug.names[i].test(name)) { return true; } } return false; } /** * Convert regexp to namespace * * @param {RegExp} regxep * @return {String} namespace * @api private */ function toNamespace(regexp) { return regexp.toString() .substring(2, regexp.toString().length - 2) .replace(/\.\*\?$/, '*'); } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) { return val.stack || val.message; } return val; } /** * XXX DO NOT USE. This is a temporary stub function. * XXX It WILL be removed in the next major release. */ function destroy() { console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } createDebug.enable(createDebug.load()); return createDebug; } module.exports = setup; /***/ }), /***/ 6807: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /** * Detect Electron renderer / nwjs process, which is node, but we should * treat as a browser. */ if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { module.exports = __webpack_require__(90215); } else { module.exports = __webpack_require__(39629); } /***/ }), /***/ 39629: /***/ ((module, exports, __webpack_require__) => { /** * Module dependencies. */ const tty = __webpack_require__(76224); const util = __webpack_require__(73837); /** * This is the Node.js implementation of `debug()`. */ exports.init = init; exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.destroy = util.deprecate( () => {}, 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' ); /** * Colors. */ exports.colors = [6, 2, 3, 4, 5, 1]; try { // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) // eslint-disable-next-line import/no-extraneous-dependencies const supportsColor = __webpack_require__(92130); if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { exports.colors = [ 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221 ]; } } catch (error) { // Swallow - we only care if `supports-color` is available; it doesn't have to be. } /** * Build up the default `inspectOpts` object from the environment variables. * * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ exports.inspectOpts = Object.keys(process.env).filter(key => { return /^debug_/i.test(key); }).reduce((obj, key) => { // Camel-case const prop = key .substring(6) .toLowerCase() .replace(/_([a-z])/g, (_, k) => { return k.toUpperCase(); }); // Coerce string value into JS value let val = process.env[key]; if (/^(yes|on|true|enabled)$/i.test(val)) { val = true; } else if (/^(no|off|false|disabled)$/i.test(val)) { val = false; } else if (val === 'null') { val = null; } else { val = Number(val); } obj[prop] = val; return obj; }, {}); /** * Is stdout a TTY? Colored output is enabled when `true`. */ function useColors() { return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); } /** * Adds ANSI color escape codes if enabled. * * @api public */ function formatArgs(args) { const {namespace: name, useColors} = this; if (useColors) { const c = this.color; const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); const prefix = ` ${colorCode};1m${name} \u001B[0m`; args[0] = prefix + args[0].split('\n').join('\n' + prefix); args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); } else { args[0] = getDate() + name + ' ' + args[0]; } } function getDate() { if (exports.inspectOpts.hideDate) { return ''; } return new Date().toISOString() + ' '; } /** * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr. */ function log(...args) { return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n'); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { if (namespaces) { process.env.DEBUG = namespaces; } else { // If you set a process.env field to null or undefined, it gets cast to the // string 'null' or 'undefined'. Just delete instead. delete process.env.DEBUG; } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { return process.env.DEBUG; } /** * Init logic for `debug` instances. * * Create a new `inspectOpts` object in case `useColors` is set * differently for a particular `debug` instance. */ function init(debug) { debug.inspectOpts = {}; const keys = Object.keys(exports.inspectOpts); for (let i = 0; i < keys.length; i++) { debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; } } module.exports = __webpack_require__(14647)(exports); const {formatters} = module.exports; /** * Map %o to `util.inspect()`, all on a single line. */ formatters.o = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts) .split('\n') .map(str => str.trim()) .join(' '); }; /** * Map %O to `util.inspect()`, allowing multiple lines if needed. */ formatters.O = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts); }; /***/ }), /***/ 38545: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const optsArg = __webpack_require__(82825) const pathArg = __webpack_require__(30348) const {mkdirpNative, mkdirpNativeSync} = __webpack_require__(55251) const {mkdirpManual, mkdirpManualSync} = __webpack_require__(97808) const {useNative, useNativeSync} = __webpack_require__(54181) const mkdirp = (path, opts) => { path = pathArg(path) opts = optsArg(opts) return useNative(opts) ? mkdirpNative(path, opts) : mkdirpManual(path, opts) } const mkdirpSync = (path, opts) => { path = pathArg(path) opts = optsArg(opts) return useNativeSync(opts) ? mkdirpNativeSync(path, opts) : mkdirpManualSync(path, opts) } mkdirp.sync = mkdirpSync mkdirp.native = (path, opts) => mkdirpNative(pathArg(path), optsArg(opts)) mkdirp.manual = (path, opts) => mkdirpManual(pathArg(path), optsArg(opts)) mkdirp.nativeSync = (path, opts) => mkdirpNativeSync(pathArg(path), optsArg(opts)) mkdirp.manualSync = (path, opts) => mkdirpManualSync(pathArg(path), optsArg(opts)) module.exports = mkdirp /***/ }), /***/ 94032: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const {dirname} = __webpack_require__(71017) const findMade = (opts, parent, path = undefined) => { // we never want the 'made' return value to be a root directory if (path === parent) return Promise.resolve() return opts.statAsync(parent).then( st => st.isDirectory() ? path : undefined, // will fail later er => er.code === 'ENOENT' ? findMade(opts, dirname(parent), parent) : undefined ) } const findMadeSync = (opts, parent, path = undefined) => { if (path === parent) return undefined try { return opts.statSync(parent).isDirectory() ? path : undefined } catch (er) { return er.code === 'ENOENT' ? findMadeSync(opts, dirname(parent), parent) : undefined } } module.exports = {findMade, findMadeSync} /***/ }), /***/ 97808: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const {dirname} = __webpack_require__(71017) const mkdirpManual = (path, opts, made) => { opts.recursive = false const parent = dirname(path) if (parent === path) { return opts.mkdirAsync(path, opts).catch(er => { // swallowed by recursive implementation on posix systems // any other error is a failure if (er.code !== 'EISDIR') throw er }) } return opts.mkdirAsync(path, opts).then(() => made || path, er => { if (er.code === 'ENOENT') return mkdirpManual(parent, opts) .then(made => mkdirpManual(path, opts, made)) if (er.code !== 'EEXIST' && er.code !== 'EROFS') throw er return opts.statAsync(path).then(st => { if (st.isDirectory()) return made else throw er }, () => { throw er }) }) } const mkdirpManualSync = (path, opts, made) => { const parent = dirname(path) opts.recursive = false if (parent === path) { try { return opts.mkdirSync(path, opts) } catch (er) { // swallowed by recursive implementation on posix systems // any other error is a failure if (er.code !== 'EISDIR') throw er else return } } try { opts.mkdirSync(path, opts) return made || path } catch (er) { if (er.code === 'ENOENT') return mkdirpManualSync(path, opts, mkdirpManualSync(parent, opts, made)) if (er.code !== 'EEXIST' && er.code !== 'EROFS') throw er try { if (!opts.statSync(path).isDirectory()) throw er } catch (_) { throw er } } } module.exports = {mkdirpManual, mkdirpManualSync} /***/ }), /***/ 55251: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const {dirname} = __webpack_require__(71017) const {findMade, findMadeSync} = __webpack_require__(94032) const {mkdirpManual, mkdirpManualSync} = __webpack_require__(97808) const mkdirpNative = (path, opts) => { opts.recursive = true const parent = dirname(path) if (parent === path) return opts.mkdirAsync(path, opts) return findMade(opts, path).then(made => opts.mkdirAsync(path, opts).then(() => made) .catch(er => { if (er.code === 'ENOENT') return mkdirpManual(path, opts) else throw er })) } const mkdirpNativeSync = (path, opts) => { opts.recursive = true const parent = dirname(path) if (parent === path) return opts.mkdirSync(path, opts) const made = findMadeSync(opts, path) try { opts.mkdirSync(path, opts) return made } catch (er) { if (er.code === 'ENOENT') return mkdirpManualSync(path, opts) else throw er } } module.exports = {mkdirpNative, mkdirpNativeSync} /***/ }), /***/ 82825: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const { promisify } = __webpack_require__(73837) const fs = __webpack_require__(57147) const optsArg = opts => { if (!opts) opts = { mode: 0o777, fs } else if (typeof opts === 'object') opts = { mode: 0o777, fs, ...opts } else if (typeof opts === 'number') opts = { mode: opts, fs } else if (typeof opts === 'string') opts = { mode: parseInt(opts, 8), fs } else throw new TypeError('invalid options argument') opts.mkdir = opts.mkdir || opts.fs.mkdir || fs.mkdir opts.mkdirAsync = promisify(opts.mkdir) opts.stat = opts.stat || opts.fs.stat || fs.stat opts.statAsync = promisify(opts.stat) opts.statSync = opts.statSync || opts.fs.statSync || fs.statSync opts.mkdirSync = opts.mkdirSync || opts.fs.mkdirSync || fs.mkdirSync return opts } module.exports = optsArg /***/ }), /***/ 30348: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const platform = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform const { resolve, parse } = __webpack_require__(71017) const pathArg = path => { if (/\0/.test(path)) { // simulate same failure that node raises throw Object.assign( new TypeError('path must be a string without null bytes'), { path, code: 'ERR_INVALID_ARG_VALUE', } ) } path = resolve(path) if (platform === 'win32') { const badWinChars = /[*|"<>?:]/ const {root} = parse(path) if (badWinChars.test(path.substr(root.length))) { throw Object.assign(new Error('Illegal characters in path.'), { path, code: 'EINVAL', }) } } return path } module.exports = pathArg /***/ }), /***/ 54181: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const fs = __webpack_require__(57147) const version = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version const versArr = version.replace(/^v/, '').split('.') const hasNative = +versArr[0] > 10 || +versArr[0] === 10 && +versArr[1] >= 12 const useNative = !hasNative ? () => false : opts => opts.mkdir === fs.mkdir const useNativeSync = !hasNative ? () => false : opts => opts.mkdirSync === fs.mkdirSync module.exports = {useNative, useNativeSync} /***/ }), /***/ 86090: /***/ ((module) => { /** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var w = d * 7; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function (val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse(val); } else if (type === 'number' && isFinite(val)) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str); if (str.length > 100) { return; } var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'weeks': case 'week': case 'w': return n * w; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return Math.round(ms / d) + 'd'; } if (msAbs >= h) { return Math.round(ms / h) + 'h'; } if (msAbs >= m) { return Math.round(ms / m) + 'm'; } if (msAbs >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return plural(ms, msAbs, d, 'day'); } if (msAbs >= h) { return plural(ms, msAbs, h, 'hour'); } if (msAbs >= m) { return plural(ms, msAbs, m, 'minute'); } if (msAbs >= s) { return plural(ms, msAbs, s, 'second'); } return ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, msAbs, n, name) { var isPlural = msAbs >= n * 1.5; return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); } /***/ }), /***/ 60377: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const ANY = Symbol('SemVer ANY') // hoisted class for cyclic dependency class Comparator { static get ANY () { return ANY } constructor (comp, options) { options = parseOptions(options) if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } comp = comp.trim().split(/\s+/).join(' ') debug('comparator', comp, options) this.options = options this.loose = !!options.loose this.parse(comp) if (this.semver === ANY) { this.value = '' } else { this.value = this.operator + this.semver.version } debug('comp', this) } parse (comp) { const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] const m = comp.match(r) if (!m) { throw new TypeError(`Invalid comparator: ${comp}`) } this.operator = m[1] !== undefined ? m[1] : '' if (this.operator === '=') { this.operator = '' } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY } else { this.semver = new SemVer(m[2], this.options.loose) } } toString () { return this.value } test (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY || version === ANY) { return true } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } return cmp(version, this.operator, this.semver, this.options) } intersects (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (this.operator === '') { if (this.value === '') { return true } return new Range(comp.value, options).test(this.value) } else if (comp.operator === '') { if (comp.value === '') { return true } return new Range(this.value, options).test(comp.semver) } options = parseOptions(options) // Special cases where nothing can possibly be lower if (options.includePrerelease && (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { return false } if (!options.includePrerelease && (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { return false } // Same direction increasing (> or >=) if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { return true } // Same direction decreasing (< or <=) if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { return true } // same SemVer and both sides are inclusive (<= or >=) if ( (this.semver.version === comp.semver.version) && this.operator.includes('=') && comp.operator.includes('=')) { return true } // opposite directions less than if (cmp(this.semver, '<', comp.semver, options) && this.operator.startsWith('>') && comp.operator.startsWith('<')) { return true } // opposite directions greater than if (cmp(this.semver, '>', comp.semver, options) && this.operator.startsWith('<') && comp.operator.startsWith('>')) { return true } return false } } module.exports = Comparator const parseOptions = __webpack_require__(40932) const { safeRe: re, t } = __webpack_require__(92805) const cmp = __webpack_require__(36650) const debug = __webpack_require__(25078) const SemVer = __webpack_require__(96769) const Range = __webpack_require__(4142) /***/ }), /***/ 4142: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SPACE_CHARACTERS = /\s+/g // hoisted class for cyclic dependency class Range { constructor (range, options) { options = parseOptions(options) if (range instanceof Range) { if ( range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease ) { return range } else { return new Range(range.raw, options) } } if (range instanceof Comparator) { // just put it in the set and return this.raw = range.value this.set = [[range]] this.formatted = undefined return this } this.options = options this.loose = !!options.loose this.includePrerelease = !!options.includePrerelease // First reduce all whitespace as much as possible so we do not have to rely // on potentially slow regexes like \s*. This is then stored and used for // future error messages as well. this.raw = range.trim().replace(SPACE_CHARACTERS, ' ') // First, split on || this.set = this.raw .split('||') // map the range to a 2d array of comparators .map(r => this.parseRange(r.trim())) // throw out any comparator lists that are empty // this generally means that it was not a valid range, which is allowed // in loose mode, but will still throw if the WHOLE range is invalid. .filter(c => c.length) if (!this.set.length) { throw new TypeError(`Invalid SemVer Range: ${this.raw}`) } // if we have any that are not the null set, throw out null sets. if (this.set.length > 1) { // keep the first one, in case they're all null sets const first = this.set[0] this.set = this.set.filter(c => !isNullSet(c[0])) if (this.set.length === 0) { this.set = [first] } else if (this.set.length > 1) { // if we have any that are *, then the range is just * for (const c of this.set) { if (c.length === 1 && isAny(c[0])) { this.set = [c] break } } } } this.formatted = undefined } get range () { if (this.formatted === undefined) { this.formatted = '' for (let i = 0; i < this.set.length; i++) { if (i > 0) { this.formatted += '||' } const comps = this.set[i] for (let k = 0; k < comps.length; k++) { if (k > 0) { this.formatted += ' ' } this.formatted += comps[k].toString().trim() } } } return this.formatted } format () { return this.range } toString () { return this.range } parseRange (range) { // memoize range parsing for performance. // this is a very hot path, and fully deterministic. const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE) const memoKey = memoOpts + ':' + range const cached = cache.get(memoKey) if (cached) { return cached } const loose = this.options.loose // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range) // `~ 1.2.3` => `~1.2.3` range = range.replace(re[t.TILDETRIM], tildeTrimReplace) debug('tilde trim', range) // `^ 1.2.3` => `^1.2.3` range = range.replace(re[t.CARETTRIM], caretTrimReplace) debug('caret trim', range) // At this point, the range is completely trimmed and // ready to be split into comparators. let rangeList = range .split(' ') .map(comp => parseComparator(comp, this.options)) .join(' ') .split(/\s+/) // >=0.0.0 is equivalent to * .map(comp => replaceGTE0(comp, this.options)) if (loose) { // in loose mode, throw out any that are not valid comparators rangeList = rangeList.filter(comp => { debug('loose invalid filter', comp, this.options) return !!comp.match(re[t.COMPARATORLOOSE]) }) } debug('range list', rangeList) // if any comparators are the null set, then replace with JUST null set // if more than one comparator, remove any * comparators // also, don't include the same comparator more than once const rangeMap = new Map() const comparators = rangeList.map(comp => new Comparator(comp, this.options)) for (const comp of comparators) { if (isNullSet(comp)) { return [comp] } rangeMap.set(comp.value, comp) } if (rangeMap.size > 1 && rangeMap.has('')) { rangeMap.delete('') } const result = [...rangeMap.values()] cache.set(memoKey, result) return result } intersects (range, options) { if (!(range instanceof Range)) { throw new TypeError('a Range is required') } return this.set.some((thisComparators) => { return ( isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => { return ( isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { return rangeComparators.every((rangeComparator) => { return thisComparator.intersects(rangeComparator, options) }) }) ) }) ) }) } // if ANY of the sets match ALL of its comparators, then pass test (version) { if (!version) { return false } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } for (let i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true } } return false } } module.exports = Range const LRU = __webpack_require__(99252) const cache = new LRU() const parseOptions = __webpack_require__(40932) const Comparator = __webpack_require__(60377) const debug = __webpack_require__(25078) const SemVer = __webpack_require__(96769) const { safeRe: re, t, comparatorTrimReplace, tildeTrimReplace, caretTrimReplace, } = __webpack_require__(92805) const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __webpack_require__(32094) const isNullSet = c => c.value === '<0.0.0-0' const isAny = c => c.value === '' // take a set of comparators and determine whether there // exists a version which can satisfy it const isSatisfiable = (comparators, options) => { let result = true const remainingComparators = comparators.slice() let testComparator = remainingComparators.pop() while (result && remainingComparators.length) { result = remainingComparators.every((otherComparator) => { return testComparator.intersects(otherComparator, options) }) testComparator = remainingComparators.pop() } return result } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. const parseComparator = (comp, options) => { debug('comp', comp, options) comp = replaceCarets(comp, options) debug('caret', comp) comp = replaceTildes(comp, options) debug('tildes', comp) comp = replaceXRanges(comp, options) debug('xrange', comp) comp = replaceStars(comp, options) debug('stars', comp) return comp } const isX = id => !id || id.toLowerCase() === 'x' || id === '*' // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 // ~0.0.1 --> >=0.0.1 <0.1.0-0 const replaceTildes = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceTilde(c, options)) .join(' ') } const replaceTilde = (comp, options) => { const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] return comp.replace(r, (_, M, m, p, pr) => { debug('tilde', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0 <${+M + 1}.0.0-0` } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0-0 ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` } else if (pr) { debug('replaceTilde pr', pr) ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } else { // ~1.2.3 == >=1.2.3 <1.3.0-0 ret = `>=${M}.${m}.${p } <${M}.${+m + 1}.0-0` } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 // ^1.2.3 --> >=1.2.3 <2.0.0-0 // ^1.2.0 --> >=1.2.0 <2.0.0-0 // ^0.0.1 --> >=0.0.1 <0.0.2-0 // ^0.1.0 --> >=0.1.0 <0.2.0-0 const replaceCarets = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceCaret(c, options)) .join(' ') } const replaceCaret = (comp, options) => { debug('caret', comp, options) const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] const z = options.includePrerelease ? '-0' : '' return comp.replace(r, (_, M, m, p, pr) => { debug('caret', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` } else if (isX(p)) { if (M === '0') { ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` } else { ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p}-${pr } <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p}-${pr } <${+M + 1}.0.0-0` } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p }${z} <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p }${z} <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p } <${+M + 1}.0.0-0` } } debug('caret return', ret) return ret }) } const replaceXRanges = (comp, options) => { debug('replaceXRanges', comp, options) return comp .split(/\s+/) .map((c) => replaceXRange(c, options)) .join(' ') } const replaceXRange = (comp, options) => { comp = comp.trim() const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] return comp.replace(r, (ret, gtlt, M, m, p, pr) => { debug('xRange', comp, ret, gtlt, M, m, p, pr) const xM = isX(M) const xm = xM || isX(m) const xp = xm || isX(p) const anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } // if we're including prereleases in the match, then we need // to fix this to -0, the lowest possible prerelease value pr = options.includePrerelease ? '-0' : '' if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0-0' } else { // nothing is forbidden ret = '*' } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0 } p = 0 if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 gtlt = '>=' if (xm) { M = +M + 1 m = 0 p = 0 } else { m = +m + 1 p = 0 } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<' if (xm) { M = +M + 1 } else { m = +m + 1 } } if (gtlt === '<') { pr = '-0' } ret = `${gtlt + M}.${m}.${p}${pr}` } else if (xm) { ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` } else if (xp) { ret = `>=${M}.${m}.0${pr } <${M}.${+m + 1}.0-0` } debug('xRange return', ret) return ret }) } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. const replaceStars = (comp, options) => { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp .trim() .replace(re[t.STAR], '') } const replaceGTE0 = (comp, options) => { debug('replaceGTE0', comp, options) return comp .trim() .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') } // This function is passed to string.replace(re[t.HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 // TODO build? const hyphenReplace = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => { if (isX(fM)) { from = '' } else if (isX(fm)) { from = `>=${fM}.0.0${incPr ? '-0' : ''}` } else if (isX(fp)) { from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` } else if (fpr) { from = `>=${from}` } else { from = `>=${from}${incPr ? '-0' : ''}` } if (isX(tM)) { to = '' } else if (isX(tm)) { to = `<${+tM + 1}.0.0-0` } else if (isX(tp)) { to = `<${tM}.${+tm + 1}.0-0` } else if (tpr) { to = `<=${tM}.${tm}.${tp}-${tpr}` } else if (incPr) { to = `<${tM}.${tm}.${+tp + 1}-0` } else { to = `<=${to}` } return `${from} ${to}`.trim() } const testSet = (set, version, options) => { for (let i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (let i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === Comparator.ANY) { continue } if (set[i].semver.prerelease.length > 0) { const allowed = set[i].semver if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } /***/ }), /***/ 96769: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const debug = __webpack_require__(25078) const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(32094) const { safeRe: re, t } = __webpack_require__(92805) const parseOptions = __webpack_require__(40932) const { compareIdentifiers } = __webpack_require__(81960) class SemVer { constructor (version, options) { options = parseOptions(options) if (version instanceof SemVer) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) } if (version.length > MAX_LENGTH) { throw new TypeError( `version is longer than ${MAX_LENGTH} characters` ) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose // this isn't actually relevant for versions, but keep it so that we // don't run into trouble passing this.options around. this.includePrerelease = !!options.includePrerelease const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) if (!m) { throw new TypeError(`Invalid Version: ${version}`) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map((id) => { if (/^[0-9]+$/.test(id)) { const num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } format () { this.version = `${this.major}.${this.minor}.${this.patch}` if (this.prerelease.length) { this.version += `-${this.prerelease.join('.')}` } return this.version } toString () { return this.version } compare (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { if (typeof other === 'string' && other === this.version) { return 0 } other = new SemVer(other, this.options) } if (other.version === this.version) { return 0 } return this.compareMain(other) || this.comparePre(other) } compareMain (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return ( compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) ) } comparePre (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } let i = 0 do { const a = this.prerelease[i] const b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } compareBuild (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } let i = 0 do { const a = this.build[i] const b = other.build[i] debug('build compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc (release, identifier, identifierBase) { switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier, identifierBase) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier, identifierBase) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier, identifierBase) this.inc('pre', identifier, identifierBase) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier, identifierBase) } this.inc('pre', identifier, identifierBase) break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if ( this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0 ) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. case 'pre': { const base = Number(identifierBase) ? 1 : 0 if (!identifier && identifierBase === false) { throw new Error('invalid increment argument: identifier is empty') } if (this.prerelease.length === 0) { this.prerelease = [base] } else { let i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything if (identifier === this.prerelease.join('.') && identifierBase === false) { throw new Error('invalid increment argument: identifier already exists') } this.prerelease.push(base) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 let prerelease = [identifier, base] if (identifierBase === false) { prerelease = [identifier] } if (compareIdentifiers(this.prerelease[0], identifier) === 0) { if (isNaN(this.prerelease[1])) { this.prerelease = prerelease } } else { this.prerelease = prerelease } } break } default: throw new Error(`invalid increment argument: ${release}`) } this.raw = this.format() if (this.build.length) { this.raw += `+${this.build.join('.')}` } return this } } module.exports = SemVer /***/ }), /***/ 48602: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(763) const clean = (version, options) => { const s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } module.exports = clean /***/ }), /***/ 36650: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const eq = __webpack_require__(17771) const neq = __webpack_require__(81945) const gt = __webpack_require__(39477) const gte = __webpack_require__(64501) const lt = __webpack_require__(7897) const lte = __webpack_require__(61858) const cmp = (a, op, b, loose) => { switch (op) { case '===': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a === b case '!==': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError(`Invalid operator: ${op}`) } } module.exports = cmp /***/ }), /***/ 35753: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(96769) const parse = __webpack_require__(763) const { safeRe: re, t } = __webpack_require__(92805) const coerce = (version, options) => { if (version instanceof SemVer) { return version } if (typeof version === 'number') { version = String(version) } if (typeof version !== 'string') { return null } options = options || {} let match = null if (!options.rtl) { match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]) } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4' // // Walk through the string checking with a /g regexp // Manually set the index so as to pick up overlapping matches. // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL] let next while ((next = coerceRtlRegex.exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next } coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length } // leave it in a clean state coerceRtlRegex.lastIndex = -1 } if (match === null) { return null } const major = match[2] const minor = match[3] || '0' const patch = match[4] || '0' const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '' const build = options.includePrerelease && match[6] ? `+${match[6]}` : '' return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options) } module.exports = coerce /***/ }), /***/ 92830: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(96769) const compareBuild = (a, b, loose) => { const versionA = new SemVer(a, loose) const versionB = new SemVer(b, loose) return versionA.compare(versionB) || versionA.compareBuild(versionB) } module.exports = compareBuild /***/ }), /***/ 57590: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(75359) const compareLoose = (a, b) => compare(a, b, true) module.exports = compareLoose /***/ }), /***/ 75359: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(96769) const compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)) module.exports = compare /***/ }), /***/ 73013: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(763) const diff = (version1, version2) => { const v1 = parse(version1, null, true) const v2 = parse(version2, null, true) const comparison = v1.compare(v2) if (comparison === 0) { return null } const v1Higher = comparison > 0 const highVersion = v1Higher ? v1 : v2 const lowVersion = v1Higher ? v2 : v1 const highHasPre = !!highVersion.prerelease.length const lowHasPre = !!lowVersion.prerelease.length if (lowHasPre && !highHasPre) { // Going from prerelease -> no prerelease requires some special casing // If the low version has only a major, then it will always be a major // Some examples: // 1.0.0-1 -> 1.0.0 // 1.0.0-1 -> 1.1.1 // 1.0.0-1 -> 2.0.0 if (!lowVersion.patch && !lowVersion.minor) { return 'major' } // Otherwise it can be determined by checking the high version if (highVersion.patch) { // anything higher than a patch bump would result in the wrong version return 'patch' } if (highVersion.minor) { // anything higher than a minor bump would result in the wrong version return 'minor' } // bumping major/minor/patch all have same result return 'major' } // add the `pre` prefix if we are going to a prerelease version const prefix = highHasPre ? 'pre' : '' if (v1.major !== v2.major) { return prefix + 'major' } if (v1.minor !== v2.minor) { return prefix + 'minor' } if (v1.patch !== v2.patch) { return prefix + 'patch' } // high and low are preleases return 'prerelease' } module.exports = diff /***/ }), /***/ 17771: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(75359) const eq = (a, b, loose) => compare(a, b, loose) === 0 module.exports = eq /***/ }), /***/ 39477: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(75359) const gt = (a, b, loose) => compare(a, b, loose) > 0 module.exports = gt /***/ }), /***/ 64501: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(75359) const gte = (a, b, loose) => compare(a, b, loose) >= 0 module.exports = gte /***/ }), /***/ 78510: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(96769) const inc = (version, release, options, identifier, identifierBase) => { if (typeof (options) === 'string') { identifierBase = identifier identifier = options options = undefined } try { return new SemVer( version instanceof SemVer ? version.version : version, options ).inc(release, identifier, identifierBase).version } catch (er) { return null } } module.exports = inc /***/ }), /***/ 7897: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(75359) const lt = (a, b, loose) => compare(a, b, loose) < 0 module.exports = lt /***/ }), /***/ 61858: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(75359) const lte = (a, b, loose) => compare(a, b, loose) <= 0 module.exports = lte /***/ }), /***/ 72202: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(96769) const major = (a, loose) => new SemVer(a, loose).major module.exports = major /***/ }), /***/ 75800: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(96769) const minor = (a, loose) => new SemVer(a, loose).minor module.exports = minor /***/ }), /***/ 81945: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(75359) const neq = (a, b, loose) => compare(a, b, loose) !== 0 module.exports = neq /***/ }), /***/ 763: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(96769) const parse = (version, options, throwErrors = false) => { if (version instanceof SemVer) { return version } try { return new SemVer(version, options) } catch (er) { if (!throwErrors) { return null } throw er } } module.exports = parse /***/ }), /***/ 45844: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(96769) const patch = (a, loose) => new SemVer(a, loose).patch module.exports = patch /***/ }), /***/ 51436: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(763) const prerelease = (version, options) => { const parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } module.exports = prerelease /***/ }), /***/ 55809: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(75359) const rcompare = (a, b, loose) => compare(b, a, loose) module.exports = rcompare /***/ }), /***/ 14475: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(92830) const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) module.exports = rsort /***/ }), /***/ 33710: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(4142) const satisfies = (version, range, options) => { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } module.exports = satisfies /***/ }), /***/ 61776: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(92830) const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) module.exports = sort /***/ }), /***/ 3555: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(763) const valid = (version, options) => { const v = parse(version, options) return v ? v.version : null } module.exports = valid /***/ }), /***/ 41009: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // just pre-load all the stuff that index.js lazily exports const internalRe = __webpack_require__(92805) const constants = __webpack_require__(32094) const SemVer = __webpack_require__(96769) const identifiers = __webpack_require__(81960) const parse = __webpack_require__(763) const valid = __webpack_require__(3555) const clean = __webpack_require__(48602) const inc = __webpack_require__(78510) const diff = __webpack_require__(73013) const major = __webpack_require__(72202) const minor = __webpack_require__(75800) const patch = __webpack_require__(45844) const prerelease = __webpack_require__(51436) const compare = __webpack_require__(75359) const rcompare = __webpack_require__(55809) const compareLoose = __webpack_require__(57590) const compareBuild = __webpack_require__(92830) const sort = __webpack_require__(61776) const rsort = __webpack_require__(14475) const gt = __webpack_require__(39477) const lt = __webpack_require__(7897) const eq = __webpack_require__(17771) const neq = __webpack_require__(81945) const gte = __webpack_require__(64501) const lte = __webpack_require__(61858) const cmp = __webpack_require__(36650) const coerce = __webpack_require__(35753) const Comparator = __webpack_require__(60377) const Range = __webpack_require__(4142) const satisfies = __webpack_require__(33710) const toComparators = __webpack_require__(30885) const maxSatisfying = __webpack_require__(65496) const minSatisfying = __webpack_require__(9810) const minVersion = __webpack_require__(66324) const validRange = __webpack_require__(19495) const outside = __webpack_require__(65885) const gtr = __webpack_require__(76321) const ltr = __webpack_require__(196) const intersects = __webpack_require__(75713) const simplifyRange = __webpack_require__(87211) const subset = __webpack_require__(66043) module.exports = { parse, valid, clean, inc, diff, major, minor, patch, prerelease, compare, rcompare, compareLoose, compareBuild, sort, rsort, gt, lt, eq, neq, gte, lte, cmp, coerce, Comparator, Range, satisfies, toComparators, maxSatisfying, minSatisfying, minVersion, validRange, outside, gtr, ltr, intersects, simplifyRange, subset, SemVer, re: internalRe.re, src: internalRe.src, tokens: internalRe.t, SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, RELEASE_TYPES: constants.RELEASE_TYPES, compareIdentifiers: identifiers.compareIdentifiers, rcompareIdentifiers: identifiers.rcompareIdentifiers, } /***/ }), /***/ 32094: /***/ ((module) => { // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. const SEMVER_SPEC_VERSION = '2.0.0' const MAX_LENGTH = 256 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. const MAX_SAFE_COMPONENT_LENGTH = 16 // Max safe length for a build identifier. The max length minus 6 characters for // the shortest version with a build 0.0.0+BUILD. const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 const RELEASE_TYPES = [ 'major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease', ] module.exports = { MAX_LENGTH, MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_SAFE_INTEGER, RELEASE_TYPES, SEMVER_SPEC_VERSION, FLAG_INCLUDE_PRERELEASE: 0b001, FLAG_LOOSE: 0b010, } /***/ }), /***/ 25078: /***/ ((module) => { const debug = ( typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ) ? (...args) => console.error('SEMVER', ...args) : () => {} module.exports = debug /***/ }), /***/ 81960: /***/ ((module) => { const numeric = /^[0-9]+$/ const compareIdentifiers = (a, b) => { const anum = numeric.test(a) const bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) module.exports = { compareIdentifiers, rcompareIdentifiers, } /***/ }), /***/ 99252: /***/ ((module) => { class LRUCache { constructor () { this.max = 1000 this.map = new Map() } get (key) { const value = this.map.get(key) if (value === undefined) { return undefined } else { // Remove the key from the map and add it to the end this.map.delete(key) this.map.set(key, value) return value } } delete (key) { return this.map.delete(key) } set (key, value) { const deleted = this.delete(key) if (!deleted && value !== undefined) { // If cache is full, delete the least recently used item if (this.map.size >= this.max) { const firstKey = this.map.keys().next().value this.delete(firstKey) } this.map.set(key, value) } return this } } module.exports = LRUCache /***/ }), /***/ 40932: /***/ ((module) => { // parse out just the options we care about const looseOption = Object.freeze({ loose: true }) const emptyOpts = Object.freeze({ }) const parseOptions = options => { if (!options) { return emptyOpts } if (typeof options !== 'object') { return looseOption } return options } module.exports = parseOptions /***/ }), /***/ 92805: /***/ ((module, exports, __webpack_require__) => { const { MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_LENGTH, } = __webpack_require__(32094) const debug = __webpack_require__(25078) exports = module.exports = {} // The actual regexps go on exports.re const re = exports.re = [] const safeRe = exports.safeRe = [] const src = exports.src = [] const t = exports.t = {} let R = 0 const LETTERDASHNUMBER = '[a-zA-Z0-9-]' // Replace some greedy regex tokens to prevent regex dos issues. These regex are // used internally via the safeRe object since all inputs in this library get // normalized first to trim and collapse all extra whitespace. The original // regexes are exported for userland consumption and lower level usage. A // future breaking change could export the safer regex only with a note that // all input should have extra whitespace removed. const safeRegexReplacements = [ ['\\s', 1], ['\\d', MAX_LENGTH], [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], ] const makeSafeRegex = (value) => { for (const [token, max] of safeRegexReplacements) { value = value .split(`${token}*`).join(`${token}{0,${max}}`) .split(`${token}+`).join(`${token}{1,${max}}`) } return value } const createToken = (name, value, isGlobal) => { const safe = makeSafeRegex(value) const index = R++ debug(name, index, value) t[name] = index src[index] = value re[index] = new RegExp(value, isGlobal ? 'g' : undefined) safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) } // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') createToken('NUMERICIDENTIFIERLOOSE', '\\d+') // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) // ## Main Version // Three dot-separated numeric identifiers. createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`) createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] }|${src[t.NONNUMERICIDENTIFIER]})`) createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] }|${src[t.NONNUMERICIDENTIFIER]})`) // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] }(?:\\.${src[t.BUILDIDENTIFIER]})*))`) // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. createToken('FULLPLAIN', `v?${src[t.MAINVERSION] }${src[t.PRERELEASE]}?${ src[t.BUILD]}?`) createToken('FULL', `^${src[t.FULLPLAIN]}$`) // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] }${src[t.PRERELEASELOOSE]}?${ src[t.BUILD]}?`) createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) createToken('GTLT', '((?:<|>)?=?)') // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) // Coercion. // Extract anything that could conceivably be a part of a valid semver createToken('COERCEPLAIN', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`) createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`) createToken('COERCEFULL', src[t.COERCEPLAIN] + `(?:${src[t.PRERELEASE]})?` + `(?:${src[t.BUILD]})?` + `(?:$|[^\\d])`) createToken('COERCERTL', src[t.COERCE], true) createToken('COERCERTLFULL', src[t.COERCEFULL], true) // Tilde ranges. // Meaning is "reasonably at or greater than" createToken('LONETILDE', '(?:~>?)') createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) exports.tildeTrimReplace = '$1~' createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) // Caret ranges. // Meaning is "at least and backwards compatible with" createToken('LONECARET', '(?:\\^)') createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) exports.caretTrimReplace = '$1^' createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) // A simple gt/lt/eq thing, or just "" to indicate "any version" createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) exports.comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`) createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`) // Star ranges basically just allow anything at all. createToken('STAR', '(<|>)?=?\\s*\\*') // >=0.0.0 is like a star createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') /***/ }), /***/ 76321: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Determine if version is greater than all the versions possible in the range. const outside = __webpack_require__(65885) const gtr = (version, range, options) => outside(version, range, '>', options) module.exports = gtr /***/ }), /***/ 75713: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(4142) const intersects = (r1, r2, options) => { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2, options) } module.exports = intersects /***/ }), /***/ 196: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const outside = __webpack_require__(65885) // Determine if version is less than all the versions possible in the range const ltr = (version, range, options) => outside(version, range, '<', options) module.exports = ltr /***/ }), /***/ 65496: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(96769) const Range = __webpack_require__(4142) const maxSatisfying = (versions, range, options) => { let max = null let maxSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } module.exports = maxSatisfying /***/ }), /***/ 9810: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(96769) const Range = __webpack_require__(4142) const minSatisfying = (versions, range, options) => { let min = null let minSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } module.exports = minSatisfying /***/ }), /***/ 66324: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(96769) const Range = __webpack_require__(4142) const gt = __webpack_require__(39477) const minVersion = (range, loose) => { range = new Range(range, loose) let minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let setMin = null comparators.forEach((comparator) => { // Clone to avoid manipulating the comparator's semver object. const compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!setMin || gt(compver, setMin)) { setMin = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error(`Unexpected operation: ${comparator.operator}`) } }) if (setMin && (!minver || gt(minver, setMin))) { minver = setMin } } if (minver && range.test(minver)) { return minver } return null } module.exports = minVersion /***/ }), /***/ 65885: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(96769) const Comparator = __webpack_require__(60377) const { ANY } = Comparator const Range = __webpack_require__(4142) const satisfies = __webpack_require__(33710) const gt = __webpack_require__(39477) const lt = __webpack_require__(7897) const lte = __webpack_require__(61858) const gte = __webpack_require__(64501) const outside = (version, range, hilo, options) => { version = new SemVer(version, options) range = new Range(range, options) let gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisfies the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let high = null let low = null comparators.forEach((comparator) => { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } module.exports = outside /***/ }), /***/ 87211: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // given a set of versions and a range, create a "simplified" range // that includes the same versions that the original range does // If the original range is shorter than the simplified one, return that. const satisfies = __webpack_require__(33710) const compare = __webpack_require__(75359) module.exports = (versions, range, options) => { const set = [] let first = null let prev = null const v = versions.sort((a, b) => compare(a, b, options)) for (const version of v) { const included = satisfies(version, range, options) if (included) { prev = version if (!first) { first = version } } else { if (prev) { set.push([first, prev]) } prev = null first = null } } if (first) { set.push([first, null]) } const ranges = [] for (const [min, max] of set) { if (min === max) { ranges.push(min) } else if (!max && min === v[0]) { ranges.push('*') } else if (!max) { ranges.push(`>=${min}`) } else if (min === v[0]) { ranges.push(`<=${max}`) } else { ranges.push(`${min} - ${max}`) } } const simplified = ranges.join(' || ') const original = typeof range.raw === 'string' ? range.raw : String(range) return simplified.length < original.length ? simplified : range } /***/ }), /***/ 66043: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(4142) const Comparator = __webpack_require__(60377) const { ANY } = Comparator const satisfies = __webpack_require__(33710) const compare = __webpack_require__(75359) // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: // - Every simple range `r1, r2, ...` is a null set, OR // - Every simple range `r1, r2, ...` which is not a null set is a subset of // some `R1, R2, ...` // // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: // - If c is only the ANY comparator // - If C is only the ANY comparator, return true // - Else if in prerelease mode, return false // - else replace c with `[>=0.0.0]` // - If C is only the ANY comparator // - if in prerelease mode, return true // - else replace C with `[>=0.0.0]` // - Let EQ be the set of = comparators in c // - If EQ is more than one, return true (null set) // - Let GT be the highest > or >= comparator in c // - Let LT be the lowest < or <= comparator in c // - If GT and LT, and GT.semver > LT.semver, return true (null set) // - If any C is a = range, and GT or LT are set, return false // - If EQ // - If GT, and EQ does not satisfy GT, return true (null set) // - If LT, and EQ does not satisfy LT, return true (null set) // - If EQ satisfies every C, return true // - Else return false // - If GT // - If GT.semver is lower than any > or >= comp in C, return false // - If GT is >=, and GT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the GT.semver tuple, return false // - If LT // - If LT.semver is greater than any < or <= comp in C, return false // - If LT is <=, and LT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the LT.semver tuple, return false // - Else return true const subset = (sub, dom, options = {}) => { if (sub === dom) { return true } sub = new Range(sub, options) dom = new Range(dom, options) let sawNonNull = false OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { const isSub = simpleSubset(simpleSub, simpleDom, options) sawNonNull = sawNonNull || isSub !== null if (isSub) { continue OUTER } } // the null set is a subset of everything, but null simple ranges in // a complex range should be ignored. so if we saw a non-null range, // then we know this isn't a subset, but if EVERY simple range was null, // then it is a subset. if (sawNonNull) { return false } } return true } const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] const minimumVersion = [new Comparator('>=0.0.0')] const simpleSubset = (sub, dom, options) => { if (sub === dom) { return true } if (sub.length === 1 && sub[0].semver === ANY) { if (dom.length === 1 && dom[0].semver === ANY) { return true } else if (options.includePrerelease) { sub = minimumVersionWithPreRelease } else { sub = minimumVersion } } if (dom.length === 1 && dom[0].semver === ANY) { if (options.includePrerelease) { return true } else { dom = minimumVersion } } const eqSet = new Set() let gt, lt for (const c of sub) { if (c.operator === '>' || c.operator === '>=') { gt = higherGT(gt, c, options) } else if (c.operator === '<' || c.operator === '<=') { lt = lowerLT(lt, c, options) } else { eqSet.add(c.semver) } } if (eqSet.size > 1) { return null } let gtltComp if (gt && lt) { gtltComp = compare(gt.semver, lt.semver, options) if (gtltComp > 0) { return null } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { return null } } // will iterate one or zero times for (const eq of eqSet) { if (gt && !satisfies(eq, String(gt), options)) { return null } if (lt && !satisfies(eq, String(lt), options)) { return null } for (const c of dom) { if (!satisfies(eq, String(c), options)) { return false } } return true } let higher, lower let hasDomLT, hasDomGT // if the subset has a prerelease, we need a comparator in the superset // with the same tuple and a prerelease, or it's not a subset let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false // exception: <1.2.3-0 is the same as <1.2.3 if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { needDomLTPre = false } for (const c of dom) { hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' if (gt) { if (needDomGTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { needDomGTPre = false } } if (c.operator === '>' || c.operator === '>=') { higher = higherGT(gt, c, options) if (higher === c && higher !== gt) { return false } } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { return false } } if (lt) { if (needDomLTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { needDomLTPre = false } } if (c.operator === '<' || c.operator === '<=') { lower = lowerLT(lt, c, options) if (lower === c && lower !== lt) { return false } } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { return false } } if (!c.operator && (lt || gt) && gtltComp !== 0) { return false } } // if there was a < or >, and nothing in the dom, then must be false // UNLESS it was limited by another range in the other direction. // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 if (gt && hasDomLT && !lt && gtltComp !== 0) { return false } if (lt && hasDomGT && !gt && gtltComp !== 0) { return false } // we needed a prerelease range in a specific tuple, but didn't get one // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, // because it includes prereleases in the 1.2.3 tuple if (needDomGTPre || needDomLTPre) { return false } return true } // >=1.2.3 is lower than >1.2.3 const higherGT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp > 0 ? a : comp < 0 ? b : b.operator === '>' && a.operator === '>=' ? b : a } // <=1.2.3 is higher than <1.2.3 const lowerLT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp < 0 ? a : comp > 0 ? b : b.operator === '<' && a.operator === '<=' ? b : a } module.exports = subset /***/ }), /***/ 30885: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(4142) // Mostly just for testing and legacy API reasons const toComparators = (range, options) => new Range(range, options).set .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) module.exports = toComparators /***/ }), /***/ 19495: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(4142) const validRange = (range, options) => { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } module.exports = validRange /***/ }), /***/ 85816: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /*! * Tmp * * Copyright (c) 2011-2017 KARASZI Istvan * * MIT Licensed */ /* * Module dependencies. */ const fs = __webpack_require__(57147); const os = __webpack_require__(22037); const path = __webpack_require__(71017); const crypto = __webpack_require__(6113); const _c = { fs: fs.constants, os: os.constants }; /* * The working inner variables. */ const // the random characters to choose from RANDOM_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', TEMPLATE_PATTERN = /XXXXXX/, DEFAULT_TRIES = 3, CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR), // constants are off on the windows platform and will not match the actual errno codes IS_WIN32 = os.platform() === 'win32', EBADF = _c.EBADF || _c.os.errno.EBADF, ENOENT = _c.ENOENT || _c.os.errno.ENOENT, DIR_MODE = 0o700 /* 448 */, FILE_MODE = 0o600 /* 384 */, EXIT = 'exit', // this will hold the objects need to be removed on exit _removeObjects = [], // API change in fs.rmdirSync leads to error when passing in a second parameter, e.g. the callback FN_RMDIR_SYNC = fs.rmdirSync.bind(fs); let _gracefulCleanup = false; /** * Recursively remove a directory and its contents. * * @param {string} dirPath path of directory to remove * @param {Function} callback * @private */ function rimraf(dirPath, callback) { return fs.rm(dirPath, { recursive: true }, callback); } /** * Recursively remove a directory and its contents, synchronously. * * @param {string} dirPath path of directory to remove * @private */ function FN_RIMRAF_SYNC(dirPath) { return fs.rmSync(dirPath, { recursive: true }); } /** * Gets a temporary file name. * * @param {(Options|tmpNameCallback)} options options or callback * @param {?tmpNameCallback} callback the callback function */ function tmpName(options, callback) { const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; try { _assertAndSanitizeOptions(opts); } catch (err) { return cb(err); } let tries = opts.tries; (function _getUniqueName() { try { const name = _generateTmpName(opts); // check whether the path exists then retry if needed fs.stat(name, function (err) { /* istanbul ignore else */ if (!err) { /* istanbul ignore else */ if (tries-- > 0) return _getUniqueName(); return cb(new Error('Could not get a unique tmp filename, max tries reached ' + name)); } cb(null, name); }); } catch (err) { cb(err); } }()); } /** * Synchronous version of tmpName. * * @param {Object} options * @returns {string} the generated random name * @throws {Error} if the options are invalid or could not generate a filename */ function tmpNameSync(options) { const args = _parseArguments(options), opts = args[0]; _assertAndSanitizeOptions(opts); let tries = opts.tries; do { const name = _generateTmpName(opts); try { fs.statSync(name); } catch (e) { return name; } } while (tries-- > 0); throw new Error('Could not get a unique tmp filename, max tries reached'); } /** * Creates and opens a temporary file. * * @param {(Options|null|undefined|fileCallback)} options the config options or the callback function or null or undefined * @param {?fileCallback} callback */ function file(options, callback) { const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; // gets a temporary filename tmpName(opts, function _tmpNameCreated(err, name) { /* istanbul ignore else */ if (err) return cb(err); // create and open the file fs.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err, fd) { /* istanbu ignore else */ if (err) return cb(err); if (opts.discardDescriptor) { return fs.close(fd, function _discardCallback(possibleErr) { // the chance of getting an error on close here is rather low and might occur in the most edgiest cases only return cb(possibleErr, name, undefined, _prepareTmpFileRemoveCallback(name, -1, opts, false)); }); } else { // detachDescriptor passes the descriptor whereas discardDescriptor closes it, either way, we no longer care // about the descriptor const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; cb(null, name, fd, _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, false)); } }); }); } /** * Synchronous version of file. * * @param {Options} options * @returns {FileSyncObject} object consists of name, fd and removeCallback * @throws {Error} if cannot create a file */ function fileSync(options) { const args = _parseArguments(options), opts = args[0]; const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; const name = tmpNameSync(opts); var fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); /* istanbul ignore else */ if (opts.discardDescriptor) { fs.closeSync(fd); fd = undefined; } return { name: name, fd: fd, removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, true) }; } /** * Creates a temporary directory. * * @param {(Options|dirCallback)} options the options or the callback function * @param {?dirCallback} callback */ function dir(options, callback) { const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; // gets a temporary filename tmpName(opts, function _tmpNameCreated(err, name) { /* istanbul ignore else */ if (err) return cb(err); // create the directory fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err) { /* istanbul ignore else */ if (err) return cb(err); cb(null, name, _prepareTmpDirRemoveCallback(name, opts, false)); }); }); } /** * Synchronous version of dir. * * @param {Options} options * @returns {DirSyncObject} object consists of name and removeCallback * @throws {Error} if it cannot create a directory */ function dirSync(options) { const args = _parseArguments(options), opts = args[0]; const name = tmpNameSync(opts); fs.mkdirSync(name, opts.mode || DIR_MODE); return { name: name, removeCallback: _prepareTmpDirRemoveCallback(name, opts, true) }; } /** * Removes files asynchronously. * * @param {Object} fdPath * @param {Function} next * @private */ function _removeFileAsync(fdPath, next) { const _handler = function (err) { if (err && !_isENOENT(err)) { // reraise any unanticipated error return next(err); } next(); }; if (0 <= fdPath[0]) fs.close(fdPath[0], function () { fs.unlink(fdPath[1], _handler); }); else fs.unlink(fdPath[1], _handler); } /** * Removes files synchronously. * * @param {Object} fdPath * @private */ function _removeFileSync(fdPath) { let rethrownException = null; try { if (0 <= fdPath[0]) fs.closeSync(fdPath[0]); } catch (e) { // reraise any unanticipated error if (!_isEBADF(e) && !_isENOENT(e)) throw e; } finally { try { fs.unlinkSync(fdPath[1]); } catch (e) { // reraise any unanticipated error if (!_isENOENT(e)) rethrownException = e; } } if (rethrownException !== null) { throw rethrownException; } } /** * Prepares the callback for removal of the temporary file. * * Returns either a sync callback or a async callback depending on whether * fileSync or file was called, which is expressed by the sync parameter. * * @param {string} name the path of the file * @param {number} fd file descriptor * @param {Object} opts * @param {boolean} sync * @returns {fileCallback | fileCallbackSync} * @private */ function _prepareTmpFileRemoveCallback(name, fd, opts, sync) { const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name], sync); const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], sync, removeCallbackSync); if (!opts.keep) _removeObjects.unshift(removeCallbackSync); return sync ? removeCallbackSync : removeCallback; } /** * Prepares the callback for removal of the temporary directory. * * Returns either a sync callback or a async callback depending on whether * tmpFileSync or tmpFile was called, which is expressed by the sync parameter. * * @param {string} name * @param {Object} opts * @param {boolean} sync * @returns {Function} the callback * @private */ function _prepareTmpDirRemoveCallback(name, opts, sync) { const removeFunction = opts.unsafeCleanup ? rimraf : fs.rmdir.bind(fs); const removeFunctionSync = opts.unsafeCleanup ? FN_RIMRAF_SYNC : FN_RMDIR_SYNC; const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name, sync); const removeCallback = _prepareRemoveCallback(removeFunction, name, sync, removeCallbackSync); if (!opts.keep) _removeObjects.unshift(removeCallbackSync); return sync ? removeCallbackSync : removeCallback; } /** * Creates a guarded function wrapping the removeFunction call. * * The cleanup callback is save to be called multiple times. * Subsequent invocations will be ignored. * * @param {Function} removeFunction * @param {string} fileOrDirName * @param {boolean} sync * @param {cleanupCallbackSync?} cleanupCallbackSync * @returns {cleanupCallback | cleanupCallbackSync} * @private */ function _prepareRemoveCallback(removeFunction, fileOrDirName, sync, cleanupCallbackSync) { let called = false; // if sync is true, the next parameter will be ignored return function _cleanupCallback(next) { /* istanbul ignore else */ if (!called) { // remove cleanupCallback from cache const toRemove = cleanupCallbackSync || _cleanupCallback; const index = _removeObjects.indexOf(toRemove); /* istanbul ignore else */ if (index >= 0) _removeObjects.splice(index, 1); called = true; if (sync || removeFunction === FN_RMDIR_SYNC || removeFunction === FN_RIMRAF_SYNC) { return removeFunction(fileOrDirName); } else { return removeFunction(fileOrDirName, next || function() {}); } } }; } /** * The garbage collector. * * @private */ function _garbageCollector() { /* istanbul ignore else */ if (!_gracefulCleanup) return; // the function being called removes itself from _removeObjects, // loop until _removeObjects is empty while (_removeObjects.length) { try { _removeObjects[0](); } catch (e) { // already removed? } } } /** * Random name generator based on crypto. * Adapted from http://blog.tompawlak.org/how-to-generate-random-values-nodejs-javascript * * @param {number} howMany * @returns {string} the generated random name * @private */ function _randomChars(howMany) { let value = [], rnd = null; // make sure that we do not fail because we ran out of entropy try { rnd = crypto.randomBytes(howMany); } catch (e) { rnd = crypto.pseudoRandomBytes(howMany); } for (var i = 0; i < howMany; i++) { value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]); } return value.join(''); } /** * Helper which determines whether a string s is blank, that is undefined, or empty or null. * * @private * @param {string} s * @returns {Boolean} true whether the string s is blank, false otherwise */ function _isBlank(s) { return s === null || _isUndefined(s) || !s.trim(); } /** * Checks whether the `obj` parameter is defined or not. * * @param {Object} obj * @returns {boolean} true if the object is undefined * @private */ function _isUndefined(obj) { return typeof obj === 'undefined'; } /** * Parses the function arguments. * * This function helps to have optional arguments. * * @param {(Options|null|undefined|Function)} options * @param {?Function} callback * @returns {Array} parsed arguments * @private */ function _parseArguments(options, callback) { /* istanbul ignore else */ if (typeof options === 'function') { return [{}, options]; } /* istanbul ignore else */ if (_isUndefined(options)) { return [{}, callback]; } // copy options so we do not leak the changes we make internally const actualOptions = {}; for (const key of Object.getOwnPropertyNames(options)) { actualOptions[key] = options[key]; } return [actualOptions, callback]; } /** * Generates a new temporary name. * * @param {Object} opts * @returns {string} the new random name according to opts * @private */ function _generateTmpName(opts) { const tmpDir = opts.tmpdir; /* istanbul ignore else */ if (!_isUndefined(opts.name)) return path.join(tmpDir, opts.dir, opts.name); /* istanbul ignore else */ if (!_isUndefined(opts.template)) return path.join(tmpDir, opts.dir, opts.template).replace(TEMPLATE_PATTERN, _randomChars(6)); // prefix and postfix const name = [ opts.prefix ? opts.prefix : 'tmp', '-', process.pid, '-', _randomChars(12), opts.postfix ? '-' + opts.postfix : '' ].join(''); return path.join(tmpDir, opts.dir, name); } /** * Asserts whether the specified options are valid, also sanitizes options and provides sane defaults for missing * options. * * @param {Options} options * @private */ function _assertAndSanitizeOptions(options) { options.tmpdir = _getTmpDir(options); const tmpDir = options.tmpdir; /* istanbul ignore else */ if (!_isUndefined(options.name)) _assertIsRelative(options.name, 'name', tmpDir); /* istanbul ignore else */ if (!_isUndefined(options.dir)) _assertIsRelative(options.dir, 'dir', tmpDir); /* istanbul ignore else */ if (!_isUndefined(options.template)) { _assertIsRelative(options.template, 'template', tmpDir); if (!options.template.match(TEMPLATE_PATTERN)) throw new Error(`Invalid template, found "${options.template}".`); } /* istanbul ignore else */ if (!_isUndefined(options.tries) && isNaN(options.tries) || options.tries < 0) throw new Error(`Invalid tries, found "${options.tries}".`); // if a name was specified we will try once options.tries = _isUndefined(options.name) ? options.tries || DEFAULT_TRIES : 1; options.keep = !!options.keep; options.detachDescriptor = !!options.detachDescriptor; options.discardDescriptor = !!options.discardDescriptor; options.unsafeCleanup = !!options.unsafeCleanup; // sanitize dir, also keep (multiple) blanks if the user, purportedly sane, requests us to options.dir = _isUndefined(options.dir) ? '' : path.relative(tmpDir, _resolvePath(options.dir, tmpDir)); options.template = _isUndefined(options.template) ? undefined : path.relative(tmpDir, _resolvePath(options.template, tmpDir)); // sanitize further if template is relative to options.dir options.template = _isBlank(options.template) ? undefined : path.relative(options.dir, options.template); // for completeness' sake only, also keep (multiple) blanks if the user, purportedly sane, requests us to options.name = _isUndefined(options.name) ? undefined : options.name; options.prefix = _isUndefined(options.prefix) ? '' : options.prefix; options.postfix = _isUndefined(options.postfix) ? '' : options.postfix; } /** * Resolve the specified path name in respect to tmpDir. * * The specified name might include relative path components, e.g. ../ * so we need to resolve in order to be sure that is is located inside tmpDir * * @param name * @param tmpDir * @returns {string} * @private */ function _resolvePath(name, tmpDir) { if (name.startsWith(tmpDir)) { return path.resolve(name); } else { return path.resolve(path.join(tmpDir, name)); } } /** * Asserts whether specified name is relative to the specified tmpDir. * * @param {string} name * @param {string} option * @param {string} tmpDir * @throws {Error} * @private */ function _assertIsRelative(name, option, tmpDir) { if (option === 'name') { // assert that name is not absolute and does not contain a path if (path.isAbsolute(name)) throw new Error(`${option} option must not contain an absolute path, found "${name}".`); // must not fail on valid . or .. or similar such constructs let basename = path.basename(name); if (basename === '..' || basename === '.' || basename !== name) throw new Error(`${option} option must not contain a path, found "${name}".`); } else { // if (option === 'dir' || option === 'template') { // assert that dir or template are relative to tmpDir if (path.isAbsolute(name) && !name.startsWith(tmpDir)) { throw new Error(`${option} option must be relative to "${tmpDir}", found "${name}".`); } let resolvedPath = _resolvePath(name, tmpDir); if (!resolvedPath.startsWith(tmpDir)) throw new Error(`${option} option must be relative to "${tmpDir}", found "${resolvedPath}".`); } } /** * Helper for testing against EBADF to compensate changes made to Node 7.x under Windows. * * @private */ function _isEBADF(error) { return _isExpectedError(error, -EBADF, 'EBADF'); } /** * Helper for testing against ENOENT to compensate changes made to Node 7.x under Windows. * * @private */ function _isENOENT(error) { return _isExpectedError(error, -ENOENT, 'ENOENT'); } /** * Helper to determine whether the expected error code matches the actual code and errno, * which will differ between the supported node versions. * * - Node >= 7.0: * error.code {string} * error.errno {number} any numerical value will be negated * * CAVEAT * * On windows, the errno for EBADF is -4083 but os.constants.errno.EBADF is different and we must assume that ENOENT * is no different here. * * @param {SystemError} error * @param {number} errno * @param {string} code * @private */ function _isExpectedError(error, errno, code) { return IS_WIN32 ? error.code === code : error.code === code && error.errno === errno; } /** * Sets the graceful cleanup. * * If graceful cleanup is set, tmp will remove all controlled temporary objects on process exit, otherwise the * temporary objects will remain in place, waiting to be cleaned up on system restart or otherwise scheduled temporary * object removals. */ function setGracefulCleanup() { _gracefulCleanup = true; } /** * Returns the currently configured tmp dir from os.tmpdir(). * * @private * @param {?Options} options * @returns {string} the currently configured tmp dir */ function _getTmpDir(options) { return path.resolve(options && options.tmpdir || os.tmpdir()); } // Install process exit listener process.addListener(EXIT, _garbageCollector); /** * Configuration options. * * @typedef {Object} Options * @property {?boolean} keep the temporary object (file or dir) will not be garbage collected * @property {?number} tries the number of tries before give up the name generation * @property (?int) mode the access mode, defaults are 0o700 for directories and 0o600 for files * @property {?string} template the "mkstemp" like filename template * @property {?string} name fixed name relative to tmpdir or the specified dir option * @property {?string} dir tmp directory relative to the root tmp directory in use * @property {?string} prefix prefix for the generated name * @property {?string} postfix postfix for the generated name * @property {?string} tmpdir the root tmp directory which overrides the os tmpdir * @property {?boolean} unsafeCleanup recursively removes the created temporary directory, even when it's not empty * @property {?boolean} detachDescriptor detaches the file descriptor, caller is responsible for closing the file, tmp will no longer try closing the file during garbage collection * @property {?boolean} discardDescriptor discards the file descriptor (closes file, fd is -1), tmp will no longer try closing the file during garbage collection */ /** * @typedef {Object} FileSyncObject * @property {string} name the name of the file * @property {string} fd the file descriptor or -1 if the fd has been discarded * @property {fileCallback} removeCallback the callback function to remove the file */ /** * @typedef {Object} DirSyncObject * @property {string} name the name of the directory * @property {fileCallback} removeCallback the callback function to remove the directory */ /** * @callback tmpNameCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name */ /** * @callback fileCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {number} fd the file descriptor or -1 if the fd had been discarded * @param {cleanupCallback} fn the cleanup callback function */ /** * @callback fileCallbackSync * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {number} fd the file descriptor or -1 if the fd had been discarded * @param {cleanupCallbackSync} fn the cleanup callback function */ /** * @callback dirCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {cleanupCallback} fn the cleanup callback function */ /** * @callback dirCallbackSync * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {cleanupCallbackSync} fn the cleanup callback function */ /** * Removes the temporary created file or directory. * * @callback cleanupCallback * @param {simpleCallback} [next] function to call whenever the tmp object needs to be removed */ /** * Removes the temporary created file or directory. * * @callback cleanupCallbackSync */ /** * Callback function for function composition. * @see {@link https://github.com/raszi/node-tmp/issues/57|raszi/node-tmp#57} * * @callback simpleCallback */ // exporting all the needed methods // evaluate _getTmpDir() lazily, mainly for simplifying testing but it also will // allow users to reconfigure the temporary directory Object.defineProperty(module.exports, "tmpdir", ({ enumerable: true, configurable: false, get: function () { return _getTmpDir(); } })); module.exports.dir = dir; module.exports.dirSync = dirSync; module.exports.file = file; module.exports.fileSync = fileSync; module.exports.tmpName = tmpName; module.exports.tmpNameSync = tmpNameSync; module.exports.setGracefulCleanup = setGracefulCleanup; /***/ }), /***/ 81918: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const isWindows = process.platform === 'win32' || process.env.OSTYPE === 'cygwin' || process.env.OSTYPE === 'msys' const path = __webpack_require__(71017) const COLON = isWindows ? ';' : ':' const isexe = __webpack_require__(31959) const getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }) const getPathInfo = (cmd, opt) => { const colon = opt.colon || COLON // If it has a slash, then we don't bother searching the pathenv. // just check the file itself, and that's it. const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] : ( [ // windows always checks the cwd first ...(isWindows ? [process.cwd()] : []), ...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */ '').split(colon), ] ) const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' : '' const pathExt = isWindows ? pathExtExe.split(colon) : [''] if (isWindows) { if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') pathExt.unshift('') } return { pathEnv, pathExt, pathExtExe, } } const which = (cmd, opt, cb) => { if (typeof opt === 'function') { cb = opt opt = {} } if (!opt) opt = {} const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) const found = [] const step = i => new Promise((resolve, reject) => { if (i === pathEnv.length) return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd)) const ppRaw = pathEnv[i] const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw const pCmd = path.join(pathPart, cmd) const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd resolve(subStep(p, i, 0)) }) const subStep = (p, i, ii) => new Promise((resolve, reject) => { if (ii === pathExt.length) return resolve(step(i + 1)) const ext = pathExt[ii] isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { if (!er && is) { if (opt.all) found.push(p + ext) else return resolve(p + ext) } return resolve(subStep(p, i, ii + 1)) }) }) return cb ? step(0).then(res => cb(null, res), cb) : step(0) } const whichSync = (cmd, opt) => { opt = opt || {} const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) const found = [] for (let i = 0; i < pathEnv.length; i ++) { const ppRaw = pathEnv[i] const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw const pCmd = path.join(pathPart, cmd) const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd for (let j = 0; j < pathExt.length; j ++) { const cur = p + pathExt[j] try { const is = isexe.sync(cur, { pathExt: pathExtExe }) if (is) { if (opt.all) found.push(cur) else return cur } } catch (ex) {} } } if (opt.all && found.length) return found if (opt.nothrow) return null throw getNotFoundError(cmd) } module.exports = which which.sync = whichSync /***/ }), /***/ 53455: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MissingGoModVersionDirectiveError = exports.InvalidUserInputError = void 0; var invalid_user_input_error_1 = __webpack_require__(68827); Object.defineProperty(exports, "InvalidUserInputError", ({ enumerable: true, get: function () { return invalid_user_input_error_1.InvalidUserInputError; } })); var missing_go_mod_version_directive_error_1 = __webpack_require__(26764); Object.defineProperty(exports, "MissingGoModVersionDirectiveError", ({ enumerable: true, get: function () { return missing_go_mod_version_directive_error_1.MissingGoModVersionDirectiveError; } })); // Other common parser error types: // OutOfSyncError - not applicable yet, since for dep/vendor, the manifests do not contain the names of actual // modules/packages used, so they cannot be out of sync with the lockfiles. //# sourceMappingURL=index.js.map /***/ }), /***/ 68827: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.InvalidUserInputError = void 0; class InvalidUserInputError extends Error { constructor(...args) { super(...args); this.code = 422; this.name = 'InvalidUserInputError'; Error.captureStackTrace(this, InvalidUserInputError); } } exports.InvalidUserInputError = InvalidUserInputError; //# sourceMappingURL=invalid-user-input-error.js.map /***/ }), /***/ 26764: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MissingGoModVersionDirectiveError = void 0; class MissingGoModVersionDirectiveError extends Error { constructor(...args) { super(...args); this.code = 422; this.name = 'MissingGoModVersionDirectiveError'; Error.captureStackTrace(this, MissingGoModVersionDirectiveError); } } exports.MissingGoModVersionDirectiveError = MissingGoModVersionDirectiveError; //# sourceMappingURL=missing-go-mod-version-directive-error.js.map /***/ }), /***/ 21318: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildGoVendorDepTree = exports.buildGoPkgDepTree = exports.parseGoModVersionDirective = exports.parseGoModRelativeManifestReplaces = exports.parseGoModGraph = exports.parseGoVendorConfig = exports.parseGoPkgConfig = void 0; const parsers_1 = __webpack_require__(71984); Object.defineProperty(exports, "parseGoPkgConfig", ({ enumerable: true, get: function () { return parsers_1.parseGoPkgConfig; } })); Object.defineProperty(exports, "parseGoVendorConfig", ({ enumerable: true, get: function () { return parsers_1.parseGoVendorConfig; } })); Object.defineProperty(exports, "parseGoModGraph", ({ enumerable: true, get: function () { return parsers_1.parseGoModGraph; } })); Object.defineProperty(exports, "parseGoModRelativeManifestReplaces", ({ enumerable: true, get: function () { return parsers_1.parseGoModRelativeManifestReplaces; } })); Object.defineProperty(exports, "parseGoModVersionDirective", ({ enumerable: true, get: function () { return parsers_1.parseGoModVersionDirective; } })); const types_1 = __webpack_require__(68798); // TODO(kyegupov): make all build* functions sync // TODO(kyegupov): pin down the types for "options" // Build dep tree from the manifest/lock files only. // This does not scan the source code for imports, so it's not accurate; // in particular, it cannot build the proper dependency graph (only a flat list). async function buildGoPkgDepTree(manifestFileContents, lockFileContents, options) { return buildGoDepTree(await (0, parsers_1.parseGoPkgConfig)(manifestFileContents, lockFileContents)); } exports.buildGoPkgDepTree = buildGoPkgDepTree; // Build dep tree from the manifest/lock files only. // This does not scan the source code for imports, so it's not accurate; // in particular, it cannot build the proper dependency graph (only a flat list). async function buildGoVendorDepTree(manifestFileContents) { return buildGoDepTree(await (0, parsers_1.parseGoVendorConfig)(manifestFileContents)); } exports.buildGoVendorDepTree = buildGoVendorDepTree; function buildGoDepTree(goProjectConfig) { const depTree = { name: goProjectConfig.packageName || 'root', version: types_1.DEFAULT_INITIAL_VERSION, dependencies: {}, }; const dependencies = depTree.dependencies; for (const dep of Object.keys(goProjectConfig.lockedVersions)) { dependencies[dep] = { name: dep, version: goProjectConfig.lockedVersions[dep].version, }; } return depTree; } //# sourceMappingURL=index.js.map /***/ }), /***/ 61051: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseGoModGraph = void 0; const semver = __webpack_require__(61746); const dep_graph_1 = __webpack_require__(71479); const types_1 = __webpack_require__(68798); // Modules can be of shape `modules/snyk/inner/v2` or `modules/snyk/v2/inner` const GO_SEMVER_PREFIXED_MODULES_REGEX = /(.*)\/v[0-9]+(.*)/; const GO_MODULES = 'gomodules'; function parseGoModGraph(goModGraphOutput, projectName, projectVersion = types_1.DEFAULT_INITIAL_VERSION, opts = { pruneRepeatedSubDependencies: true }) { var _a; const lines = extractLines(goModGraphOutput); const maxVersions = getMaxVersions(lines); const depMap = getChildrenByParent(lines); const rootPkgInfo = { name: projectName || ((_a = lines[0]) === null || _a === void 0 ? void 0 : _a.parent.name) || 'empty', version: projectVersion, }; const dgBuilder = new dep_graph_1.DepGraphBuilder({ name: GO_MODULES }, rootPkgInfo); dfsVisit(dgBuilder, depMap, maxVersions, opts.pruneRepeatedSubDependencies, rootPkgInfo); return dgBuilder.build(); } exports.parseGoModGraph = parseGoModGraph; function dfsVisit(dgBuilder, depMap, maxVersions, prune, pkg, visited) { const isRoot = visited === undefined; const nodeId = `${pkg.name}@${pkg.version}`; const parentId = isRoot ? 'root-node' : nodeId; if (isRoot && !prune) { visited = new Set(); } const deps = depMap[nodeId] || []; for (const { name, version } of deps) { const localVisited = visited || new Set(); const effectiveDep = { name, version: maxVersions.get(name) || version }; const depId = `${effectiveDep.name}@${effectiveDep.version}`; if (localVisited.has(depId)) { if (prune) { const prunedId = `${depId}:pruned`; dgBuilder.addPkgNode(effectiveDep, prunedId, { labels: { pruned: 'true' }, }); dgBuilder.connectDep(parentId, prunedId); } else { dgBuilder.connectDep(parentId, depId); } continue; } dgBuilder.addPkgNode(effectiveDep, depId); dgBuilder.connectDep(parentId, depId); localVisited.add(depId); dfsVisit(dgBuilder, depMap, maxVersions, prune, effectiveDep, localVisited); } } function extractLines(goModGraphOutput) { return goModGraphOutput .trim() .split('\n') .filter(Boolean) .map((line) => { const [parent, child] = line .trim() .split(/\s/) .map((item) => item.split('@')) .map(([name, version]) => ({ // Handle cases for prefixed-semver // see https://golang.org/ref/mod#major-version-suffixes name: name.replace(GO_SEMVER_PREFIXED_MODULES_REGEX, '$1$2'), version: version, })); return { parent, child }; }); } function getMaxVersions(lines) { const maxVersions = new Map(); for (const line of lines) { const { child } = line; if (!maxVersions.has(child.name) || semver.gt(child.version, maxVersions.get(child.name))) { maxVersions.set(child.name, child.version); } } return maxVersions; } function getChildrenByParent(lines) { const childrenByParent = {}; for (const line of lines) { const { parent, child } = line; const parentId = `${parent.name}@${parent.version || types_1.DEFAULT_INITIAL_VERSION}`; if (parentId in childrenByParent) { childrenByParent[parentId].push(child); } else { childrenByParent[parentId] = [child]; } } return childrenByParent; } //# sourceMappingURL=gomod-graph-parser.js.map /***/ }), /***/ 70635: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseGoModRelativeManifestReplaces = void 0; const GO_MOD_DELIMITER = ' => '; const replaceSectionRegex = /replace\W?\(?(.*)\)?/s; // s as regex flag means . will match newlines too const relativePathRegex = /^\.\.?\//; function parseGoModRelativeManifestReplaces(goModFileContent) { const [, replaceSection] = replaceSectionRegex.exec(goModFileContent) || []; if (!replaceSection) { return []; } return replaceSection .replace(/\/\/.*/g, '') // remove all comments .split('\n') // now we got lines of "ModulePath" => "ModulePath" | "FilePath" .map((line) => line.trim().split(GO_MOD_DELIMITER)) // split lines by ' => ' .filter(([, filePath]) => relativePathRegex.test(filePath)) .map(([, filePath]) => filePath); } exports.parseGoModRelativeManifestReplaces = parseGoModRelativeManifestReplaces; //# sourceMappingURL=gomod-relative-manifest-parser.js.map /***/ }), /***/ 99133: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseGoModVersionDirective = void 0; const errors_1 = __webpack_require__(53455); // Parse the Go version directive from the go.mod file, if defined. // The logic is more or less identical to the actual `go` command's. See more here: // https://cs.opensource.google/go/x/mod/+/7c05a442b7c1d1a107879b4a090bb5a38d3774a1:modfile/rule.go;l=342-362 const GoVersionRE = /^go\s(?([1-9][0-9]*)\.(0|[1-9][0-9]*))/m; // Attempt to parse the go directive out of a go.mod file, either in strict mode or not. // If strict mode, will cause a failure if no version is found, otherwise just return undefined. // Both options are available as different versions of the go cli tool have acted differently around this issue. function parseGoModVersionDirective(goModFileContent, strict = true) { const version = GoVersionRE.exec(goModFileContent); if (!version) { if (strict) { // No strict version was found, and we needed one to be defined. throw new errors_1.MissingGoModVersionDirectiveError('go.mod file must have a go version directive and must match format {major}.{minor} (e.g. 1.23)'); } return undefined; } return version[1]; } exports.parseGoModVersionDirective = parseGoModVersionDirective; //# sourceMappingURL=gomod-version-directive-parser.js.map /***/ }), /***/ 88686: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseGoPkgConfig = void 0; const toml = __webpack_require__(5022); const errors_1 = __webpack_require__(53455); const event_loop_spinner_1 = __webpack_require__(77158); async function parseDepLockContents(lockFileString) { try { const lockJson = (await toml.parse.async(lockFileString)); const deps = {}; if (lockJson.projects) { for (const proj of lockJson.projects) { const version = proj.version || '#' + proj.revision; for (const subpackageName of proj.packages) { const name = subpackageName === '.' ? proj.name : proj.name + '/' + subpackageName; const dep = { name, version, }; deps[dep.name] = dep; if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } } } return deps; } catch (e) { throw new errors_1.InvalidUserInputError('Gopkg.lock parsing failed with error ' + e.message); } } function parseDepManifestContents(manifestToml) { try { const manifestJson = toml.parse(manifestToml) || {}; manifestJson.ignored = manifestJson.ignored || []; return manifestJson; } catch (e) { throw new errors_1.InvalidUserInputError('Gopkg.toml parsing failed with error ' + e.message); } } async function parseGoPkgConfig(manifestFileContents, lockFileContents) { if (!manifestFileContents && !lockFileContents) { throw new errors_1.InvalidUserInputError('Gopkg.lock and Gopkg.toml file contents are empty'); } if (!lockFileContents) { throw new errors_1.InvalidUserInputError('Gopkg.lock is empty, cannot proceed parsing'); } const lockedVersions = await parseDepLockContents(lockFileContents); let ignoredPkgs = []; if (manifestFileContents) { const manifest = parseDepManifestContents(manifestFileContents); ignoredPkgs = manifest.ignored; } return { lockedVersions, ignoredPkgs }; } exports.parseGoPkgConfig = parseGoPkgConfig; //# sourceMappingURL=gopkg-parser.js.map /***/ }), /***/ 98553: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseGoVendorConfig = void 0; const errors_1 = __webpack_require__(53455); const event_loop_spinner_1 = __webpack_require__(77158); async function parseGovendorJsonContents(jsonStr) { try { const gvJson = JSON.parse(jsonStr); const goProjectConfig = { ignoredPkgs: [], lockedVersions: {}, packageName: gvJson.rootPath, }; const packages = gvJson.package || gvJson.Package; if (packages) { for (const pkg of packages) { const revision = pkg.revision || pkg.Revision || pkg.version || pkg.Version; const version = pkg.versionExact || '#' + revision; const dep = { name: pkg.path, version, }; goProjectConfig.lockedVersions[dep.name] = dep; if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } } const ignores = gvJson.ignore || ''; for (let pkgName of ignores.split(/\s/)) { if (pkgName.indexOf('/') === -1) { continue; // it's a build-tag rather than a pacakge } pkgName = pkgName.replace(/\/+$/, ''); // remove trailing / goProjectConfig.ignoredPkgs.push(pkgName); goProjectConfig.ignoredPkgs.push(pkgName + '/*'); if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } return goProjectConfig; } catch (e) { throw new errors_1.InvalidUserInputError('vendor.json parsing failed with error ' + e.message); } } async function parseGoVendorConfig(manifestFileContents) { if (!manifestFileContents) { throw new errors_1.InvalidUserInputError('vendor.json file contents are empty'); } return parseGovendorJsonContents(manifestFileContents); } exports.parseGoVendorConfig = parseGoVendorConfig; //# sourceMappingURL=govendor-parser.js.map /***/ }), /***/ 71984: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseGoModVersionDirective = exports.parseGoModRelativeManifestReplaces = exports.parseGoPkgConfig = exports.parseGoVendorConfig = exports.parseGoModGraph = void 0; var gomod_graph_parser_1 = __webpack_require__(61051); Object.defineProperty(exports, "parseGoModGraph", ({ enumerable: true, get: function () { return gomod_graph_parser_1.parseGoModGraph; } })); var govendor_parser_1 = __webpack_require__(98553); Object.defineProperty(exports, "parseGoVendorConfig", ({ enumerable: true, get: function () { return govendor_parser_1.parseGoVendorConfig; } })); var gopkg_parser_1 = __webpack_require__(88686); Object.defineProperty(exports, "parseGoPkgConfig", ({ enumerable: true, get: function () { return gopkg_parser_1.parseGoPkgConfig; } })); var gomod_relative_manifest_parser_1 = __webpack_require__(70635); Object.defineProperty(exports, "parseGoModRelativeManifestReplaces", ({ enumerable: true, get: function () { return gomod_relative_manifest_parser_1.parseGoModRelativeManifestReplaces; } })); var gomod_version_directive_parser_1 = __webpack_require__(99133); Object.defineProperty(exports, "parseGoModVersionDirective", ({ enumerable: true, get: function () { return gomod_version_directive_parser_1.parseGoModVersionDirective; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 68798: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DEFAULT_ROOT_NODE_NAME = exports.DEFAULT_INITIAL_VERSION = void 0; exports.DEFAULT_INITIAL_VERSION = '0.0.0'; exports.DEFAULT_ROOT_NODE_NAME = 'root-node'; //# sourceMappingURL=types.js.map /***/ }), /***/ 32027: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CustomError = void 0; class CustomError extends Error { constructor(message) { super(message); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.code = undefined; this.innerError = undefined; this.userMessage = undefined; } } exports.CustomError = CustomError; //# sourceMappingURL=custom-error.js.map /***/ }), /***/ 29376: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.jsonParse = exports.buildDepGraphFromImportsAndModules = exports.inspect = void 0; const fs = __webpack_require__(57147); const path = __webpack_require__(71017); const tmp = __webpack_require__(91406); const lookpath_1 = __webpack_require__(77103); const debugLib = __webpack_require__(15158); const graphlib = __webpack_require__(39322); const dep_graph_1 = __webpack_require__(7377); const subProcess = __webpack_require__(10840); const custom_error_1 = __webpack_require__(32027); const snyk_go_parser_1 = __webpack_require__(21318); const debug = debugLib('snyk-go-plugin'); const VIRTUAL_ROOT_NODE_ID = '.'; async function inspect(root, targetFile, options = {}) { options.debug ? debugLib.enable('snyk-go-plugin') : debugLib.disable(); const goPath = await (0, lookpath_1.lookpath)('go'); if (!goPath) { throw new Error('The "go" command is not available on your system. To scan your dependencies in the CLI, you must ensure you have first installed the relevant package manager.'); } const result = await Promise.all([ getMetaData(root, targetFile), getDependencies(root, targetFile, options.args), ]); const hasDepGraph = result[1].dependencyGraph && !result[1].dependencyTree; const hasDepTree = !result[1].dependencyGraph && result[1].dependencyTree; // TODO @boost: get rid of the rest of depTree and fully convert this plugin to use depGraph if (hasDepGraph) { return { plugin: result[0], dependencyGraph: result[1].dependencyGraph, }; } else if (hasDepTree) { return { plugin: result[0], package: result[1].dependencyTree, }; } // TODO @boost: remove me throw new Error('Failed to scan this go project.'); } exports.inspect = inspect; async function getMetaData(root, targetFile) { const output = await subProcess.execute('go', ['version'], { cwd: root }); const versionMatch = /(go\d+\.?\d+?\.?\d*)/.exec(output); const runtime = versionMatch ? versionMatch[0] : undefined; return { name: 'snyk-go-plugin', runtime, targetFile: pathToPosix(targetFile), }; } function createAssets() { // path.join calls have to be exactly in this format, needed by "pkg" to build a standalone Snyk CLI binary: // https://www.npmjs.com/package/pkg#detecting-assets-in-source-code return [path.join(__dirname, '../gosrc/resolve-deps.go')]; } function writeFile(writeFilePath, contents) { const dirPath = path.dirname(writeFilePath); if (!fs.existsSync(dirPath)) { fs.mkdirSync(dirPath); } fs.writeFileSync(writeFilePath, contents); } function getFilePathRelativeToDumpDir(filePath) { let pathParts = filePath.split('\\gosrc\\'); // Windows if (pathParts.length > 1) { return pathParts[1]; } // Unix pathParts = filePath.split('/gosrc/'); return pathParts[1]; } function dumpAllResolveDepsFilesInTempDir(tempDirName) { createAssets().forEach((currentReadFilePath) => { if (!fs.existsSync(currentReadFilePath)) { throw new Error('The file `' + currentReadFilePath + '` is missing'); } const relFilePathToDumpDir = getFilePathRelativeToDumpDir(currentReadFilePath); const writeFilePath = path.join(tempDirName, relFilePathToDumpDir); const contents = fs.readFileSync(currentReadFilePath); writeFile(writeFilePath, contents); }); } const PACKAGE_MANAGER_BY_TARGET = { 'Gopkg.lock': 'golangdep', 'vendor.json': 'govendor', 'go.mod': 'gomodules', }; const VENDOR_SYNC_CMD_BY_PKG_MANAGER = { golangdep: 'dep ensure', govendor: 'govendor sync', gomodules: 'go mod download', }; async function getDependencies(root, targetFile, additionalArgs) { let tempDirObj; const packageManager = pkgManagerByTarget(targetFile); if (packageManager === 'gomodules') { const dependencyGraph = await buildDepGraphFromImportsAndModules(root, targetFile, additionalArgs); return { dependencyGraph, }; } try { debug('parsing manifest/lockfile', { root, targetFile }); const config = await parseConfig(root, targetFile); tempDirObj = tmp.dirSync({ unsafeCleanup: true, }); dumpAllResolveDepsFilesInTempDir(tempDirObj.name); const goResolveTool = path.join(tempDirObj.name, 'resolve-deps.go'); let ignorePkgsParam; if (config.ignoredPkgs && config.ignoredPkgs.length > 0) { ignorePkgsParam = '-ignoredPkgs=' + config.ignoredPkgs.join(','); } const args = ['run', goResolveTool, ignorePkgsParam]; debug('executing go deps resolver', { cmd: 'go' + args.join(' ') }); const graphStr = await runGo(args, { cwd: root, env: { GO111MODULE: 'off' }, }); tempDirObj.removeCallback(); debug('loading deps resolver graph output to graphlib', { jsonSize: graphStr.length, }); const graph = graphlib.json.read(JSON.parse(graphStr)); if (!graphlib.alg.isAcyclic(graph)) { throw new Error('Go import cycle detected (not allowed by the Go compiler)'); } // A project can contain several "entry points", // i.e. pkgs with no local dependants. // To create a tree, we add edges from a "virutal root", // to these source nodes. const rootNode = graph.node(VIRTUAL_ROOT_NODE_ID); if (!rootNode) { throw new Error('Failed parsing dependency graph'); } graph.sources().forEach((nodeId) => { if (nodeId !== VIRTUAL_ROOT_NODE_ID) { graph.setEdge(VIRTUAL_ROOT_NODE_ID, nodeId); } }); const projectRootPath = getProjectRootFromTargetFile(targetFile); debug('building dep-tree'); const pkgsTree = recursivelyBuildPkgTree(graph, rootNode, config.lockedVersions, projectRootPath, {}); delete pkgsTree._counts; pkgsTree.packageFormatVersion = 'golang:0.0.1'; debug('done building dep-tree', { rootPkgName: pkgsTree.name }); return { dependencyTree: pkgsTree }; } catch (error) { if (tempDirObj) { tempDirObj.removeCallback(); } if (typeof error === 'string') { const unresolvedOffset = error.indexOf('Unresolved packages:'); if (unresolvedOffset !== -1) { throw new Error(error.slice(unresolvedOffset) + '\n' + 'Unresolved imports found, please run `' + syncCmdForTarget(targetFile) + '`'); } throw new Error(error); } throw error; } } function pkgManagerByTarget(targetFile) { const fname = path.basename(targetFile); return PACKAGE_MANAGER_BY_TARGET[fname]; } function syncCmdForTarget(targetFile) { return VENDOR_SYNC_CMD_BY_PKG_MANAGER[pkgManagerByTarget(targetFile)]; } function getProjectRootFromTargetFile(targetFile) { const resolved = path.resolve(targetFile); const parts = resolved.split(path.sep); if (parts[parts.length - 1] === 'Gopkg.lock') { return path.dirname(resolved); } if (parts[parts.length - 1] === 'vendor.json' && parts[parts.length - 2] === 'vendor') { return path.dirname(path.dirname(resolved)); } if (parts[parts.length - 1] === 'go.mod') { return path.dirname(resolved); } throw new Error('Unsupported file: ' + targetFile); } function recursivelyBuildPkgTree(graph, node, lockedVersions, projectRootPath, totalPackageOccurenceCounter) { const isRoot = node.Name === VIRTUAL_ROOT_NODE_ID; const isProjSubpkg = isProjSubpackage(node.Dir, projectRootPath); const pkg = { name: isRoot ? node.FullImportPath : node.Name, dependencies: {}, }; if (!isRoot && isProjSubpkg) { pkg._isProjSubpkg = true; } if (isRoot || isProjSubpkg) { pkg.version = ''; } else if (!lockedVersions[pkg.name]) { pkg.version = ''; // TODO: warn or set to "?" ? } else { pkg.version = lockedVersions[pkg.name].version; } const children = graph.successors(node.Name).sort(); children.forEach((depName) => { // We drop whole dep tree branches for frequently repeatedpackages: // this loses some paths, but avoids explosion in result size if ((totalPackageOccurenceCounter[depName] || 0) > 10) { return; } const dep = graph.node(depName); const child = recursivelyBuildPkgTree(graph, dep, lockedVersions, projectRootPath, totalPackageOccurenceCounter); if (child._isProjSubpkg) { Object.keys(child.dependencies).forEach((grandChildName) => { // We merge all the subpackages of the project into the root project, by transplanting dependencies of the // subpackages one level up. // This is done to decrease the tree size - and to be similar to other languages, where we are only showing // dependencies at the project level, not at the level of individual code sub-directories (which Go packages // are, essentially). if (!pkg.dependencies[grandChildName]) { pkg.dependencies[grandChildName] = child.dependencies[grandChildName]; } }); // Even though subpackages are not preserved in the result, we still need protection from combinatorial explosion // while scanning the tree. totalPackageOccurenceCounter[child.name] = (totalPackageOccurenceCounter[child.name] || 0) + 1; } else { // in case was already added via a grandchild if (!pkg.dependencies[child.name]) { pkg.dependencies[child.name] = child; totalPackageOccurenceCounter[child.name] = (totalPackageOccurenceCounter[child.name] || 0) + 1; } } }); return pkg; } function isProjSubpackage(pkgPath, projectRootPath) { if (pkgPath === projectRootPath) { return true; } let root = projectRootPath; root = root[root.length - 1] === path.sep ? root : root + path.sep; if (pkgPath.indexOf(root) !== 0) { return false; } const pkgRelativePath = pkgPath.slice(root.length); if (pkgRelativePath.split(path.sep).indexOf('vendor') !== -1) { return false; } return true; } // interface LockedDep { // name: string; // version: string; // } // // interface LockedDeps { // [dep: string]: LockedDep; // } // // interface DepManifest { // ignored: string[]; // } async function parseConfig(root, targetFile) { const pkgManager = pkgManagerByTarget(targetFile); debug('detected package-manager:', pkgManager); switch (pkgManager) { case 'golangdep': { try { return await (0, snyk_go_parser_1.parseGoPkgConfig)(getDepManifest(root, targetFile), getDepLock(root, targetFile)); } catch (e) { throw new Error('failed parsing manifest/lock files for Go dep: ' + e.message); } } case 'govendor': { try { return await (0, snyk_go_parser_1.parseGoVendorConfig)(getGovendorJson(root, targetFile)); } catch (e) { throw new Error('failed parsing config file for Go Vendor Tool: ' + e.message); } } default: { throw new Error('Unsupported file: ' + targetFile); } } } function getDepLock(root, targetFile) { return fs.readFileSync(path.join(root, targetFile), 'utf8'); } function getDepManifest(root, targetFile) { const manifestDir = path.dirname(path.join(root, targetFile)); const manifestPath = path.join(manifestDir, 'Gopkg.toml'); return fs.readFileSync(manifestPath, 'utf8'); } // TODO: branch, old Version can be a tag too? function getGovendorJson(root, targetFile) { return fs.readFileSync(path.join(root, targetFile), 'utf8'); } function pathToPosix(fpath) { const parts = fpath.split(path.sep); return parts.join(path.posix.sep); } async function buildDepGraphFromImportsAndModules(root = '.', targetFile = 'go.mod', additionalArgs = []) { // TODO(BST-657): parse go.mod file to obtain root module name and go version const projectName = path.basename(root); // The correct name should come from the `go list` command const projectVersion = '0.0.0'; // TODO(BST-657): try `git describe`? let depGraphBuilder = new dep_graph_1.DepGraphBuilder({ name: 'gomodules' }, { name: projectName, version: projectVersion, }); let goDepsOutput; const args = ['list', ...additionalArgs, '-json', '-deps', './...']; try { const goModAbsolutPath = path.resolve(root, path.dirname(targetFile)); goDepsOutput = await runGo(args, { cwd: goModAbsolutPath }); } catch (err) { if (/cannot find main module, but found/.test(err)) { return depGraphBuilder.build(); } if (/does not contain main module/.test(err)) { return depGraphBuilder.build(); } const userError = new custom_error_1.CustomError(err); userError.userMessage = `'go ${args.join(' ')}' command failed with error: ${userError.message}`; throw userError; } if (goDepsOutput.includes('matched no packages')) { return depGraphBuilder.build(); } const goDepsString = `[${goDepsOutput.replace(/}\r?\n{/g, '},{')}]`; const goDeps = JSON.parse(goDepsString); const packagesByName = {}; for (const gp of goDeps) { packagesByName[gp.ImportPath] = gp; // ImportPath is the fully qualified name } const localPackages = goDeps.filter((gp) => !gp.DepOnly); const localPackageWithMainModule = localPackages.find((localPackage) => !!(localPackage.Module && localPackage.Module.Main)); if (localPackageWithMainModule && localPackageWithMainModule.Module.Path) { depGraphBuilder = new dep_graph_1.DepGraphBuilder({ name: 'gomodules' }, { name: localPackageWithMainModule.Module.Path, version: projectVersion, }); } const topLevelDeps = extractAllImports(localPackages); const childrenChain = new Map(); const ancestorsChain = new Map(); buildGraph(depGraphBuilder, topLevelDeps, packagesByName, 'root-node', childrenChain, ancestorsChain); return depGraphBuilder.build(); } exports.buildDepGraphFromImportsAndModules = buildDepGraphFromImportsAndModules; async function runGo(args, options, additionalGoCommands = []) { try { return await subProcess.execute('go', args, options); } catch (err) { const [command] = /(go mod download)|(go get [^"]*)/.exec(err) || []; if (command && !additionalGoCommands.includes(command)) { debug('running command:', command); const newArgs = command.split(' ').slice(1); await subProcess.execute('go', newArgs, options); return runGo(args, options, additionalGoCommands.concat(command)); } throw err; } } function buildGraph(depGraphBuilder, depPackages, packagesByName, currentParent, childrenChain, ancestorsChain, visited) { var _a; const depPackagesLen = depPackages.length; for (let i = depPackagesLen - 1; i >= 0; i--) { const localVisited = visited || new Set(); const packageImport = depPackages[i]; let version = 'unknown'; if (isBuiltinPackage(packageImport)) { // We do not track vulns in Go standard library continue; } else if (!packagesByName[packageImport].DepOnly) { // Do not include packages of this module continue; } const pkg = packagesByName[packageImport]; if (pkg.Module && pkg.Module.Version) { // get hash (prefixed with #) or version (with v prefix removed) version = toSnykVersion(parseVersion(((_a = pkg.Module.Replace) === null || _a === void 0 ? void 0 : _a.Version) || pkg.Module.Version)); } if (currentParent && packageImport) { const newNode = { name: packageImport, version, }; const currentChildren = childrenChain.get(currentParent) || []; const currentAncestors = ancestorsChain.get(currentParent) || []; const isAncestorOrChild = currentChildren.includes(packageImport) || currentAncestors.includes(packageImport); // @TODO boost: breaking cycles, re-work once dep-graph lib can handle cycles if (packageImport === currentParent || isAncestorOrChild) { continue; } if (localVisited.has(packageImport)) { const prunedId = `${packageImport}:pruned`; depGraphBuilder.addPkgNode(newNode, prunedId, { labels: { pruned: 'true' }, }); depGraphBuilder.connectDep(currentParent, prunedId); continue; } depGraphBuilder.addPkgNode(newNode, packageImport); depGraphBuilder.connectDep(currentParent, packageImport); localVisited.add(packageImport); childrenChain.set(currentParent, [...currentChildren, packageImport]); ancestorsChain.set(packageImport, [...currentAncestors, currentParent]); const transitives = packagesByName[packageImport].Imports || []; if (transitives.length > 0) { buildGraph(depGraphBuilder, transitives, packagesByName, packageImport, childrenChain, ancestorsChain, localVisited); } } } } function extractAllImports(goDeps) { const goDepsImports = new Set(); for (const pkg of goDeps) { if (pkg.Imports) { for (const imp of pkg.Imports) { goDepsImports.add(imp); } } } return Array.from(goDepsImports); } // Better error message than JSON.parse function jsonParse(s) { try { return JSON.parse(s); } catch (e) { e.message = e.message + ', original string: "' + s + '"'; throw e; } } exports.jsonParse = jsonParse; function isBuiltinPackage(pkgName) { // Non-builtin packages have domain names in them that contain dots return pkgName.indexOf('.') === -1; } const rePseudoVersion = /(v\d+\.\d+\.\d+)-(.*?)(\d{14})-([0-9a-f]{12})/; const reExactVersion = /^(.*?)(\+incompatible)?$/; function parseVersion(versionString) { const maybeRegexMatch = rePseudoVersion.exec(versionString); if (maybeRegexMatch) { const [baseVersion, suffix, timestamp, hash] = maybeRegexMatch.slice(1); return { baseVersion, suffix, timestamp, hash }; } else { // No pseudo version recognized, assuming the provided version string is exact const [exactVersion, incompatibleStr] = reExactVersion .exec(versionString) .slice(1); return { exactVersion, incompatible: !!incompatibleStr }; } } function toSnykVersion(v) { if ('hash' in v && v.hash) { return '#' + v.hash; } else if ('exactVersion' in v && v.exactVersion) { return v.exactVersion.replace(/^v/, ''); } else { throw new Error('Unexpected module version format'); } } //# sourceMappingURL=index.js.map /***/ }), /***/ 10840: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.execute = void 0; const childProcess = __webpack_require__(32081); function execute(command, args, options, shell = false) { const spawnOptions = { shell, env: { ...process.env }, }; if (options === null || options === void 0 ? void 0 : options.cwd) { spawnOptions.cwd = options.cwd; } if (options === null || options === void 0 ? void 0 : options.env) { spawnOptions.env = { ...process.env, ...options.env }; } // Before spawning an external process, we look if we need to restore the system proxy configuration, // which overides the cli internal proxy configuration. if (process.env.SNYK_SYSTEM_HTTP_PROXY !== undefined) { spawnOptions.env.HTTP_PROXY = process.env.SNYK_SYSTEM_HTTP_PROXY; } if (process.env.SNYK_SYSTEM_HTTPS_PROXY !== undefined) { spawnOptions.env.HTTPS_PROXY = process.env.SNYK_SYSTEM_HTTPS_PROXY; } if (process.env.SNYK_SYSTEM_NO_PROXY !== undefined) { spawnOptions.env.NO_PROXY = process.env.SNYK_SYSTEM_NO_PROXY; } return new Promise((resolve, reject) => { let stdout = ''; let stderr = ''; const proc = childProcess.spawn(command, args, spawnOptions); proc.stdout.on('data', (data) => { stdout = stdout + data; }); proc.stderr.on('data', (data) => { stderr = stderr + data; }); proc.on('close', (code) => { if (code !== 0) { return reject(stdout || stderr); } resolve(stdout || stderr); }); }); } exports.execute = execute; //# sourceMappingURL=sub-process.js.map /***/ }), /***/ 54039: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DepGraphBuilder = void 0; const graphlib = __webpack_require__(45488); const dep_graph_1 = __webpack_require__(30765); class DepGraphBuilder { constructor(pkgManager, rootPkg) { this._pkgs = {}; this._pkgNodes = {}; const graph = new graphlib.Graph({ directed: true, multigraph: false, compound: false, }); if (!rootPkg) { rootPkg = { name: '_root', version: '0.0.0', }; } this._rootNodeId = 'root-node'; this._rootPkgId = DepGraphBuilder._getPkgId(rootPkg); this._pkgs[this._rootPkgId] = rootPkg; graph.setNode(this._rootNodeId, { pkgId: this._rootPkgId }); this._pkgNodes[this._rootPkgId] = new Set([this._rootNodeId]); this._graph = graph; this._pkgManager = pkgManager; } get rootNodeId() { return this._rootNodeId; } static _getPkgId(pkg) { return `${pkg.name}@${pkg.version || ''}`; } getPkgs() { return Object.values(this._pkgs); } // TODO: this can create disconnected nodes addPkgNode(pkgInfo, nodeId, nodeInfo) { if (nodeId === this._rootNodeId) { throw new Error('DepGraphBuilder.addPkgNode() cant override root node'); } const pkgId = DepGraphBuilder._getPkgId(pkgInfo); this._pkgs[pkgId] = pkgInfo; this._pkgNodes[pkgId] = this._pkgNodes[pkgId] || new Set(); this._pkgNodes[pkgId].add(nodeId); this._graph.setNode(nodeId, { pkgId, info: nodeInfo }); return this; } // TODO: this can create cycles connectDep(parentNodeId, depNodeId) { if (!this._graph.hasNode(parentNodeId)) { throw new Error('parentNodeId does not exist'); } if (!this._graph.hasNode(depNodeId)) { throw new Error('depNodeId does not exist'); } this._graph.setEdge(parentNodeId, depNodeId); return this; } build() { return new dep_graph_1.DepGraphImpl(this._graph, this._rootNodeId, this._pkgs, this._pkgNodes, this._pkgManager); } } exports.DepGraphBuilder = DepGraphBuilder; //# sourceMappingURL=builder.js.map /***/ }), /***/ 47020: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createFromJSON = exports.SUPPORTED_SCHEMA_RANGE = void 0; const semver = __webpack_require__(45047); const graphlib = __webpack_require__(45488); const errors_1 = __webpack_require__(297); const validate_graph_1 = __webpack_require__(98447); const dep_graph_1 = __webpack_require__(30765); exports.SUPPORTED_SCHEMA_RANGE = '^1.0.0'; /** * Create a DepGraph instance from a JSON representation of a dep graph. This * is typically used after passing the graph over the wire as `DepGraphData`. */ function createFromJSON(depGraphData) { validateDepGraphData(depGraphData); const graph = new graphlib.Graph({ directed: true, multigraph: false, compound: false, }); const pkgs = {}; const pkgNodes = {}; for (const { id, info } of depGraphData.pkgs) { pkgs[id] = info.version ? info : Object.assign(Object.assign({}, info), { version: undefined }); } for (const node of depGraphData.graph.nodes) { const pkgId = node.pkgId; if (!pkgNodes[pkgId]) { pkgNodes[pkgId] = new Set(); } pkgNodes[pkgId].add(node.nodeId); graph.setNode(node.nodeId, { pkgId, info: node.info }); } for (const node of depGraphData.graph.nodes) { for (const depNodeId of node.deps) { graph.setEdge(node.nodeId, depNodeId.nodeId); } } validate_graph_1.validateGraph(graph, depGraphData.graph.rootNodeId, pkgs, pkgNodes); return new dep_graph_1.DepGraphImpl(graph, depGraphData.graph.rootNodeId, pkgs, pkgNodes, depGraphData.pkgManager); } exports.createFromJSON = createFromJSON; function assert(condition, msg) { if (!condition) { throw new errors_1.ValidationError(msg); } } function validateDepGraphData(depGraphData) { assert(!!semver.valid(depGraphData.schemaVersion) && semver.satisfies(depGraphData.schemaVersion, exports.SUPPORTED_SCHEMA_RANGE), `dep-graph schemaVersion not in "${exports.SUPPORTED_SCHEMA_RANGE}"`); assert(depGraphData.pkgManager && !!depGraphData.pkgManager.name, '.pkgManager.name is missing'); const pkgsMap = depGraphData.pkgs.reduce((acc, cur) => { assert(!(cur.id in acc), 'more than one pkg with same id'); assert(!!cur.info, '.pkgs item missing .info'); acc[cur.id] = cur.info; return acc; }, {}); const nodesMap = depGraphData.graph.nodes.reduce((acc, cur) => { assert(!(cur.nodeId in acc), 'more than on node with same id'); acc[cur.nodeId] = cur; return acc; }, {}); const rootNodeId = depGraphData.graph.rootNodeId; const rootNode = nodesMap[rootNodeId]; assert(rootNodeId in nodesMap, `.${rootNodeId} root graph node is missing`); const rootPkgId = rootNode.pkgId; assert(rootPkgId in pkgsMap, `.${rootPkgId} root pkg missing`); assert(nodesMap[rootNodeId].pkgId === rootPkgId, `the root node .pkgId should be "${rootPkgId}"`); const pkgIds = Object.keys(pkgsMap); // NOTE: this name@version check is very strict, // we can relax it later, it just makes things easier now assert(pkgIds.filter((pkgId) => pkgId !== dep_graph_1.DepGraphImpl.getPkgId(pkgsMap[pkgId])) .length === 0, 'pkgs ids should be name@version'); assert(Object.values(nodesMap).filter((node) => !(node.pkgId in pkgsMap)) .length === 0, 'some instance nodes belong to non-existing pkgIds'); assert(Object.values(pkgsMap).filter((pkg) => !pkg.name) .length === 0, 'some .pkgs elements have no .name field'); } //# sourceMappingURL=create-from-json.js.map /***/ }), /***/ 30765: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DepGraphImpl = void 0; const _isEqual = __webpack_require__(72307); const graphlib = __webpack_require__(45488); const create_from_json_1 = __webpack_require__(47020); class DepGraphImpl { constructor(_graph, _rootNodeId, _pkgs, _pkgNodes, _pkgManager) { this._graph = _graph; this._rootNodeId = _rootNodeId; this._pkgs = _pkgs; this._pkgNodes = _pkgNodes; this._pkgManager = _pkgManager; this._countNodePathsToRootCache = new Map(); this._rootPkgId = _graph.node(_rootNodeId).pkgId; this._pkgList = Object.values(_pkgs); this._depPkgsList = this._pkgList.filter((pkg) => pkg !== this.rootPkg); } static getPkgId(pkg) { return `${pkg.name}@${pkg.version || ''}`; } get pkgManager() { return this._pkgManager; } get rootPkg() { return this._pkgs[this._rootPkgId]; } get rootNodeId() { return this._rootNodeId; } /** * Get all unique packages in the graph (including the root package) */ getPkgs() { return this._pkgList; } /** * Get all unique packages in the graph (excluding the root package) */ getDepPkgs() { return this._depPkgsList; } getPkgNodes(pkg) { const pkgId = DepGraphImpl.getPkgId(pkg); const nodes = []; for (const nodeId of Array.from(this._pkgNodes[pkgId])) { const graphNode = this.getGraphNode(nodeId); nodes.push({ info: graphNode.info || {}, }); } return nodes; } getNode(nodeId) { return this.getGraphNode(nodeId).info || {}; } getNodePkg(nodeId) { return this._pkgs[this.getGraphNode(nodeId).pkgId]; } getPkgNodeIds(pkg) { const pkgId = DepGraphImpl.getPkgId(pkg); if (!this._pkgs[pkgId]) { throw new Error(`no such pkg: ${pkgId}`); } return Array.from(this._pkgNodes[pkgId]); } getNodeDepsNodeIds(nodeId) { const deps = this._graph.successors(nodeId); if (!deps) { throw new Error(`no such node: ${nodeId}`); } return deps; } getNodeParentsNodeIds(nodeId) { const parents = this._graph.predecessors(nodeId); if (!parents) { throw new Error(`no such node: ${nodeId}`); } return parents; } hasCycles() { // `isAcyclic` is expensive, so memoize if (this._hasCycles === undefined) { this._hasCycles = !graphlib.alg.isAcyclic(this._graph); } return this._hasCycles; } pkgPathsToRoot(pkg, opts) { const pathsToRoot = []; const limit = opts === null || opts === void 0 ? void 0 : opts.limit; for (const nodeId of this.getPkgNodeIds(pkg)) { const pathsFromNodeToRoot = this.pathsFromNodeToRoot(nodeId, [], { limit, }); for (const path of pathsFromNodeToRoot) { pathsToRoot.push(path); } if (limit && pathsToRoot.length >= limit) { break; } } // note: sorting to get shorter paths first - // it's nicer - and better resembles older behaviour return pathsToRoot.sort((a, b) => a.length - b.length); } countPathsToRoot(pkg) { let count = 0; for (const nodeId of this.getPkgNodeIds(pkg)) { count += this.countNodePathsToRoot(nodeId); } return count; } equals(other, { compareRoot = true } = {}) { let otherDepGraph; if (other instanceof DepGraphImpl) { otherDepGraph = other; } else { // At runtime theoretically we can have multiple versions of // @snyk/dep-graph. If "other" is not an instance of the same class it is // safer to rebuild it from JSON. otherDepGraph = create_from_json_1.createFromJSON(other.toJSON()); } // In theory, for the graphs created by standard means, `_.isEquals(this._data, otherDepGraph._data)` // should suffice, since node IDs will be generated in a predictable way. // However, there might be different versions of graph and inconsistencies // in the ordering of the arrays, so we perform a deep comparison. return this.nodeEquals(this, this.rootNodeId, otherDepGraph, otherDepGraph.rootNodeId, compareRoot); } directDepsLeadingTo(pkg) { const pkgNodes = this.getPkgNodeIds(pkg); const directDeps = this.getNodeDepsNodeIds(this.rootNodeId); const nodes = directDeps.filter((directDep) => { const reachableNodes = graphlib.alg.postorder(this._graph, [directDep]); return reachableNodes.filter((node) => pkgNodes.includes(node)).length; }); return nodes.map((node) => this.getNodePkg(node)); } /** * Create a JSON representation of a dep graph. This is typically used to * send the dep graph over the wire */ toJSON() { const nodeIds = this._graph.nodes(); const nodes = nodeIds.reduce((acc, nodeId) => { const deps = (this._graph.successors(nodeId) || []).map((depNodeId) => ({ nodeId: depNodeId, })); const node = this._graph.node(nodeId); const elem = { nodeId, pkgId: node.pkgId, deps, }; if (node.info && Object.keys(node.info).length > 0) { elem.info = node.info; } acc.push(elem); return acc; }, []); const pkgs = Object.keys(this._pkgs).map((pkgId) => ({ id: pkgId, info: this._pkgs[pkgId], })); return { schemaVersion: DepGraphImpl.SCHEMA_VERSION, pkgManager: this._pkgManager, pkgs, graph: { rootNodeId: this._rootNodeId, nodes, }, }; } nodeEquals(graphA, nodeIdA, graphB, nodeIdB, compareRoot, traversedPairs = new Set()) { // Skip root nodes comparision if needed. if (compareRoot || (nodeIdA !== graphA.rootNodeId && nodeIdB !== graphB.rootNodeId)) { const pkgA = graphA.getNodePkg(nodeIdA); const pkgB = graphB.getNodePkg(nodeIdB); // Compare PkgInfo (name and version). if (!_isEqual(pkgA, pkgB)) { return false; } const infoA = graphA.getNode(nodeIdA); const infoB = graphB.getNode(nodeIdB); // Compare NodeInfo (VersionProvenance and labels). if (!_isEqual(infoA, infoB)) { return false; } } let depsA = graphA.getNodeDepsNodeIds(nodeIdA); let depsB = graphB.getNodeDepsNodeIds(nodeIdB); // Number of dependencies should be the same. if (depsA.length !== depsB.length) { return false; } // Sort dependencies by name@version string. const sortFn = (graph) => (idA, idB) => { const pkgA = graph.getNodePkg(idA); const pkgB = graph.getNodePkg(idB); return DepGraphImpl.getPkgId(pkgA).localeCompare(DepGraphImpl.getPkgId(pkgB)); }; depsA = depsA.sort(sortFn(graphA)); depsB = depsB.sort(sortFn(graphB)); // Compare Each dependency recursively. for (let i = 0; i < depsA.length; i++) { const pairKey = `${depsA[i]}_${depsB[i]}`; // Prevent cycles. if (traversedPairs.has(pairKey)) { continue; } traversedPairs.add(pairKey); if (!this.nodeEquals(graphA, depsA[i], graphB, depsB[i], compareRoot, traversedPairs)) { return false; } } return true; } getGraphNode(nodeId) { const node = this._graph.node(nodeId); if (!node) { throw new Error(`no such node: ${nodeId}`); } return node; } pathsFromNodeToRoot(nodeId, ancestors = [], opts) { const parentNodesIds = this.getNodeParentsNodeIds(nodeId); const pkgInfo = this.getNodePkg(nodeId); if (parentNodesIds.length === 0) { return [[pkgInfo]]; } const allPaths = []; ancestors = ancestors.concat(nodeId); const limit = opts.limit; for (const id of parentNodesIds) { if (ancestors.includes(id)) continue; const pathsFromNodeToRoot = this.pathsFromNodeToRoot(id, ancestors, opts); pathsFromNodeToRoot.forEach((path) => allPaths.push([pkgInfo].concat(path))); if (limit && allPaths.length >= limit) { break; } } return allPaths; } countNodePathsToRoot(nodeId, ancestors = []) { if (ancestors.includes(nodeId)) { return 0; } if (this._countNodePathsToRootCache.has(nodeId)) { return this._countNodePathsToRootCache.get(nodeId) || 0; } const parentNodesIds = this.getNodeParentsNodeIds(nodeId); if (parentNodesIds.length === 0) { this._countNodePathsToRootCache.set(nodeId, 1); return 1; } ancestors = ancestors.concat(nodeId); const count = parentNodesIds.reduce((acc, parentNodeId) => { return acc + this.countNodePathsToRoot(parentNodeId, ancestors); }, 0); this._countNodePathsToRootCache.set(nodeId, count); return count; } } exports.DepGraphImpl = DepGraphImpl; DepGraphImpl.SCHEMA_VERSION = '1.2.0'; //# sourceMappingURL=dep-graph.js.map /***/ }), /***/ 71732: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CustomError = void 0; class CustomError extends Error { constructor(message) { super(message); Object.setPrototypeOf(this, CustomError.prototype); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; } } exports.CustomError = CustomError; //# sourceMappingURL=custom-error.js.map /***/ }), /***/ 297: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ValidationError = void 0; const validation_error_1 = __webpack_require__(12042); Object.defineProperty(exports, "ValidationError", ({ enumerable: true, get: function () { return validation_error_1.ValidationError; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 12042: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ValidationError = void 0; const custom_error_1 = __webpack_require__(71732); class ValidationError extends custom_error_1.CustomError { constructor(message) { super(message); Object.setPrototypeOf(this, ValidationError.prototype); } } exports.ValidationError = ValidationError; //# sourceMappingURL=validation-error.js.map /***/ }), /***/ 98447: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.validateGraph = void 0; const graphlib = __webpack_require__(45488); const errors_1 = __webpack_require__(297); function assert(condition, msg) { if (!condition) { throw new errors_1.ValidationError(msg); } } function validateGraph(graph, rootNodeId, pkgs, pkgNodes) { assert((graph.predecessors(rootNodeId) || []).length === 0, `"${rootNodeId}" is not really the root`); const reachableFromRoot = graphlib.alg.postorder(graph, [rootNodeId]); const nodeIds = graph.nodes(); assert(JSON.stringify(nodeIds.sort()) === JSON.stringify(reachableFromRoot.sort()), 'not all graph nodes are reachable from root'); const pkgIds = Object.keys(pkgs); const pkgsWithoutInstances = pkgIds.filter((pkgId) => !pkgNodes[pkgId] || pkgNodes[pkgId].size === 0); assert(pkgsWithoutInstances.length === 0, 'not all pkgs have instance nodes'); } exports.validateGraph = validateGraph; //# sourceMappingURL=validate-graph.js.map /***/ }), /***/ 4377: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.dfs = void 0; const each = __webpack_require__(43590); /* * A helper that preforms a pre- or post-order traversal on the input graph * and returns the nodes in the order they were visited. If the graph is * undirected then this algorithm will navigate using neighbors. If the graph * is directed then this algorithm will navigate using successors. * * Order must be one of "pre" or "post". */ function dfs(g, vs, order) { if (!Array.isArray(vs)) { vs = [vs]; } const navigation = (g.isDirected() ? g.successors : g.neighbors).bind(g); const acc = []; const visited = {}; each(vs, (v) => { if (!g.hasNode(v)) { throw new Error('Graph does not have node: ' + v); } doDfs(g, v, order === 'post', visited, navigation, acc); }); return acc; } exports.dfs = dfs; function doDfs(g, v, postorder, visited, navigation, acc) { if (!(v in visited)) { visited[v] = true; if (!postorder) { acc.push(v); } each(navigation(v), function (w) { doDfs(g, w, postorder, visited, navigation, acc); }); if (postorder) { acc.push(v); } } } //# sourceMappingURL=dfs.js.map /***/ }), /***/ 29162: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isAcyclic = void 0; const topsort_1 = __webpack_require__(72118); function isAcyclic(g) { try { topsort_1.topsort(g); } catch (e) { if (e instanceof topsort_1.CycleException) { return false; } throw e; } return true; } exports.isAcyclic = isAcyclic; //# sourceMappingURL=is-acyclic.js.map /***/ }), /***/ 10661: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.postorder = void 0; const dfs_1 = __webpack_require__(4377); function postorder(g, vs) { return dfs_1.dfs(g, vs, 'post'); } exports.postorder = postorder; //# sourceMappingURL=postorder.js.map /***/ }), /***/ 72118: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CycleException = exports.topsort = void 0; const each = __webpack_require__(43590); const size = __webpack_require__(27946); function topsort(g) { const visited = {}; const stack = {}; const results = []; function visit(node) { if (node in stack) { throw new CycleException(); } if (!(node in visited)) { stack[node] = true; visited[node] = true; each(g.predecessors(node), visit); delete stack[node]; results.push(node); } } each(g.sinks(), visit); if (size(visited) !== g.nodeCount()) { throw new CycleException(); } return results; } exports.topsort = topsort; class CycleException extends Error { } exports.CycleException = CycleException; //# sourceMappingURL=topsort.js.map /***/ }), /***/ 74699: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Graph = void 0; /* eslint-disable prefer-rest-params */ /* eslint-disable @typescript-eslint/no-this-alias */ const constant = __webpack_require__(4254); const each = __webpack_require__(43590); const _filter = __webpack_require__(43590); const isEmpty = __webpack_require__(99245); const isFunction = __webpack_require__(98423); const isUndefined = __webpack_require__(28801); const keys = __webpack_require__(44799); const reduce = __webpack_require__(34766); const union = __webpack_require__(96744); const values = __webpack_require__(17720); const DEFAULT_EDGE_NAME = '\x00'; const GRAPH_NODE = '\x00'; const EDGE_KEY_DELIM = '\x01'; // Implementation notes: // // * Node id query functions should return string ids for the nodes // * Edge id query functions should return an "edgeObj", edge object, that is // composed of enough information to uniquely identify an edge: {v, w, name}. // * Internally we use an "edgeId", a stringified form of the edgeObj, to // reference edges. This is because we need a performant way to look these // edges up and, object properties, which have string keys, are the closest // we're going to get to a performant hashtable in JavaScript. class Graph { constructor(opts) { var _a, _b, _c; /* Number of nodes in the graph. Should only be changed by the implementation. */ this._nodeCount = 0; /* Number of edges in the graph. Should only be changed by the implementation. */ this._edgeCount = 0; this._isDirected = (_a = opts === null || opts === void 0 ? void 0 : opts.directed) !== null && _a !== void 0 ? _a : true; this._isMultigraph = (_b = opts === null || opts === void 0 ? void 0 : opts.multigraph) !== null && _b !== void 0 ? _b : false; this._isCompound = (_c = opts === null || opts === void 0 ? void 0 : opts.compound) !== null && _c !== void 0 ? _c : false; // Label for the graph itself this._label = undefined; // Defaults to be set when creating a new node this._defaultNodeLabelFn = constant(undefined); // Defaults to be set when creating a new edge this._defaultEdgeLabelFn = constant(undefined); // v -> label this._nodes = {}; if (this._isCompound) { // v -> parent this._parent = {}; // v -> children this._children = {}; this._children[GRAPH_NODE] = {}; } // v -> edgeObj this._in = {}; // u -> v -> Number this._preds = {}; // v -> edgeObj this._out = {}; // v -> w -> Number this._sucs = {}; // e -> edgeObj this._edgeObjs = {}; // e -> label this._edgeLabels = {}; } /* === Graph functions ========= */ isDirected() { return this._isDirected; } isMultigraph() { return this._isMultigraph; } isCompound() { return this._isCompound; } setGraph(label) { this._label = label; return this; } graph() { return this._label; } /* === Node functions ========== */ setDefaultNodeLabel(newDefault) { if (!isFunction(newDefault)) { newDefault = constant(newDefault); } this._defaultNodeLabelFn = newDefault; return this; } nodeCount() { return this._nodeCount; } nodes() { return keys(this._nodes); } sources() { const self = this; return _filter(this.nodes(), function (v) { return isEmpty(self._in[v]); }); } sinks() { const self = this; return _filter(this.nodes(), function (v) { return isEmpty(self._out[v]); }); } setNodes(vs, value) { const args = arguments; const self = this; each(vs, function (v) { if (args.length > 1) { self.setNode(v, value); } else { self.setNode(v); } }); return this; } setNode(v, value) { if (v in this._nodes) { if (arguments.length > 1) { this._nodes[v] = value; } return this; } this._nodes[v] = arguments.length > 1 ? value : this._defaultNodeLabelFn(v); if (this._isCompound) { this._parent[v] = GRAPH_NODE; this._children[v] = {}; this._children[GRAPH_NODE][v] = true; } this._in[v] = {}; this._preds[v] = {}; this._out[v] = {}; this._sucs[v] = {}; ++this._nodeCount; return this; } node(v) { return this._nodes[v]; } hasNode(v) { return v in this._nodes; } removeNode(v) { const self = this; if (v in this._nodes) { const removeEdge = function (e) { self.removeEdge(self._edgeObjs[e]); }; delete this._nodes[v]; if (this._isCompound) { this._removeFromParentsChildList(v); delete this._parent[v]; each(this.children(v), function (child) { self.setParent(child); }); delete this._children[v]; } each(keys(this._in[v]), removeEdge); delete this._in[v]; delete this._preds[v]; each(keys(this._out[v]), removeEdge); delete this._out[v]; delete this._sucs[v]; --this._nodeCount; } return this; } setParent(v, parent) { if (!this._isCompound) { throw new Error('Cannot set parent in a non-compound graph'); } if (isUndefined(parent)) { parent = GRAPH_NODE; } else { // Coerce parent to string parent += ''; for (let ancestor = parent; !isUndefined(ancestor); ancestor = this.parent(ancestor)) { if (ancestor === v) { throw new Error('Setting ' + parent + ' as parent of ' + v + ' would create a cycle'); } } this.setNode(parent); } this.setNode(v); this._removeFromParentsChildList(v); this._parent[v] = parent; this._children[parent][v] = true; return this; } _removeFromParentsChildList(v) { delete this._children[this._parent[v]][v]; } parent(v) { if (this._isCompound) { const parent = this._parent[v]; if (parent !== GRAPH_NODE) { return parent; } } } children(v) { if (isUndefined(v)) { v = GRAPH_NODE; } if (this._isCompound) { const children = this._children[v]; if (children) { return keys(children); } } else if (v === GRAPH_NODE) { return this.nodes(); } else if (this.hasNode(v)) { return []; } } predecessors(v) { const predsV = this._preds[v]; if (predsV) { return keys(predsV); } } successors(v) { const sucsV = this._sucs[v]; if (sucsV) { return keys(sucsV); } } neighbors(v) { const preds = this.predecessors(v); if (preds) { return union(preds, this.successors(v)); } } isLeaf(v) { let neighbors; if (this.isDirected()) { neighbors = this.successors(v); } else { neighbors = this.neighbors(v); } return neighbors.length === 0; } filterNodes(filter) { const copy = new Graph({ directed: this._isDirected, multigraph: this._isMultigraph, compound: this._isCompound, }); copy.setGraph(this.graph()); const self = this; each(this._nodes, function (value, v) { if (filter(v)) { copy.setNode(v, value); } }); each(this._edgeObjs, function (e) { if (copy.hasNode(e.v) && copy.hasNode(e.w)) { copy.setEdge(e, self.edge(e)); } }); const parents = {}; function findParent(v) { const parent = self.parent(v); if (parent === undefined || copy.hasNode(parent)) { parents[v] = parent; return parent; } else if (parent in parents) { return parents[parent]; } else { return findParent(parent); } } if (this._isCompound) { each(copy.nodes(), function (v) { copy.setParent(v, findParent(v)); }); } return copy; } /* === Edge functions ========== */ setDefaultEdgeLabel(newDefault) { if (!isFunction(newDefault)) { newDefault = constant(newDefault); } this._defaultEdgeLabelFn = newDefault; return this; } edgeCount() { return this._edgeCount; } edges() { return values(this._edgeObjs); } setPath(vs, value) { const self = this; const args = arguments; reduce(vs, function (v, w) { if (args.length > 1) { self.setEdge(v, w, value); } else { self.setEdge(v, w); } return w; }); return this; } // eslint-disable-next-line @typescript-eslint/no-unused-vars setEdge(...args) { let v, w, name, value; let valueSpecified = false; const arg0 = arguments[0]; if (typeof arg0 === 'object' && arg0 !== null && 'v' in arg0) { v = arg0.v; w = arg0.w; name = arg0.name; if (arguments.length === 2) { value = arguments[1]; valueSpecified = true; } } else { v = arg0; w = arguments[1]; name = arguments[3]; if (arguments.length > 2) { value = arguments[2]; valueSpecified = true; } } v = '' + v; w = '' + w; if (!isUndefined(name)) { name = '' + name; } const e = edgeArgsToId(this._isDirected, v, w, name); if (e in this._edgeLabels) { if (valueSpecified) { this._edgeLabels[e] = value; } return this; } if (!isUndefined(name) && !this._isMultigraph) { throw new Error('Cannot set a named edge when isMultigraph = false'); } // It didn't exist, so we need to create it. // First ensure the nodes exist. this.setNode(v); this.setNode(w); this._edgeLabels[e] = valueSpecified ? value : this._defaultEdgeLabelFn(v, w, name); const edgeObj = edgeArgsToObj(this._isDirected, v, w, name); // Ensure we add undirected edges in a consistent way. v = edgeObj.v; w = edgeObj.w; Object.freeze(edgeObj); this._edgeObjs[e] = edgeObj; incrementOrInitEntry(this._preds[w], v); incrementOrInitEntry(this._sucs[v], w); this._in[w][e] = edgeObj; this._out[v][e] = edgeObj; this._edgeCount++; return this; } edge(v, w, name) { const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); return this._edgeLabels[e]; } hasEdge(v, w, name) { const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); return e in this._edgeLabels; } removeEdge(v, w, name) { const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); const edge = this._edgeObjs[e]; if (edge) { v = edge.v; w = edge.w; delete this._edgeLabels[e]; delete this._edgeObjs[e]; decrementOrRemoveEntry(this._preds[w], v); decrementOrRemoveEntry(this._sucs[v], w); delete this._in[w][e]; delete this._out[v][e]; this._edgeCount--; } return this; } inEdges(v, u) { const inV = this._in[v]; if (inV) { const edges = values(inV); if (!u) { return edges; } return _filter(edges, function (edge) { return edge.v === u; }); } } outEdges(v, w) { const outV = this._out[v]; if (outV) { const edges = values(outV); if (!w) { return edges; } return _filter(edges, function (edge) { return edge.w === w; }); } } nodeEdges(v, w) { const inEdges = this.inEdges(v, w); if (inEdges) { return inEdges.concat(this.outEdges(v, w)); } } } exports.Graph = Graph; function incrementOrInitEntry(map, k) { if (map[k]) { map[k]++; } else { map[k] = 1; } } function decrementOrRemoveEntry(map, k) { if (!--map[k]) { delete map[k]; } } function edgeArgsToId(isDirected, v_, w_, name) { let v = '' + v_; let w = '' + w_; if (!isDirected && v > w) { const tmp = v; v = w; w = tmp; } return (v + EDGE_KEY_DELIM + w + EDGE_KEY_DELIM + (isUndefined(name) ? DEFAULT_EDGE_NAME : name)); } function edgeArgsToObj(isDirected, v_, w_, name) { let v = '' + v_; let w = '' + w_; if (!isDirected && v > w) { const tmp = v; v = w; w = tmp; } const edgeObj = { v: v, w: w }; if (name) { edgeObj.name = name; } return edgeObj; } function edgeObjToId(isDirected, edgeObj) { return edgeArgsToId(isDirected, edgeObj.v, edgeObj.w, edgeObj.name); } //# sourceMappingURL=graph.js.map /***/ }), /***/ 45488: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.alg = exports.Graph = void 0; var graph_1 = __webpack_require__(74699); Object.defineProperty(exports, "Graph", ({ enumerable: true, get: function () { return graph_1.Graph; } })); const is_acyclic_1 = __webpack_require__(29162); const postorder_1 = __webpack_require__(10661); exports.alg = { isAcyclic: is_acyclic_1.isAcyclic, postorder: postorder_1.postorder, }; //# sourceMappingURL=index.js.map /***/ }), /***/ 7377: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.legacy = exports.Errors = exports.DepGraphBuilder = exports.createFromJSON = void 0; var create_from_json_1 = __webpack_require__(47020); Object.defineProperty(exports, "createFromJSON", ({ enumerable: true, get: function () { return create_from_json_1.createFromJSON; } })); var builder_1 = __webpack_require__(54039); Object.defineProperty(exports, "DepGraphBuilder", ({ enumerable: true, get: function () { return builder_1.DepGraphBuilder; } })); const Errors = __webpack_require__(297); exports.Errors = Errors; const legacy = __webpack_require__(58994); exports.legacy = legacy; //# sourceMappingURL=index.js.map /***/ }), /***/ 5828: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.partitionCycles = exports.getCycle = void 0; function getCycle(ancestors, nodeId) { if (!ancestors.includes(nodeId)) { return null; } // first item is where the cycle starts and ends. return ancestors.slice(ancestors.indexOf(nodeId)); } exports.getCycle = getCycle; function partitionCycles(nodeId, allCyclesTheNodeIsPartOf) { const cyclesStartWithThisNode = []; const cyclesWithThisNode = []; for (const cycle of allCyclesTheNodeIsPartOf) { const nodeStartsCycle = cycle[0] === nodeId; if (nodeStartsCycle) { cyclesStartWithThisNode.push(cycle); } else { cyclesWithThisNode.push(cycle); } } return { cyclesStartWithThisNode, cyclesWithThisNode }; } exports.partitionCycles = partitionCycles; //# sourceMappingURL=cycles.js.map /***/ }), /***/ 58994: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.graphToDepTree = exports.depTreeToGraph = void 0; const crypto = __webpack_require__(6113); const event_loop_spinner_1 = __webpack_require__(77158); const builder_1 = __webpack_require__(54039); const objectHash = __webpack_require__(41006); const cycles_1 = __webpack_require__(5828); const memiozation_1 = __webpack_require__(24804); function addLabel(dep, key, value) { if (!dep.labels) { dep.labels = {}; } dep.labels[key] = value; } /** * @deprecated Don't use dep trees as an intermediate step, because they are * large structures, resulting in high memory usage and high CPU costs from * serializing / deserializing. Instead, create a graph directly with * {@link DepGraphBuilder} */ async function depTreeToGraph(depTree, pkgManagerName) { const rootPkg = { name: depTree.name, version: depTree.version || undefined, }; const pkgManagerInfo = { name: pkgManagerName, }; const targetOS = depTree.targetOS; if (targetOS) { pkgManagerInfo.repositories = [ { alias: `${targetOS.name}:${targetOS.version}`, }, ]; } const builder = new builder_1.DepGraphBuilder(pkgManagerInfo, rootPkg); await buildGraph(builder, depTree, depTree.name, true); const depGraph = await builder.build(); return shortenNodeIds(depGraph); } exports.depTreeToGraph = depTreeToGraph; async function buildGraph(builder, depTree, pkgName, isRoot = false, memoizationMap = new Map()) { if (memoizationMap.has(depTree)) { return memoizationMap.get(depTree); } const getNodeId = (name, version, hashId) => `${name}@${version || ''}|${hashId}`; const depNodesIds = []; const hash = crypto.createHash('sha1'); if (depTree.versionProvenance) { hash.update(objectHash(depTree.versionProvenance)); } if (depTree.labels) { hash.update(objectHash(depTree.labels)); } const deps = depTree.dependencies || {}; // filter-out invalid null deps (shouldn't happen - but did...) const depNames = Object.keys(deps).filter((d) => !!deps[d]); for (const depName of depNames.sort()) { const dep = deps[depName]; const subtreeHash = await buildGraph(builder, dep, depName, false, memoizationMap); const depPkg = { name: depName, version: dep.version, }; const depNodeId = getNodeId(depPkg.name, depPkg.version, subtreeHash); depNodesIds.push(depNodeId); const nodeInfo = {}; if (dep.versionProvenance) { nodeInfo.versionProvenance = dep.versionProvenance; } if (dep.labels) { nodeInfo.labels = dep.labels; } builder.addPkgNode(depPkg, depNodeId, nodeInfo); hash.update(depNodeId); } const treeHash = hash.digest('hex'); let pkgNodeId; if (isRoot) { pkgNodeId = builder.rootNodeId; } else { // we don't assume depTree has a .name to support output of `npm list --json` const pkg = { name: pkgName, version: depTree.version, }; pkgNodeId = getNodeId(pkg.name, pkg.version, treeHash); const nodeInfo = {}; if (depTree.versionProvenance) { nodeInfo.versionProvenance = depTree.versionProvenance; } if (depTree.labels) { nodeInfo.labels = depTree.labels; } builder.addPkgNode(pkg, pkgNodeId, nodeInfo); } for (const depNodeId of depNodesIds) { builder.connectDep(pkgNodeId, depNodeId); } if (depNodesIds.length > 0 && event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } memoizationMap.set(depTree, treeHash); return treeHash; } async function shortenNodeIds(depGraph) { const builder = new builder_1.DepGraphBuilder(depGraph.pkgManager, depGraph.rootPkg); const nodesMap = {}; // create nodes with shorter ids for (const pkg of depGraph.getPkgs()) { const nodeIds = depGraph.getPkgNodeIds(pkg); for (let i = 0; i < nodeIds.length; i++) { const nodeId = nodeIds[i]; if (nodeId === depGraph.rootNodeId) { continue; } const nodeInfo = depGraph.getNode(nodeId); let newNodeId; if (nodeIds.length === 1) { newNodeId = `${trimAfterLastSep(nodeId, '|')}`; } else { newNodeId = `${trimAfterLastSep(nodeId, '|')}|${i + 1}`; } nodesMap[nodeId] = newNodeId; builder.addPkgNode(pkg, newNodeId, nodeInfo); } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } // connect nodes for (const pkg of depGraph.getPkgs()) { for (const nodeId of depGraph.getPkgNodeIds(pkg)) { for (const depNodeId of depGraph.getNodeDepsNodeIds(nodeId)) { const parentNode = nodesMap[nodeId] || nodeId; const childNode = nodesMap[depNodeId] || depNodeId; builder.connectDep(parentNode, childNode); } } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } return builder.build(); } /** * @deprecated Don't use dep trees. You should adapt your code to use graphs, * and enhance the dep-graph library if there is missing functionality from * the graph structure */ async function graphToDepTree(depGraphInterface, pkgType, opts = { deduplicateWithinTopLevelDeps: false }) { const depGraph = depGraphInterface; const [depTree] = await buildSubtree(depGraph, depGraph.rootNodeId, opts.deduplicateWithinTopLevelDeps ? null : false); depTree.type = depGraph.pkgManager.name; depTree.packageFormatVersion = constructPackageFormatVersion(pkgType); const targetOS = constructTargetOS(depGraph); if (targetOS) { depTree.targetOS = targetOS; } return depTree; } exports.graphToDepTree = graphToDepTree; function constructPackageFormatVersion(pkgType) { if (pkgType === 'maven') { pkgType = 'mvn'; } return `${pkgType}:0.0.1`; } function constructTargetOS(depGraph) { if (['apk', 'apt', 'deb', 'rpm', 'linux'].indexOf(depGraph.pkgManager.name) === -1) { // .targetOS is undefined unless its a linux pkgManager return; } if (!depGraph.pkgManager.repositories || !depGraph.pkgManager.repositories.length || !depGraph.pkgManager.repositories[0].alias) { throw new Error('Incomplete .pkgManager, could not create .targetOS'); } const [name, version] = depGraph.pkgManager.repositories[0].alias.split(':'); return { name, version }; } async function buildSubtree(depGraph, nodeId, maybeDeduplicationSet = false, // false = disabled; null = not in deduplication scope yet ancestors = [], memoizationMap = new Map()) { if (!maybeDeduplicationSet) { const memoizedDepTree = memiozation_1.getMemoizedDepTree(nodeId, ancestors, memoizationMap); if (memoizedDepTree) { return [memoizedDepTree, undefined]; } } const isRoot = nodeId === depGraph.rootNodeId; const nodePkg = depGraph.getNodePkg(nodeId); const nodeInfo = depGraph.getNode(nodeId); const depTree = {}; depTree.name = nodePkg.name; depTree.version = nodePkg.version; if (nodeInfo.versionProvenance) { depTree.versionProvenance = nodeInfo.versionProvenance; } if (nodeInfo.labels) { depTree.labels = Object.assign({}, nodeInfo.labels); } const depInstanceIds = depGraph.getNodeDepsNodeIds(nodeId); if (!depInstanceIds || depInstanceIds.length === 0) { memoizationMap.set(nodeId, { depTree }); return [depTree, undefined]; } const cycle = cycles_1.getCycle(ancestors, nodeId); if (cycle) { // This node starts a cycle and now it's the second visit. addLabel(depTree, 'pruned', 'cyclic'); return [depTree, [cycle]]; } if (maybeDeduplicationSet) { if (maybeDeduplicationSet.has(nodeId)) { if (depInstanceIds.length > 0) { addLabel(depTree, 'pruned', 'true'); } return [depTree, undefined]; } maybeDeduplicationSet.add(nodeId); } const cycles = []; for (const depInstId of depInstanceIds) { // Deduplication of nodes occurs only within a scope of a top-level dependency. // Therefore, every top-level dep gets an independent set to track duplicates. if (isRoot && maybeDeduplicationSet !== false) { maybeDeduplicationSet = new Set(); } const [subtree, subtreeCycles] = await buildSubtree(depGraph, depInstId, maybeDeduplicationSet, ancestors.concat(nodeId), memoizationMap); if (subtreeCycles) { for (const cycle of subtreeCycles) { cycles.push(cycle); } } if (!subtree) { continue; } if (!depTree.dependencies) { depTree.dependencies = {}; } depTree.dependencies[subtree.name] = subtree; } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } const partitionedCycles = cycles_1.partitionCycles(nodeId, cycles); memiozation_1.memoize(nodeId, memoizationMap, depTree, partitionedCycles); return [depTree, partitionedCycles.cyclesWithThisNode]; } function trimAfterLastSep(str, sep) { return str.slice(0, str.lastIndexOf(sep)); } //# sourceMappingURL=index.js.map /***/ }), /***/ 24804: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getMemoizedDepTree = exports.memoize = void 0; function memoize(nodeId, memoizationMap, depTree, partitionedCycles) { const { cyclesStartWithThisNode, cyclesWithThisNode } = partitionedCycles; if (cyclesStartWithThisNode.length > 0) { const cycleNodeIds = new Set(...cyclesStartWithThisNode); memoizationMap.set(nodeId, { depTree, cycleNodeIds }); } else if (cyclesWithThisNode.length === 0) { memoizationMap.set(nodeId, { depTree }); } // Don't memoize nodes in cycles (cyclesWithThisNode.length > 0) } exports.memoize = memoize; function getMemoizedDepTree(nodeId, ancestors, memoizationMap) { if (!memoizationMap.has(nodeId)) return null; const { depTree, cycleNodeIds } = memoizationMap.get(nodeId); if (!cycleNodeIds) return depTree; const ancestorsArePartOfTheCycle = ancestors.some((nodeId) => cycleNodeIds.has(nodeId)); return ancestorsArePartOfTheCycle ? null : depTree; } exports.getMemoizedDepTree = getMemoizedDepTree; //# sourceMappingURL=memiozation.js.map /***/ }), /***/ 5146: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // A linked list to keep track of recently-used-ness const Yallist = __webpack_require__(52426) const MAX = Symbol('max') const LENGTH = Symbol('length') const LENGTH_CALCULATOR = Symbol('lengthCalculator') const ALLOW_STALE = Symbol('allowStale') const MAX_AGE = Symbol('maxAge') const DISPOSE = Symbol('dispose') const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') const LRU_LIST = Symbol('lruList') const CACHE = Symbol('cache') const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') const naiveLength = () => 1 // lruList is a yallist where the head is the youngest // item, and the tail is the oldest. the list contains the Hit // objects as the entries. // Each Hit object has a reference to its Yallist.Node. This // never changes. // // cache is a Map (or PseudoMap) that matches the keys to // the Yallist.Node object. class LRUCache { constructor (options) { if (typeof options === 'number') options = { max: options } if (!options) options = {} if (options.max && (typeof options.max !== 'number' || options.max < 0)) throw new TypeError('max must be a non-negative number') // Kind of weird to have a default max of Infinity, but oh well. const max = this[MAX] = options.max || Infinity const lc = options.length || naiveLength this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc this[ALLOW_STALE] = options.stale || false if (options.maxAge && typeof options.maxAge !== 'number') throw new TypeError('maxAge must be a number') this[MAX_AGE] = options.maxAge || 0 this[DISPOSE] = options.dispose this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false this.reset() } // resize the cache when the max changes. set max (mL) { if (typeof mL !== 'number' || mL < 0) throw new TypeError('max must be a non-negative number') this[MAX] = mL || Infinity trim(this) } get max () { return this[MAX] } set allowStale (allowStale) { this[ALLOW_STALE] = !!allowStale } get allowStale () { return this[ALLOW_STALE] } set maxAge (mA) { if (typeof mA !== 'number') throw new TypeError('maxAge must be a non-negative number') this[MAX_AGE] = mA trim(this) } get maxAge () { return this[MAX_AGE] } // resize the cache when the lengthCalculator changes. set lengthCalculator (lC) { if (typeof lC !== 'function') lC = naiveLength if (lC !== this[LENGTH_CALCULATOR]) { this[LENGTH_CALCULATOR] = lC this[LENGTH] = 0 this[LRU_LIST].forEach(hit => { hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) this[LENGTH] += hit.length }) } trim(this) } get lengthCalculator () { return this[LENGTH_CALCULATOR] } get length () { return this[LENGTH] } get itemCount () { return this[LRU_LIST].length } rforEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].tail; walker !== null;) { const prev = walker.prev forEachStep(this, fn, walker, thisp) walker = prev } } forEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].head; walker !== null;) { const next = walker.next forEachStep(this, fn, walker, thisp) walker = next } } keys () { return this[LRU_LIST].toArray().map(k => k.key) } values () { return this[LRU_LIST].toArray().map(k => k.value) } reset () { if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) { this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) } this[CACHE] = new Map() // hash of items by key this[LRU_LIST] = new Yallist() // list of items in order of use recency this[LENGTH] = 0 // length of items in the list } dump () { return this[LRU_LIST].map(hit => isStale(this, hit) ? false : { k: hit.key, v: hit.value, e: hit.now + (hit.maxAge || 0) }).toArray().filter(h => h) } dumpLru () { return this[LRU_LIST] } set (key, value, maxAge) { maxAge = maxAge || this[MAX_AGE] if (maxAge && typeof maxAge !== 'number') throw new TypeError('maxAge must be a number') const now = maxAge ? Date.now() : 0 const len = this[LENGTH_CALCULATOR](value, key) if (this[CACHE].has(key)) { if (len > this[MAX]) { del(this, this[CACHE].get(key)) return false } const node = this[CACHE].get(key) const item = node.value // dispose of the old one before overwriting // split out into 2 ifs for better coverage tracking if (this[DISPOSE]) { if (!this[NO_DISPOSE_ON_SET]) this[DISPOSE](key, item.value) } item.now = now item.maxAge = maxAge item.value = value this[LENGTH] += len - item.length item.length = len this.get(key) trim(this) return true } const hit = new Entry(key, value, len, now, maxAge) // oversized objects fall out of cache automatically. if (hit.length > this[MAX]) { if (this[DISPOSE]) this[DISPOSE](key, value) return false } this[LENGTH] += hit.length this[LRU_LIST].unshift(hit) this[CACHE].set(key, this[LRU_LIST].head) trim(this) return true } has (key) { if (!this[CACHE].has(key)) return false const hit = this[CACHE].get(key).value return !isStale(this, hit) } get (key) { return get(this, key, true) } peek (key) { return get(this, key, false) } pop () { const node = this[LRU_LIST].tail if (!node) return null del(this, node) return node.value } del (key) { del(this, this[CACHE].get(key)) } load (arr) { // reset the cache this.reset() const now = Date.now() // A previous serialized cache has the most recent items first for (let l = arr.length - 1; l >= 0; l--) { const hit = arr[l] const expiresAt = hit.e || 0 if (expiresAt === 0) // the item was created without expiration in a non aged cache this.set(hit.k, hit.v) else { const maxAge = expiresAt - now // dont add already expired items if (maxAge > 0) { this.set(hit.k, hit.v, maxAge) } } } } prune () { this[CACHE].forEach((value, key) => get(this, key, false)) } } const get = (self, key, doUse) => { const node = self[CACHE].get(key) if (node) { const hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) return undefined } else { if (doUse) { if (self[UPDATE_AGE_ON_GET]) node.value.now = Date.now() self[LRU_LIST].unshiftNode(node) } } return hit.value } } const isStale = (self, hit) => { if (!hit || (!hit.maxAge && !self[MAX_AGE])) return false const diff = Date.now() - hit.now return hit.maxAge ? diff > hit.maxAge : self[MAX_AGE] && (diff > self[MAX_AGE]) } const trim = self => { if (self[LENGTH] > self[MAX]) { for (let walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) { // We know that we're about to delete this one, and also // what the next least recently used key will be, so just // go ahead and set it now. const prev = walker.prev del(self, walker) walker = prev } } } const del = (self, node) => { if (node) { const hit = node.value if (self[DISPOSE]) self[DISPOSE](hit.key, hit.value) self[LENGTH] -= hit.length self[CACHE].delete(hit.key) self[LRU_LIST].removeNode(node) } } class Entry { constructor (key, value, length, now, maxAge) { this.key = key this.value = value this.length = length this.now = now this.maxAge = maxAge || 0 } } const forEachStep = (self, fn, node, thisp) => { let hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) hit = undefined } if (hit) fn.call(thisp, hit.value, hit.key, self) } module.exports = LRUCache /***/ }), /***/ 41006: /***/ ((module, exports, __webpack_require__) => { "use strict"; var crypto = __webpack_require__(6113); /** * Exported function * * Options: * * - `algorithm` hash algo to be used by this instance: *'sha1', 'md5' * - `excludeValues` {true|*false} hash object keys, values ignored * - `encoding` hash encoding, supports 'buffer', '*hex', 'binary', 'base64' * - `ignoreUnknown` {true|*false} ignore unknown object types * - `replacer` optional function that replaces values before hashing * - `respectFunctionProperties` {*true|false} consider function properties when hashing * - `respectFunctionNames` {*true|false} consider 'name' property of functions for hashing * - `respectType` {*true|false} Respect special properties (prototype, constructor) * when hashing to distinguish between types * - `unorderedArrays` {true|*false} Sort all arrays before hashing * - `unorderedSets` {*true|false} Sort `Set` and `Map` instances before hashing * * = default * * @param {object} object value to hash * @param {object} options hashing options * @return {string} hash value * @api public */ exports = module.exports = objectHash; function objectHash(object, options){ options = applyDefaults(object, options); return hash(object, options); } /** * Exported sugar methods * * @param {object} object value to hash * @return {string} hash value * @api public */ exports.sha1 = function(object){ return objectHash(object); }; exports.keys = function(object){ return objectHash(object, {excludeValues: true, algorithm: 'sha1', encoding: 'hex'}); }; exports.MD5 = function(object){ return objectHash(object, {algorithm: 'md5', encoding: 'hex'}); }; exports.keysMD5 = function(object){ return objectHash(object, {algorithm: 'md5', encoding: 'hex', excludeValues: true}); }; // Internals var hashes = crypto.getHashes ? crypto.getHashes().slice() : ['sha1', 'md5']; hashes.push('passthrough'); var encodings = ['buffer', 'hex', 'binary', 'base64']; function applyDefaults(object, sourceOptions){ sourceOptions = sourceOptions || {}; // create a copy rather than mutating var options = {}; options.algorithm = sourceOptions.algorithm || 'sha1'; options.encoding = sourceOptions.encoding || 'hex'; options.excludeValues = sourceOptions.excludeValues ? true : false; options.algorithm = options.algorithm.toLowerCase(); options.encoding = options.encoding.toLowerCase(); options.ignoreUnknown = sourceOptions.ignoreUnknown !== true ? false : true; // default to false options.respectType = sourceOptions.respectType === false ? false : true; // default to true options.respectFunctionNames = sourceOptions.respectFunctionNames === false ? false : true; options.respectFunctionProperties = sourceOptions.respectFunctionProperties === false ? false : true; options.unorderedArrays = sourceOptions.unorderedArrays !== true ? false : true; // default to false options.unorderedSets = sourceOptions.unorderedSets === false ? false : true; // default to false options.unorderedObjects = sourceOptions.unorderedObjects === false ? false : true; // default to true options.replacer = sourceOptions.replacer || undefined; options.excludeKeys = sourceOptions.excludeKeys || undefined; if(typeof object === 'undefined') { throw new Error('Object argument required.'); } // if there is a case-insensitive match in the hashes list, accept it // (i.e. SHA256 for sha256) for (var i = 0; i < hashes.length; ++i) { if (hashes[i].toLowerCase() === options.algorithm.toLowerCase()) { options.algorithm = hashes[i]; } } if(hashes.indexOf(options.algorithm) === -1){ throw new Error('Algorithm "' + options.algorithm + '" not supported. ' + 'supported values: ' + hashes.join(', ')); } if(encodings.indexOf(options.encoding) === -1 && options.algorithm !== 'passthrough'){ throw new Error('Encoding "' + options.encoding + '" not supported. ' + 'supported values: ' + encodings.join(', ')); } return options; } /** Check if the given function is a native function */ function isNativeFunction(f) { if ((typeof f) !== 'function') { return false; } var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i; return exp.exec(Function.prototype.toString.call(f)) != null; } function hash(object, options) { var hashingStream; if (options.algorithm !== 'passthrough') { hashingStream = crypto.createHash(options.algorithm); } else { hashingStream = new PassThrough(); } if (typeof hashingStream.write === 'undefined') { hashingStream.write = hashingStream.update; hashingStream.end = hashingStream.update; } var hasher = typeHasher(options, hashingStream); hasher.dispatch(object); if (!hashingStream.update) { hashingStream.end(''); } if (hashingStream.digest) { return hashingStream.digest(options.encoding === 'buffer' ? undefined : options.encoding); } var buf = hashingStream.read(); if (options.encoding === 'buffer') { return buf; } return buf.toString(options.encoding); } /** * Expose streaming API * * @param {object} object Value to serialize * @param {object} options Options, as for hash() * @param {object} stream A stream to write the serializiation to * @api public */ exports.writeToStream = function(object, options, stream) { if (typeof stream === 'undefined') { stream = options; options = {}; } options = applyDefaults(object, options); return typeHasher(options, stream).dispatch(object); }; function typeHasher(options, writeTo, context){ context = context || []; var write = function(str) { if (writeTo.update) { return writeTo.update(str, 'utf8'); } else { return writeTo.write(str, 'utf8'); } }; return { dispatch: function(value){ if (options.replacer) { value = options.replacer(value); } var type = typeof value; if (value === null) { type = 'null'; } //console.log("[DEBUG] Dispatch: ", value, "->", type, " -> ", "_" + type); return this['_' + type](value); }, _object: function(object) { var pattern = (/\[object (.*)\]/i); var objString = Object.prototype.toString.call(object); var objType = pattern.exec(objString); if (!objType) { // object type did not match [object ...] objType = 'unknown:[' + objString + ']'; } else { objType = objType[1]; // take only the class name } objType = objType.toLowerCase(); var objectNumber = null; if ((objectNumber = context.indexOf(object)) >= 0) { return this.dispatch('[CIRCULAR:' + objectNumber + ']'); } else { context.push(object); } if (typeof Buffer !== 'undefined' && Buffer.isBuffer && Buffer.isBuffer(object)) { write('buffer:'); return write(object); } if(objType !== 'object' && objType !== 'function' && objType !== 'asyncfunction') { if(this['_' + objType]) { this['_' + objType](object); } else if (options.ignoreUnknown) { return write('[' + objType + ']'); } else { throw new Error('Unknown object type "' + objType + '"'); } }else{ var keys = Object.keys(object); if (options.unorderedObjects) { keys = keys.sort(); } // Make sure to incorporate special properties, so // Types with different prototypes will produce // a different hash and objects derived from // different functions (`new Foo`, `new Bar`) will // produce different hashes. // We never do this for native functions since some // seem to break because of that. if (options.respectType !== false && !isNativeFunction(object)) { keys.splice(0, 0, 'prototype', '__proto__', 'constructor'); } if (options.excludeKeys) { keys = keys.filter(function(key) { return !options.excludeKeys(key); }); } write('object:' + keys.length + ':'); var self = this; return keys.forEach(function(key){ self.dispatch(key); write(':'); if(!options.excludeValues) { self.dispatch(object[key]); } write(','); }); } }, _array: function(arr, unordered){ unordered = typeof unordered !== 'undefined' ? unordered : options.unorderedArrays !== false; // default to options.unorderedArrays var self = this; write('array:' + arr.length + ':'); if (!unordered || arr.length <= 1) { return arr.forEach(function(entry) { return self.dispatch(entry); }); } // the unordered case is a little more complicated: // since there is no canonical ordering on objects, // i.e. {a:1} < {a:2} and {a:1} > {a:2} are both false, // we first serialize each entry using a PassThrough stream // before sorting. // also: we can’t use the same context array for all entries // since the order of hashing should *not* matter. instead, // we keep track of the additions to a copy of the context array // and add all of them to the global context array when we’re done var contextAdditions = []; var entries = arr.map(function(entry) { var strm = new PassThrough(); var localContext = context.slice(); // make copy var hasher = typeHasher(options, strm, localContext); hasher.dispatch(entry); // take only what was added to localContext and append it to contextAdditions contextAdditions = contextAdditions.concat(localContext.slice(context.length)); return strm.read().toString(); }); context = context.concat(contextAdditions); entries.sort(); return this._array(entries, false); }, _date: function(date){ return write('date:' + date.toJSON()); }, _symbol: function(sym){ return write('symbol:' + sym.toString()); }, _error: function(err){ return write('error:' + err.toString()); }, _boolean: function(bool){ return write('bool:' + bool.toString()); }, _string: function(string){ write('string:' + string.length + ':'); write(string.toString()); }, _function: function(fn){ write('fn:'); if (isNativeFunction(fn)) { this.dispatch('[native]'); } else { this.dispatch(fn.toString()); } if (options.respectFunctionNames !== false) { // Make sure we can still distinguish native functions // by their name, otherwise String and Function will // have the same hash this.dispatch("function-name:" + String(fn.name)); } if (options.respectFunctionProperties) { this._object(fn); } }, _number: function(number){ return write('number:' + number.toString()); }, _xml: function(xml){ return write('xml:' + xml.toString()); }, _null: function() { return write('Null'); }, _undefined: function() { return write('Undefined'); }, _regexp: function(regex){ return write('regex:' + regex.toString()); }, _uint8array: function(arr){ write('uint8array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _uint8clampedarray: function(arr){ write('uint8clampedarray:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _int8array: function(arr){ write('uint8array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _uint16array: function(arr){ write('uint16array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _int16array: function(arr){ write('uint16array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _uint32array: function(arr){ write('uint32array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _int32array: function(arr){ write('uint32array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _float32array: function(arr){ write('float32array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _float64array: function(arr){ write('float64array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _arraybuffer: function(arr){ write('arraybuffer:'); return this.dispatch(new Uint8Array(arr)); }, _url: function(url) { return write('url:' + url.toString(), 'utf8'); }, _map: function(map) { write('map:'); var arr = Array.from(map); return this._array(arr, options.unorderedSets !== false); }, _set: function(set) { write('set:'); var arr = Array.from(set); return this._array(arr, options.unorderedSets !== false); }, _file: function(file) { write('file:'); return this.dispatch([file.name, file.size, file.type, file.lastModfied]); }, _blob: function() { if (options.ignoreUnknown) { return write('[blob]'); } throw Error('Hashing Blob objects is currently not supported\n' + '(see https://github.com/puleos/object-hash/issues/26)\n' + 'Use "options.replacer" or "options.ignoreUnknown"\n'); }, _domwindow: function() { return write('domwindow'); }, _bigint: function(number){ return write('bigint:' + number.toString()); }, /* Node.js standard native objects */ _process: function() { return write('process'); }, _timer: function() { return write('timer'); }, _pipe: function() { return write('pipe'); }, _tcp: function() { return write('tcp'); }, _udp: function() { return write('udp'); }, _tty: function() { return write('tty'); }, _statwatcher: function() { return write('statwatcher'); }, _securecontext: function() { return write('securecontext'); }, _connection: function() { return write('connection'); }, _zlib: function() { return write('zlib'); }, _context: function() { return write('context'); }, _nodescript: function() { return write('nodescript'); }, _httpparser: function() { return write('httpparser'); }, _dataview: function() { return write('dataview'); }, _signal: function() { return write('signal'); }, _fsevent: function() { return write('fsevent'); }, _tlswrap: function() { return write('tlswrap'); }, }; } // Mini-implementation of stream.PassThrough // We are far from having need for the full implementation, and we can // make assumptions like "many writes, then only one final read" // and we can ignore encoding specifics function PassThrough() { return { buf: '', write: function(b) { this.buf += b; }, end: function(b) { this.buf += b; }, read: function() { return this.buf; } }; } /***/ }), /***/ 54546: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const assert = __webpack_require__(39491) const path = __webpack_require__(71017) const fs = __webpack_require__(57147) let glob = undefined try { glob = __webpack_require__(12884) } catch (_err) { // treat glob as optional. } const defaultGlobOpts = { nosort: true, silent: true } // for EMFILE handling let timeout = 0 const isWindows = (process.platform === "win32") const defaults = options => { const methods = [ 'unlink', 'chmod', 'stat', 'lstat', 'rmdir', 'readdir' ] methods.forEach(m => { options[m] = options[m] || fs[m] m = m + 'Sync' options[m] = options[m] || fs[m] }) options.maxBusyTries = options.maxBusyTries || 3 options.emfileWait = options.emfileWait || 1000 if (options.glob === false) { options.disableGlob = true } if (options.disableGlob !== true && glob === undefined) { throw Error('glob dependency not found, set `options.disableGlob = true` if intentional') } options.disableGlob = options.disableGlob || false options.glob = options.glob || defaultGlobOpts } const rimraf = (p, options, cb) => { if (typeof options === 'function') { cb = options options = {} } assert(p, 'rimraf: missing path') assert.equal(typeof p, 'string', 'rimraf: path should be a string') assert.equal(typeof cb, 'function', 'rimraf: callback function required') assert(options, 'rimraf: invalid options argument provided') assert.equal(typeof options, 'object', 'rimraf: options should be object') defaults(options) let busyTries = 0 let errState = null let n = 0 const next = (er) => { errState = errState || er if (--n === 0) cb(errState) } const afterGlob = (er, results) => { if (er) return cb(er) n = results.length if (n === 0) return cb() results.forEach(p => { const CB = (er) => { if (er) { if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && busyTries < options.maxBusyTries) { busyTries ++ // try again, with the same exact callback as this one. return setTimeout(() => rimraf_(p, options, CB), busyTries * 100) } // this one won't happen if graceful-fs is used. if (er.code === "EMFILE" && timeout < options.emfileWait) { return setTimeout(() => rimraf_(p, options, CB), timeout ++) } // already gone if (er.code === "ENOENT") er = null } timeout = 0 next(er) } rimraf_(p, options, CB) }) } if (options.disableGlob || !glob.hasMagic(p)) return afterGlob(null, [p]) options.lstat(p, (er, stat) => { if (!er) return afterGlob(null, [p]) glob(p, options.glob, afterGlob) }) } // Two possible strategies. // 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR // 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR // // Both result in an extra syscall when you guess wrong. However, there // are likely far more normal files in the world than directories. This // is based on the assumption that a the average number of files per // directory is >= 1. // // If anyone ever complains about this, then I guess the strategy could // be made configurable somehow. But until then, YAGNI. const rimraf_ = (p, options, cb) => { assert(p) assert(options) assert(typeof cb === 'function') // sunos lets the root user unlink directories, which is... weird. // so we have to lstat here and make sure it's not a dir. options.lstat(p, (er, st) => { if (er && er.code === "ENOENT") return cb(null) // Windows can EPERM on stat. Life is suffering. if (er && er.code === "EPERM" && isWindows) fixWinEPERM(p, options, er, cb) if (st && st.isDirectory()) return rmdir(p, options, er, cb) options.unlink(p, er => { if (er) { if (er.code === "ENOENT") return cb(null) if (er.code === "EPERM") return (isWindows) ? fixWinEPERM(p, options, er, cb) : rmdir(p, options, er, cb) if (er.code === "EISDIR") return rmdir(p, options, er, cb) } return cb(er) }) }) } const fixWinEPERM = (p, options, er, cb) => { assert(p) assert(options) assert(typeof cb === 'function') options.chmod(p, 0o666, er2 => { if (er2) cb(er2.code === "ENOENT" ? null : er) else options.stat(p, (er3, stats) => { if (er3) cb(er3.code === "ENOENT" ? null : er) else if (stats.isDirectory()) rmdir(p, options, er, cb) else options.unlink(p, cb) }) }) } const fixWinEPERMSync = (p, options, er) => { assert(p) assert(options) try { options.chmodSync(p, 0o666) } catch (er2) { if (er2.code === "ENOENT") return else throw er } let stats try { stats = options.statSync(p) } catch (er3) { if (er3.code === "ENOENT") return else throw er } if (stats.isDirectory()) rmdirSync(p, options, er) else options.unlinkSync(p) } const rmdir = (p, options, originalEr, cb) => { assert(p) assert(options) assert(typeof cb === 'function') // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) // if we guessed wrong, and it's not a directory, then // raise the original error. options.rmdir(p, er => { if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) rmkids(p, options, cb) else if (er && er.code === "ENOTDIR") cb(originalEr) else cb(er) }) } const rmkids = (p, options, cb) => { assert(p) assert(options) assert(typeof cb === 'function') options.readdir(p, (er, files) => { if (er) return cb(er) let n = files.length if (n === 0) return options.rmdir(p, cb) let errState files.forEach(f => { rimraf(path.join(p, f), options, er => { if (errState) return if (er) return cb(errState = er) if (--n === 0) options.rmdir(p, cb) }) }) }) } // this looks simpler, and is strictly *faster*, but will // tie up the JavaScript thread and fail on excessively // deep directory trees. const rimrafSync = (p, options) => { options = options || {} defaults(options) assert(p, 'rimraf: missing path') assert.equal(typeof p, 'string', 'rimraf: path should be a string') assert(options, 'rimraf: missing options') assert.equal(typeof options, 'object', 'rimraf: options should be object') let results if (options.disableGlob || !glob.hasMagic(p)) { results = [p] } else { try { options.lstatSync(p) results = [p] } catch (er) { results = glob.sync(p, options.glob) } } if (!results.length) return for (let i = 0; i < results.length; i++) { const p = results[i] let st try { st = options.lstatSync(p) } catch (er) { if (er.code === "ENOENT") return // Windows can EPERM on stat. Life is suffering. if (er.code === "EPERM" && isWindows) fixWinEPERMSync(p, options, er) } try { // sunos lets the root user unlink directories, which is... weird. if (st && st.isDirectory()) rmdirSync(p, options, null) else options.unlinkSync(p) } catch (er) { if (er.code === "ENOENT") return if (er.code === "EPERM") return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) if (er.code !== "EISDIR") throw er rmdirSync(p, options, er) } } } const rmdirSync = (p, options, originalEr) => { assert(p) assert(options) try { options.rmdirSync(p) } catch (er) { if (er.code === "ENOENT") return if (er.code === "ENOTDIR") throw originalEr if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") rmkidsSync(p, options) } } const rmkidsSync = (p, options) => { assert(p) assert(options) options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)) // We only end up here once we got ENOTEMPTY at least once, and // at this point, we are guaranteed to have removed all the kids. // So, we know that it won't be ENOENT or ENOTDIR or anything else. // try really hard to delete stuff on windows, because it has a // PROFOUNDLY annoying habit of not closing handles promptly when // files are deleted, resulting in spurious ENOTEMPTY errors. const retries = isWindows ? 100 : 1 let i = 0 do { let threw = true try { const ret = options.rmdirSync(p, options) threw = false return ret } finally { if (++i < retries && threw) continue } } while (true) } module.exports = rimraf rimraf.sync = rimrafSync /***/ }), /***/ 43663: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const ANY = Symbol('SemVer ANY') // hoisted class for cyclic dependency class Comparator { static get ANY () { return ANY } constructor (comp, options) { options = parseOptions(options) if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } comp = comp.trim().split(/\s+/).join(' ') debug('comparator', comp, options) this.options = options this.loose = !!options.loose this.parse(comp) if (this.semver === ANY) { this.value = '' } else { this.value = this.operator + this.semver.version } debug('comp', this) } parse (comp) { const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] const m = comp.match(r) if (!m) { throw new TypeError(`Invalid comparator: ${comp}`) } this.operator = m[1] !== undefined ? m[1] : '' if (this.operator === '=') { this.operator = '' } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY } else { this.semver = new SemVer(m[2], this.options.loose) } } toString () { return this.value } test (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY || version === ANY) { return true } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } return cmp(version, this.operator, this.semver, this.options) } intersects (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (this.operator === '') { if (this.value === '') { return true } return new Range(comp.value, options).test(this.value) } else if (comp.operator === '') { if (comp.value === '') { return true } return new Range(this.value, options).test(comp.semver) } options = parseOptions(options) // Special cases where nothing can possibly be lower if (options.includePrerelease && (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { return false } if (!options.includePrerelease && (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { return false } // Same direction increasing (> or >=) if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { return true } // Same direction decreasing (< or <=) if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { return true } // same SemVer and both sides are inclusive (<= or >=) if ( (this.semver.version === comp.semver.version) && this.operator.includes('=') && comp.operator.includes('=')) { return true } // opposite directions less than if (cmp(this.semver, '<', comp.semver, options) && this.operator.startsWith('>') && comp.operator.startsWith('<')) { return true } // opposite directions greater than if (cmp(this.semver, '>', comp.semver, options) && this.operator.startsWith('<') && comp.operator.startsWith('>')) { return true } return false } } module.exports = Comparator const parseOptions = __webpack_require__(6318) const { safeRe: re, t } = __webpack_require__(73726) const cmp = __webpack_require__(98600) const debug = __webpack_require__(31819) const SemVer = __webpack_require__(46629) const Range = __webpack_require__(87521) /***/ }), /***/ 87521: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // hoisted class for cyclic dependency class Range { constructor (range, options) { options = parseOptions(options) if (range instanceof Range) { if ( range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease ) { return range } else { return new Range(range.raw, options) } } if (range instanceof Comparator) { // just put it in the set and return this.raw = range.value this.set = [[range]] this.format() return this } this.options = options this.loose = !!options.loose this.includePrerelease = !!options.includePrerelease // First reduce all whitespace as much as possible so we do not have to rely // on potentially slow regexes like \s*. This is then stored and used for // future error messages as well. this.raw = range .trim() .split(/\s+/) .join(' ') // First, split on || this.set = this.raw .split('||') // map the range to a 2d array of comparators .map(r => this.parseRange(r.trim())) // throw out any comparator lists that are empty // this generally means that it was not a valid range, which is allowed // in loose mode, but will still throw if the WHOLE range is invalid. .filter(c => c.length) if (!this.set.length) { throw new TypeError(`Invalid SemVer Range: ${this.raw}`) } // if we have any that are not the null set, throw out null sets. if (this.set.length > 1) { // keep the first one, in case they're all null sets const first = this.set[0] this.set = this.set.filter(c => !isNullSet(c[0])) if (this.set.length === 0) { this.set = [first] } else if (this.set.length > 1) { // if we have any that are *, then the range is just * for (const c of this.set) { if (c.length === 1 && isAny(c[0])) { this.set = [c] break } } } } this.format() } format () { this.range = this.set .map((comps) => comps.join(' ').trim()) .join('||') .trim() return this.range } toString () { return this.range } parseRange (range) { // memoize range parsing for performance. // this is a very hot path, and fully deterministic. const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE) const memoKey = memoOpts + ':' + range const cached = cache.get(memoKey) if (cached) { return cached } const loose = this.options.loose // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range) // `~ 1.2.3` => `~1.2.3` range = range.replace(re[t.TILDETRIM], tildeTrimReplace) debug('tilde trim', range) // `^ 1.2.3` => `^1.2.3` range = range.replace(re[t.CARETTRIM], caretTrimReplace) debug('caret trim', range) // At this point, the range is completely trimmed and // ready to be split into comparators. let rangeList = range .split(' ') .map(comp => parseComparator(comp, this.options)) .join(' ') .split(/\s+/) // >=0.0.0 is equivalent to * .map(comp => replaceGTE0(comp, this.options)) if (loose) { // in loose mode, throw out any that are not valid comparators rangeList = rangeList.filter(comp => { debug('loose invalid filter', comp, this.options) return !!comp.match(re[t.COMPARATORLOOSE]) }) } debug('range list', rangeList) // if any comparators are the null set, then replace with JUST null set // if more than one comparator, remove any * comparators // also, don't include the same comparator more than once const rangeMap = new Map() const comparators = rangeList.map(comp => new Comparator(comp, this.options)) for (const comp of comparators) { if (isNullSet(comp)) { return [comp] } rangeMap.set(comp.value, comp) } if (rangeMap.size > 1 && rangeMap.has('')) { rangeMap.delete('') } const result = [...rangeMap.values()] cache.set(memoKey, result) return result } intersects (range, options) { if (!(range instanceof Range)) { throw new TypeError('a Range is required') } return this.set.some((thisComparators) => { return ( isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => { return ( isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { return rangeComparators.every((rangeComparator) => { return thisComparator.intersects(rangeComparator, options) }) }) ) }) ) }) } // if ANY of the sets match ALL of its comparators, then pass test (version) { if (!version) { return false } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } for (let i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true } } return false } } module.exports = Range const LRU = __webpack_require__(5146) const cache = new LRU({ max: 1000 }) const parseOptions = __webpack_require__(6318) const Comparator = __webpack_require__(43663) const debug = __webpack_require__(31819) const SemVer = __webpack_require__(46629) const { safeRe: re, t, comparatorTrimReplace, tildeTrimReplace, caretTrimReplace, } = __webpack_require__(73726) const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __webpack_require__(90216) const isNullSet = c => c.value === '<0.0.0-0' const isAny = c => c.value === '' // take a set of comparators and determine whether there // exists a version which can satisfy it const isSatisfiable = (comparators, options) => { let result = true const remainingComparators = comparators.slice() let testComparator = remainingComparators.pop() while (result && remainingComparators.length) { result = remainingComparators.every((otherComparator) => { return testComparator.intersects(otherComparator, options) }) testComparator = remainingComparators.pop() } return result } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. const parseComparator = (comp, options) => { debug('comp', comp, options) comp = replaceCarets(comp, options) debug('caret', comp) comp = replaceTildes(comp, options) debug('tildes', comp) comp = replaceXRanges(comp, options) debug('xrange', comp) comp = replaceStars(comp, options) debug('stars', comp) return comp } const isX = id => !id || id.toLowerCase() === 'x' || id === '*' // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 // ~0.0.1 --> >=0.0.1 <0.1.0-0 const replaceTildes = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceTilde(c, options)) .join(' ') } const replaceTilde = (comp, options) => { const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] return comp.replace(r, (_, M, m, p, pr) => { debug('tilde', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0 <${+M + 1}.0.0-0` } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0-0 ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` } else if (pr) { debug('replaceTilde pr', pr) ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } else { // ~1.2.3 == >=1.2.3 <1.3.0-0 ret = `>=${M}.${m}.${p } <${M}.${+m + 1}.0-0` } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 // ^1.2.3 --> >=1.2.3 <2.0.0-0 // ^1.2.0 --> >=1.2.0 <2.0.0-0 // ^0.0.1 --> >=0.0.1 <0.0.2-0 // ^0.1.0 --> >=0.1.0 <0.2.0-0 const replaceCarets = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceCaret(c, options)) .join(' ') } const replaceCaret = (comp, options) => { debug('caret', comp, options) const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] const z = options.includePrerelease ? '-0' : '' return comp.replace(r, (_, M, m, p, pr) => { debug('caret', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` } else if (isX(p)) { if (M === '0') { ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` } else { ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p}-${pr } <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p}-${pr } <${+M + 1}.0.0-0` } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p }${z} <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p }${z} <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p } <${+M + 1}.0.0-0` } } debug('caret return', ret) return ret }) } const replaceXRanges = (comp, options) => { debug('replaceXRanges', comp, options) return comp .split(/\s+/) .map((c) => replaceXRange(c, options)) .join(' ') } const replaceXRange = (comp, options) => { comp = comp.trim() const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] return comp.replace(r, (ret, gtlt, M, m, p, pr) => { debug('xRange', comp, ret, gtlt, M, m, p, pr) const xM = isX(M) const xm = xM || isX(m) const xp = xm || isX(p) const anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } // if we're including prereleases in the match, then we need // to fix this to -0, the lowest possible prerelease value pr = options.includePrerelease ? '-0' : '' if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0-0' } else { // nothing is forbidden ret = '*' } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0 } p = 0 if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 gtlt = '>=' if (xm) { M = +M + 1 m = 0 p = 0 } else { m = +m + 1 p = 0 } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<' if (xm) { M = +M + 1 } else { m = +m + 1 } } if (gtlt === '<') { pr = '-0' } ret = `${gtlt + M}.${m}.${p}${pr}` } else if (xm) { ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` } else if (xp) { ret = `>=${M}.${m}.0${pr } <${M}.${+m + 1}.0-0` } debug('xRange return', ret) return ret }) } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. const replaceStars = (comp, options) => { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp .trim() .replace(re[t.STAR], '') } const replaceGTE0 = (comp, options) => { debug('replaceGTE0', comp, options) return comp .trim() .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') } // This function is passed to string.replace(re[t.HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 const hyphenReplace = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) => { if (isX(fM)) { from = '' } else if (isX(fm)) { from = `>=${fM}.0.0${incPr ? '-0' : ''}` } else if (isX(fp)) { from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` } else if (fpr) { from = `>=${from}` } else { from = `>=${from}${incPr ? '-0' : ''}` } if (isX(tM)) { to = '' } else if (isX(tm)) { to = `<${+tM + 1}.0.0-0` } else if (isX(tp)) { to = `<${tM}.${+tm + 1}.0-0` } else if (tpr) { to = `<=${tM}.${tm}.${tp}-${tpr}` } else if (incPr) { to = `<${tM}.${tm}.${+tp + 1}-0` } else { to = `<=${to}` } return `${from} ${to}`.trim() } const testSet = (set, version, options) => { for (let i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (let i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === Comparator.ANY) { continue } if (set[i].semver.prerelease.length > 0) { const allowed = set[i].semver if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } /***/ }), /***/ 46629: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const debug = __webpack_require__(31819) const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(90216) const { safeRe: re, t } = __webpack_require__(73726) const parseOptions = __webpack_require__(6318) const { compareIdentifiers } = __webpack_require__(49174) class SemVer { constructor (version, options) { options = parseOptions(options) if (version instanceof SemVer) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) } if (version.length > MAX_LENGTH) { throw new TypeError( `version is longer than ${MAX_LENGTH} characters` ) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose // this isn't actually relevant for versions, but keep it so that we // don't run into trouble passing this.options around. this.includePrerelease = !!options.includePrerelease const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) if (!m) { throw new TypeError(`Invalid Version: ${version}`) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map((id) => { if (/^[0-9]+$/.test(id)) { const num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } format () { this.version = `${this.major}.${this.minor}.${this.patch}` if (this.prerelease.length) { this.version += `-${this.prerelease.join('.')}` } return this.version } toString () { return this.version } compare (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { if (typeof other === 'string' && other === this.version) { return 0 } other = new SemVer(other, this.options) } if (other.version === this.version) { return 0 } return this.compareMain(other) || this.comparePre(other) } compareMain (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return ( compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) ) } comparePre (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } let i = 0 do { const a = this.prerelease[i] const b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } compareBuild (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } let i = 0 do { const a = this.build[i] const b = other.build[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc (release, identifier, identifierBase) { switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier, identifierBase) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier, identifierBase) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier, identifierBase) this.inc('pre', identifier, identifierBase) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier, identifierBase) } this.inc('pre', identifier, identifierBase) break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if ( this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0 ) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. case 'pre': { const base = Number(identifierBase) ? 1 : 0 if (!identifier && identifierBase === false) { throw new Error('invalid increment argument: identifier is empty') } if (this.prerelease.length === 0) { this.prerelease = [base] } else { let i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything if (identifier === this.prerelease.join('.') && identifierBase === false) { throw new Error('invalid increment argument: identifier already exists') } this.prerelease.push(base) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 let prerelease = [identifier, base] if (identifierBase === false) { prerelease = [identifier] } if (compareIdentifiers(this.prerelease[0], identifier) === 0) { if (isNaN(this.prerelease[1])) { this.prerelease = prerelease } } else { this.prerelease = prerelease } } break } default: throw new Error(`invalid increment argument: ${release}`) } this.raw = this.format() if (this.build.length) { this.raw += `+${this.build.join('.')}` } return this } } module.exports = SemVer /***/ }), /***/ 32280: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(13155) const clean = (version, options) => { const s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } module.exports = clean /***/ }), /***/ 98600: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const eq = __webpack_require__(84125) const neq = __webpack_require__(56152) const gt = __webpack_require__(68118) const gte = __webpack_require__(49412) const lt = __webpack_require__(25708) const lte = __webpack_require__(79269) const cmp = (a, op, b, loose) => { switch (op) { case '===': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a === b case '!==': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError(`Invalid operator: ${op}`) } } module.exports = cmp /***/ }), /***/ 61722: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(46629) const parse = __webpack_require__(13155) const { safeRe: re, t } = __webpack_require__(73726) const coerce = (version, options) => { if (version instanceof SemVer) { return version } if (typeof version === 'number') { version = String(version) } if (typeof version !== 'string') { return null } options = options || {} let match = null if (!options.rtl) { match = version.match(re[t.COERCE]) } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' // // Walk through the string checking with a /g regexp // Manually set the index so as to pick up overlapping matches. // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. let next while ((next = re[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next } re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length } // leave it in a clean state re[t.COERCERTL].lastIndex = -1 } if (match === null) { return null } return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) } module.exports = coerce /***/ }), /***/ 58423: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(46629) const compareBuild = (a, b, loose) => { const versionA = new SemVer(a, loose) const versionB = new SemVer(b, loose) return versionA.compare(versionB) || versionA.compareBuild(versionB) } module.exports = compareBuild /***/ }), /***/ 61765: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(70880) const compareLoose = (a, b) => compare(a, b, true) module.exports = compareLoose /***/ }), /***/ 70880: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(46629) const compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)) module.exports = compare /***/ }), /***/ 82632: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(13155) const diff = (version1, version2) => { const v1 = parse(version1, null, true) const v2 = parse(version2, null, true) const comparison = v1.compare(v2) if (comparison === 0) { return null } const v1Higher = comparison > 0 const highVersion = v1Higher ? v1 : v2 const lowVersion = v1Higher ? v2 : v1 const highHasPre = !!highVersion.prerelease.length const lowHasPre = !!lowVersion.prerelease.length if (lowHasPre && !highHasPre) { // Going from prerelease -> no prerelease requires some special casing // If the low version has only a major, then it will always be a major // Some examples: // 1.0.0-1 -> 1.0.0 // 1.0.0-1 -> 1.1.1 // 1.0.0-1 -> 2.0.0 if (!lowVersion.patch && !lowVersion.minor) { return 'major' } // Otherwise it can be determined by checking the high version if (highVersion.patch) { // anything higher than a patch bump would result in the wrong version return 'patch' } if (highVersion.minor) { // anything higher than a minor bump would result in the wrong version return 'minor' } // bumping major/minor/patch all have same result return 'major' } // add the `pre` prefix if we are going to a prerelease version const prefix = highHasPre ? 'pre' : '' if (v1.major !== v2.major) { return prefix + 'major' } if (v1.minor !== v2.minor) { return prefix + 'minor' } if (v1.patch !== v2.patch) { return prefix + 'patch' } // high and low are preleases return 'prerelease' } module.exports = diff /***/ }), /***/ 84125: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(70880) const eq = (a, b, loose) => compare(a, b, loose) === 0 module.exports = eq /***/ }), /***/ 68118: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(70880) const gt = (a, b, loose) => compare(a, b, loose) > 0 module.exports = gt /***/ }), /***/ 49412: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(70880) const gte = (a, b, loose) => compare(a, b, loose) >= 0 module.exports = gte /***/ }), /***/ 69684: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(46629) const inc = (version, release, options, identifier, identifierBase) => { if (typeof (options) === 'string') { identifierBase = identifier identifier = options options = undefined } try { return new SemVer( version instanceof SemVer ? version.version : version, options ).inc(release, identifier, identifierBase).version } catch (er) { return null } } module.exports = inc /***/ }), /***/ 25708: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(70880) const lt = (a, b, loose) => compare(a, b, loose) < 0 module.exports = lt /***/ }), /***/ 79269: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(70880) const lte = (a, b, loose) => compare(a, b, loose) <= 0 module.exports = lte /***/ }), /***/ 82767: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(46629) const major = (a, loose) => new SemVer(a, loose).major module.exports = major /***/ }), /***/ 42404: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(46629) const minor = (a, loose) => new SemVer(a, loose).minor module.exports = minor /***/ }), /***/ 56152: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(70880) const neq = (a, b, loose) => compare(a, b, loose) !== 0 module.exports = neq /***/ }), /***/ 13155: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(46629) const parse = (version, options, throwErrors = false) => { if (version instanceof SemVer) { return version } try { return new SemVer(version, options) } catch (er) { if (!throwErrors) { return null } throw er } } module.exports = parse /***/ }), /***/ 4814: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(46629) const patch = (a, loose) => new SemVer(a, loose).patch module.exports = patch /***/ }), /***/ 7319: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(13155) const prerelease = (version, options) => { const parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } module.exports = prerelease /***/ }), /***/ 33815: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(70880) const rcompare = (a, b, loose) => compare(b, a, loose) module.exports = rcompare /***/ }), /***/ 84063: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(58423) const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) module.exports = rsort /***/ }), /***/ 38859: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(87521) const satisfies = (version, range, options) => { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } module.exports = satisfies /***/ }), /***/ 50083: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(58423) const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) module.exports = sort /***/ }), /***/ 38233: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(13155) const valid = (version, options) => { const v = parse(version, options) return v ? v.version : null } module.exports = valid /***/ }), /***/ 45047: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // just pre-load all the stuff that index.js lazily exports const internalRe = __webpack_require__(73726) const constants = __webpack_require__(90216) const SemVer = __webpack_require__(46629) const identifiers = __webpack_require__(49174) const parse = __webpack_require__(13155) const valid = __webpack_require__(38233) const clean = __webpack_require__(32280) const inc = __webpack_require__(69684) const diff = __webpack_require__(82632) const major = __webpack_require__(82767) const minor = __webpack_require__(42404) const patch = __webpack_require__(4814) const prerelease = __webpack_require__(7319) const compare = __webpack_require__(70880) const rcompare = __webpack_require__(33815) const compareLoose = __webpack_require__(61765) const compareBuild = __webpack_require__(58423) const sort = __webpack_require__(50083) const rsort = __webpack_require__(84063) const gt = __webpack_require__(68118) const lt = __webpack_require__(25708) const eq = __webpack_require__(84125) const neq = __webpack_require__(56152) const gte = __webpack_require__(49412) const lte = __webpack_require__(79269) const cmp = __webpack_require__(98600) const coerce = __webpack_require__(61722) const Comparator = __webpack_require__(43663) const Range = __webpack_require__(87521) const satisfies = __webpack_require__(38859) const toComparators = __webpack_require__(82145) const maxSatisfying = __webpack_require__(27825) const minSatisfying = __webpack_require__(75418) const minVersion = __webpack_require__(68223) const validRange = __webpack_require__(58134) const outside = __webpack_require__(89956) const gtr = __webpack_require__(62750) const ltr = __webpack_require__(2090) const intersects = __webpack_require__(41593) const simplifyRange = __webpack_require__(95842) const subset = __webpack_require__(31595) module.exports = { parse, valid, clean, inc, diff, major, minor, patch, prerelease, compare, rcompare, compareLoose, compareBuild, sort, rsort, gt, lt, eq, neq, gte, lte, cmp, coerce, Comparator, Range, satisfies, toComparators, maxSatisfying, minSatisfying, minVersion, validRange, outside, gtr, ltr, intersects, simplifyRange, subset, SemVer, re: internalRe.re, src: internalRe.src, tokens: internalRe.t, SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, RELEASE_TYPES: constants.RELEASE_TYPES, compareIdentifiers: identifiers.compareIdentifiers, rcompareIdentifiers: identifiers.rcompareIdentifiers, } /***/ }), /***/ 90216: /***/ ((module) => { // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. const SEMVER_SPEC_VERSION = '2.0.0' const MAX_LENGTH = 256 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. const MAX_SAFE_COMPONENT_LENGTH = 16 // Max safe length for a build identifier. The max length minus 6 characters for // the shortest version with a build 0.0.0+BUILD. const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 const RELEASE_TYPES = [ 'major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease', ] module.exports = { MAX_LENGTH, MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_SAFE_INTEGER, RELEASE_TYPES, SEMVER_SPEC_VERSION, FLAG_INCLUDE_PRERELEASE: 0b001, FLAG_LOOSE: 0b010, } /***/ }), /***/ 31819: /***/ ((module) => { const debug = ( typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ) ? (...args) => console.error('SEMVER', ...args) : () => {} module.exports = debug /***/ }), /***/ 49174: /***/ ((module) => { const numeric = /^[0-9]+$/ const compareIdentifiers = (a, b) => { const anum = numeric.test(a) const bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) module.exports = { compareIdentifiers, rcompareIdentifiers, } /***/ }), /***/ 6318: /***/ ((module) => { // parse out just the options we care about const looseOption = Object.freeze({ loose: true }) const emptyOpts = Object.freeze({ }) const parseOptions = options => { if (!options) { return emptyOpts } if (typeof options !== 'object') { return looseOption } return options } module.exports = parseOptions /***/ }), /***/ 73726: /***/ ((module, exports, __webpack_require__) => { const { MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_LENGTH, } = __webpack_require__(90216) const debug = __webpack_require__(31819) exports = module.exports = {} // The actual regexps go on exports.re const re = exports.re = [] const safeRe = exports.safeRe = [] const src = exports.src = [] const t = exports.t = {} let R = 0 const LETTERDASHNUMBER = '[a-zA-Z0-9-]' // Replace some greedy regex tokens to prevent regex dos issues. These regex are // used internally via the safeRe object since all inputs in this library get // normalized first to trim and collapse all extra whitespace. The original // regexes are exported for userland consumption and lower level usage. A // future breaking change could export the safer regex only with a note that // all input should have extra whitespace removed. const safeRegexReplacements = [ ['\\s', 1], ['\\d', MAX_LENGTH], [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], ] const makeSafeRegex = (value) => { for (const [token, max] of safeRegexReplacements) { value = value .split(`${token}*`).join(`${token}{0,${max}}`) .split(`${token}+`).join(`${token}{1,${max}}`) } return value } const createToken = (name, value, isGlobal) => { const safe = makeSafeRegex(value) const index = R++ debug(name, index, value) t[name] = index src[index] = value re[index] = new RegExp(value, isGlobal ? 'g' : undefined) safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) } // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') createToken('NUMERICIDENTIFIERLOOSE', '\\d+') // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) // ## Main Version // Three dot-separated numeric identifiers. createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`) createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] }|${src[t.NONNUMERICIDENTIFIER]})`) createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] }|${src[t.NONNUMERICIDENTIFIER]})`) // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] }(?:\\.${src[t.BUILDIDENTIFIER]})*))`) // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. createToken('FULLPLAIN', `v?${src[t.MAINVERSION] }${src[t.PRERELEASE]}?${ src[t.BUILD]}?`) createToken('FULL', `^${src[t.FULLPLAIN]}$`) // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] }${src[t.PRERELEASELOOSE]}?${ src[t.BUILD]}?`) createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) createToken('GTLT', '((?:<|>)?=?)') // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) // Coercion. // Extract anything that could conceivably be a part of a valid semver createToken('COERCE', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:$|[^\\d])`) createToken('COERCERTL', src[t.COERCE], true) // Tilde ranges. // Meaning is "reasonably at or greater than" createToken('LONETILDE', '(?:~>?)') createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) exports.tildeTrimReplace = '$1~' createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) // Caret ranges. // Meaning is "at least and backwards compatible with" createToken('LONECARET', '(?:\\^)') createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) exports.caretTrimReplace = '$1^' createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) // A simple gt/lt/eq thing, or just "" to indicate "any version" createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) exports.comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`) createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`) // Star ranges basically just allow anything at all. createToken('STAR', '(<|>)?=?\\s*\\*') // >=0.0.0 is like a star createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') /***/ }), /***/ 62750: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Determine if version is greater than all the versions possible in the range. const outside = __webpack_require__(89956) const gtr = (version, range, options) => outside(version, range, '>', options) module.exports = gtr /***/ }), /***/ 41593: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(87521) const intersects = (r1, r2, options) => { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2, options) } module.exports = intersects /***/ }), /***/ 2090: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const outside = __webpack_require__(89956) // Determine if version is less than all the versions possible in the range const ltr = (version, range, options) => outside(version, range, '<', options) module.exports = ltr /***/ }), /***/ 27825: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(46629) const Range = __webpack_require__(87521) const maxSatisfying = (versions, range, options) => { let max = null let maxSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } module.exports = maxSatisfying /***/ }), /***/ 75418: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(46629) const Range = __webpack_require__(87521) const minSatisfying = (versions, range, options) => { let min = null let minSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } module.exports = minSatisfying /***/ }), /***/ 68223: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(46629) const Range = __webpack_require__(87521) const gt = __webpack_require__(68118) const minVersion = (range, loose) => { range = new Range(range, loose) let minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let setMin = null comparators.forEach((comparator) => { // Clone to avoid manipulating the comparator's semver object. const compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!setMin || gt(compver, setMin)) { setMin = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error(`Unexpected operation: ${comparator.operator}`) } }) if (setMin && (!minver || gt(minver, setMin))) { minver = setMin } } if (minver && range.test(minver)) { return minver } return null } module.exports = minVersion /***/ }), /***/ 89956: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(46629) const Comparator = __webpack_require__(43663) const { ANY } = Comparator const Range = __webpack_require__(87521) const satisfies = __webpack_require__(38859) const gt = __webpack_require__(68118) const lt = __webpack_require__(25708) const lte = __webpack_require__(79269) const gte = __webpack_require__(49412) const outside = (version, range, hilo, options) => { version = new SemVer(version, options) range = new Range(range, options) let gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisfies the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let high = null let low = null comparators.forEach((comparator) => { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } module.exports = outside /***/ }), /***/ 95842: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // given a set of versions and a range, create a "simplified" range // that includes the same versions that the original range does // If the original range is shorter than the simplified one, return that. const satisfies = __webpack_require__(38859) const compare = __webpack_require__(70880) module.exports = (versions, range, options) => { const set = [] let first = null let prev = null const v = versions.sort((a, b) => compare(a, b, options)) for (const version of v) { const included = satisfies(version, range, options) if (included) { prev = version if (!first) { first = version } } else { if (prev) { set.push([first, prev]) } prev = null first = null } } if (first) { set.push([first, null]) } const ranges = [] for (const [min, max] of set) { if (min === max) { ranges.push(min) } else if (!max && min === v[0]) { ranges.push('*') } else if (!max) { ranges.push(`>=${min}`) } else if (min === v[0]) { ranges.push(`<=${max}`) } else { ranges.push(`${min} - ${max}`) } } const simplified = ranges.join(' || ') const original = typeof range.raw === 'string' ? range.raw : String(range) return simplified.length < original.length ? simplified : range } /***/ }), /***/ 31595: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(87521) const Comparator = __webpack_require__(43663) const { ANY } = Comparator const satisfies = __webpack_require__(38859) const compare = __webpack_require__(70880) // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: // - Every simple range `r1, r2, ...` is a null set, OR // - Every simple range `r1, r2, ...` which is not a null set is a subset of // some `R1, R2, ...` // // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: // - If c is only the ANY comparator // - If C is only the ANY comparator, return true // - Else if in prerelease mode, return false // - else replace c with `[>=0.0.0]` // - If C is only the ANY comparator // - if in prerelease mode, return true // - else replace C with `[>=0.0.0]` // - Let EQ be the set of = comparators in c // - If EQ is more than one, return true (null set) // - Let GT be the highest > or >= comparator in c // - Let LT be the lowest < or <= comparator in c // - If GT and LT, and GT.semver > LT.semver, return true (null set) // - If any C is a = range, and GT or LT are set, return false // - If EQ // - If GT, and EQ does not satisfy GT, return true (null set) // - If LT, and EQ does not satisfy LT, return true (null set) // - If EQ satisfies every C, return true // - Else return false // - If GT // - If GT.semver is lower than any > or >= comp in C, return false // - If GT is >=, and GT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the GT.semver tuple, return false // - If LT // - If LT.semver is greater than any < or <= comp in C, return false // - If LT is <=, and LT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the LT.semver tuple, return false // - Else return true const subset = (sub, dom, options = {}) => { if (sub === dom) { return true } sub = new Range(sub, options) dom = new Range(dom, options) let sawNonNull = false OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { const isSub = simpleSubset(simpleSub, simpleDom, options) sawNonNull = sawNonNull || isSub !== null if (isSub) { continue OUTER } } // the null set is a subset of everything, but null simple ranges in // a complex range should be ignored. so if we saw a non-null range, // then we know this isn't a subset, but if EVERY simple range was null, // then it is a subset. if (sawNonNull) { return false } } return true } const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] const minimumVersion = [new Comparator('>=0.0.0')] const simpleSubset = (sub, dom, options) => { if (sub === dom) { return true } if (sub.length === 1 && sub[0].semver === ANY) { if (dom.length === 1 && dom[0].semver === ANY) { return true } else if (options.includePrerelease) { sub = minimumVersionWithPreRelease } else { sub = minimumVersion } } if (dom.length === 1 && dom[0].semver === ANY) { if (options.includePrerelease) { return true } else { dom = minimumVersion } } const eqSet = new Set() let gt, lt for (const c of sub) { if (c.operator === '>' || c.operator === '>=') { gt = higherGT(gt, c, options) } else if (c.operator === '<' || c.operator === '<=') { lt = lowerLT(lt, c, options) } else { eqSet.add(c.semver) } } if (eqSet.size > 1) { return null } let gtltComp if (gt && lt) { gtltComp = compare(gt.semver, lt.semver, options) if (gtltComp > 0) { return null } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { return null } } // will iterate one or zero times for (const eq of eqSet) { if (gt && !satisfies(eq, String(gt), options)) { return null } if (lt && !satisfies(eq, String(lt), options)) { return null } for (const c of dom) { if (!satisfies(eq, String(c), options)) { return false } } return true } let higher, lower let hasDomLT, hasDomGT // if the subset has a prerelease, we need a comparator in the superset // with the same tuple and a prerelease, or it's not a subset let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false // exception: <1.2.3-0 is the same as <1.2.3 if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { needDomLTPre = false } for (const c of dom) { hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' if (gt) { if (needDomGTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { needDomGTPre = false } } if (c.operator === '>' || c.operator === '>=') { higher = higherGT(gt, c, options) if (higher === c && higher !== gt) { return false } } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { return false } } if (lt) { if (needDomLTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { needDomLTPre = false } } if (c.operator === '<' || c.operator === '<=') { lower = lowerLT(lt, c, options) if (lower === c && lower !== lt) { return false } } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { return false } } if (!c.operator && (lt || gt) && gtltComp !== 0) { return false } } // if there was a < or >, and nothing in the dom, then must be false // UNLESS it was limited by another range in the other direction. // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 if (gt && hasDomLT && !lt && gtltComp !== 0) { return false } if (lt && hasDomGT && !gt && gtltComp !== 0) { return false } // we needed a prerelease range in a specific tuple, but didn't get one // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, // because it includes prereleases in the 1.2.3 tuple if (needDomGTPre || needDomLTPre) { return false } return true } // >=1.2.3 is lower than >1.2.3 const higherGT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp > 0 ? a : comp < 0 ? b : b.operator === '>' && a.operator === '>=' ? b : a } // <=1.2.3 is higher than <1.2.3 const lowerLT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp < 0 ? a : comp > 0 ? b : b.operator === '<' && a.operator === '<=' ? b : a } module.exports = subset /***/ }), /***/ 82145: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(87521) // Mostly just for testing and legacy API reasons const toComparators = (range, options) => new Range(range, options).set .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) module.exports = toComparators /***/ }), /***/ 58134: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(87521) const validRange = (range, options) => { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } module.exports = validRange /***/ }), /***/ 91406: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /*! * Tmp * * Copyright (c) 2011-2017 KARASZI Istvan * * MIT Licensed */ /* * Module dependencies. */ const fs = __webpack_require__(57147); const os = __webpack_require__(22037); const path = __webpack_require__(71017); const crypto = __webpack_require__(6113); const _c = { fs: fs.constants, os: os.constants }; const rimraf = __webpack_require__(54546); /* * The working inner variables. */ const // the random characters to choose from RANDOM_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', TEMPLATE_PATTERN = /XXXXXX/, DEFAULT_TRIES = 3, CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR), // constants are off on the windows platform and will not match the actual errno codes IS_WIN32 = os.platform() === 'win32', EBADF = _c.EBADF || _c.os.errno.EBADF, ENOENT = _c.ENOENT || _c.os.errno.ENOENT, DIR_MODE = 0o700 /* 448 */, FILE_MODE = 0o600 /* 384 */, EXIT = 'exit', // this will hold the objects need to be removed on exit _removeObjects = [], // API change in fs.rmdirSync leads to error when passing in a second parameter, e.g. the callback FN_RMDIR_SYNC = fs.rmdirSync.bind(fs), FN_RIMRAF_SYNC = rimraf.sync; let _gracefulCleanup = false; /** * Gets a temporary file name. * * @param {(Options|tmpNameCallback)} options options or callback * @param {?tmpNameCallback} callback the callback function */ function tmpName(options, callback) { const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; try { _assertAndSanitizeOptions(opts); } catch (err) { return cb(err); } let tries = opts.tries; (function _getUniqueName() { try { const name = _generateTmpName(opts); // check whether the path exists then retry if needed fs.stat(name, function (err) { /* istanbul ignore else */ if (!err) { /* istanbul ignore else */ if (tries-- > 0) return _getUniqueName(); return cb(new Error('Could not get a unique tmp filename, max tries reached ' + name)); } cb(null, name); }); } catch (err) { cb(err); } }()); } /** * Synchronous version of tmpName. * * @param {Object} options * @returns {string} the generated random name * @throws {Error} if the options are invalid or could not generate a filename */ function tmpNameSync(options) { const args = _parseArguments(options), opts = args[0]; _assertAndSanitizeOptions(opts); let tries = opts.tries; do { const name = _generateTmpName(opts); try { fs.statSync(name); } catch (e) { return name; } } while (tries-- > 0); throw new Error('Could not get a unique tmp filename, max tries reached'); } /** * Creates and opens a temporary file. * * @param {(Options|null|undefined|fileCallback)} options the config options or the callback function or null or undefined * @param {?fileCallback} callback */ function file(options, callback) { const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; // gets a temporary filename tmpName(opts, function _tmpNameCreated(err, name) { /* istanbul ignore else */ if (err) return cb(err); // create and open the file fs.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err, fd) { /* istanbu ignore else */ if (err) return cb(err); if (opts.discardDescriptor) { return fs.close(fd, function _discardCallback(possibleErr) { // the chance of getting an error on close here is rather low and might occur in the most edgiest cases only return cb(possibleErr, name, undefined, _prepareTmpFileRemoveCallback(name, -1, opts, false)); }); } else { // detachDescriptor passes the descriptor whereas discardDescriptor closes it, either way, we no longer care // about the descriptor const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; cb(null, name, fd, _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, false)); } }); }); } /** * Synchronous version of file. * * @param {Options} options * @returns {FileSyncObject} object consists of name, fd and removeCallback * @throws {Error} if cannot create a file */ function fileSync(options) { const args = _parseArguments(options), opts = args[0]; const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; const name = tmpNameSync(opts); var fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); /* istanbul ignore else */ if (opts.discardDescriptor) { fs.closeSync(fd); fd = undefined; } return { name: name, fd: fd, removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, true) }; } /** * Creates a temporary directory. * * @param {(Options|dirCallback)} options the options or the callback function * @param {?dirCallback} callback */ function dir(options, callback) { const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; // gets a temporary filename tmpName(opts, function _tmpNameCreated(err, name) { /* istanbul ignore else */ if (err) return cb(err); // create the directory fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err) { /* istanbul ignore else */ if (err) return cb(err); cb(null, name, _prepareTmpDirRemoveCallback(name, opts, false)); }); }); } /** * Synchronous version of dir. * * @param {Options} options * @returns {DirSyncObject} object consists of name and removeCallback * @throws {Error} if it cannot create a directory */ function dirSync(options) { const args = _parseArguments(options), opts = args[0]; const name = tmpNameSync(opts); fs.mkdirSync(name, opts.mode || DIR_MODE); return { name: name, removeCallback: _prepareTmpDirRemoveCallback(name, opts, true) }; } /** * Removes files asynchronously. * * @param {Object} fdPath * @param {Function} next * @private */ function _removeFileAsync(fdPath, next) { const _handler = function (err) { if (err && !_isENOENT(err)) { // reraise any unanticipated error return next(err); } next(); }; if (0 <= fdPath[0]) fs.close(fdPath[0], function () { fs.unlink(fdPath[1], _handler); }); else fs.unlink(fdPath[1], _handler); } /** * Removes files synchronously. * * @param {Object} fdPath * @private */ function _removeFileSync(fdPath) { let rethrownException = null; try { if (0 <= fdPath[0]) fs.closeSync(fdPath[0]); } catch (e) { // reraise any unanticipated error if (!_isEBADF(e) && !_isENOENT(e)) throw e; } finally { try { fs.unlinkSync(fdPath[1]); } catch (e) { // reraise any unanticipated error if (!_isENOENT(e)) rethrownException = e; } } if (rethrownException !== null) { throw rethrownException; } } /** * Prepares the callback for removal of the temporary file. * * Returns either a sync callback or a async callback depending on whether * fileSync or file was called, which is expressed by the sync parameter. * * @param {string} name the path of the file * @param {number} fd file descriptor * @param {Object} opts * @param {boolean} sync * @returns {fileCallback | fileCallbackSync} * @private */ function _prepareTmpFileRemoveCallback(name, fd, opts, sync) { const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name], sync); const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], sync, removeCallbackSync); if (!opts.keep) _removeObjects.unshift(removeCallbackSync); return sync ? removeCallbackSync : removeCallback; } /** * Prepares the callback for removal of the temporary directory. * * Returns either a sync callback or a async callback depending on whether * tmpFileSync or tmpFile was called, which is expressed by the sync parameter. * * @param {string} name * @param {Object} opts * @param {boolean} sync * @returns {Function} the callback * @private */ function _prepareTmpDirRemoveCallback(name, opts, sync) { const removeFunction = opts.unsafeCleanup ? rimraf : fs.rmdir.bind(fs); const removeFunctionSync = opts.unsafeCleanup ? FN_RIMRAF_SYNC : FN_RMDIR_SYNC; const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name, sync); const removeCallback = _prepareRemoveCallback(removeFunction, name, sync, removeCallbackSync); if (!opts.keep) _removeObjects.unshift(removeCallbackSync); return sync ? removeCallbackSync : removeCallback; } /** * Creates a guarded function wrapping the removeFunction call. * * The cleanup callback is save to be called multiple times. * Subsequent invocations will be ignored. * * @param {Function} removeFunction * @param {string} fileOrDirName * @param {boolean} sync * @param {cleanupCallbackSync?} cleanupCallbackSync * @returns {cleanupCallback | cleanupCallbackSync} * @private */ function _prepareRemoveCallback(removeFunction, fileOrDirName, sync, cleanupCallbackSync) { let called = false; // if sync is true, the next parameter will be ignored return function _cleanupCallback(next) { /* istanbul ignore else */ if (!called) { // remove cleanupCallback from cache const toRemove = cleanupCallbackSync || _cleanupCallback; const index = _removeObjects.indexOf(toRemove); /* istanbul ignore else */ if (index >= 0) _removeObjects.splice(index, 1); called = true; if (sync || removeFunction === FN_RMDIR_SYNC || removeFunction === FN_RIMRAF_SYNC) { return removeFunction(fileOrDirName); } else { return removeFunction(fileOrDirName, next || function() {}); } } }; } /** * The garbage collector. * * @private */ function _garbageCollector() { /* istanbul ignore else */ if (!_gracefulCleanup) return; // the function being called removes itself from _removeObjects, // loop until _removeObjects is empty while (_removeObjects.length) { try { _removeObjects[0](); } catch (e) { // already removed? } } } /** * Random name generator based on crypto. * Adapted from http://blog.tompawlak.org/how-to-generate-random-values-nodejs-javascript * * @param {number} howMany * @returns {string} the generated random name * @private */ function _randomChars(howMany) { let value = [], rnd = null; // make sure that we do not fail because we ran out of entropy try { rnd = crypto.randomBytes(howMany); } catch (e) { rnd = crypto.pseudoRandomBytes(howMany); } for (var i = 0; i < howMany; i++) { value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]); } return value.join(''); } /** * Helper which determines whether a string s is blank, that is undefined, or empty or null. * * @private * @param {string} s * @returns {Boolean} true whether the string s is blank, false otherwise */ function _isBlank(s) { return s === null || _isUndefined(s) || !s.trim(); } /** * Checks whether the `obj` parameter is defined or not. * * @param {Object} obj * @returns {boolean} true if the object is undefined * @private */ function _isUndefined(obj) { return typeof obj === 'undefined'; } /** * Parses the function arguments. * * This function helps to have optional arguments. * * @param {(Options|null|undefined|Function)} options * @param {?Function} callback * @returns {Array} parsed arguments * @private */ function _parseArguments(options, callback) { /* istanbul ignore else */ if (typeof options === 'function') { return [{}, options]; } /* istanbul ignore else */ if (_isUndefined(options)) { return [{}, callback]; } // copy options so we do not leak the changes we make internally const actualOptions = {}; for (const key of Object.getOwnPropertyNames(options)) { actualOptions[key] = options[key]; } return [actualOptions, callback]; } /** * Generates a new temporary name. * * @param {Object} opts * @returns {string} the new random name according to opts * @private */ function _generateTmpName(opts) { const tmpDir = opts.tmpdir; /* istanbul ignore else */ if (!_isUndefined(opts.name)) return path.join(tmpDir, opts.dir, opts.name); /* istanbul ignore else */ if (!_isUndefined(opts.template)) return path.join(tmpDir, opts.dir, opts.template).replace(TEMPLATE_PATTERN, _randomChars(6)); // prefix and postfix const name = [ opts.prefix ? opts.prefix : 'tmp', '-', process.pid, '-', _randomChars(12), opts.postfix ? '-' + opts.postfix : '' ].join(''); return path.join(tmpDir, opts.dir, name); } /** * Asserts whether the specified options are valid, also sanitizes options and provides sane defaults for missing * options. * * @param {Options} options * @private */ function _assertAndSanitizeOptions(options) { options.tmpdir = _getTmpDir(options); const tmpDir = options.tmpdir; /* istanbul ignore else */ if (!_isUndefined(options.name)) _assertIsRelative(options.name, 'name', tmpDir); /* istanbul ignore else */ if (!_isUndefined(options.dir)) _assertIsRelative(options.dir, 'dir', tmpDir); /* istanbul ignore else */ if (!_isUndefined(options.template)) { _assertIsRelative(options.template, 'template', tmpDir); if (!options.template.match(TEMPLATE_PATTERN)) throw new Error(`Invalid template, found "${options.template}".`); } /* istanbul ignore else */ if (!_isUndefined(options.tries) && isNaN(options.tries) || options.tries < 0) throw new Error(`Invalid tries, found "${options.tries}".`); // if a name was specified we will try once options.tries = _isUndefined(options.name) ? options.tries || DEFAULT_TRIES : 1; options.keep = !!options.keep; options.detachDescriptor = !!options.detachDescriptor; options.discardDescriptor = !!options.discardDescriptor; options.unsafeCleanup = !!options.unsafeCleanup; // sanitize dir, also keep (multiple) blanks if the user, purportedly sane, requests us to options.dir = _isUndefined(options.dir) ? '' : path.relative(tmpDir, _resolvePath(options.dir, tmpDir)); options.template = _isUndefined(options.template) ? undefined : path.relative(tmpDir, _resolvePath(options.template, tmpDir)); // sanitize further if template is relative to options.dir options.template = _isBlank(options.template) ? undefined : path.relative(options.dir, options.template); // for completeness' sake only, also keep (multiple) blanks if the user, purportedly sane, requests us to options.name = _isUndefined(options.name) ? undefined : _sanitizeName(options.name); options.prefix = _isUndefined(options.prefix) ? '' : options.prefix; options.postfix = _isUndefined(options.postfix) ? '' : options.postfix; } /** * Resolve the specified path name in respect to tmpDir. * * The specified name might include relative path components, e.g. ../ * so we need to resolve in order to be sure that is is located inside tmpDir * * @param name * @param tmpDir * @returns {string} * @private */ function _resolvePath(name, tmpDir) { const sanitizedName = _sanitizeName(name); if (sanitizedName.startsWith(tmpDir)) { return path.resolve(sanitizedName); } else { return path.resolve(path.join(tmpDir, sanitizedName)); } } /** * Sanitize the specified path name by removing all quote characters. * * @param name * @returns {string} * @private */ function _sanitizeName(name) { if (_isBlank(name)) { return name; } return name.replace(/["']/g, ''); } /** * Asserts whether specified name is relative to the specified tmpDir. * * @param {string} name * @param {string} option * @param {string} tmpDir * @throws {Error} * @private */ function _assertIsRelative(name, option, tmpDir) { if (option === 'name') { // assert that name is not absolute and does not contain a path if (path.isAbsolute(name)) throw new Error(`${option} option must not contain an absolute path, found "${name}".`); // must not fail on valid . or .. or similar such constructs let basename = path.basename(name); if (basename === '..' || basename === '.' || basename !== name) throw new Error(`${option} option must not contain a path, found "${name}".`); } else { // if (option === 'dir' || option === 'template') { // assert that dir or template are relative to tmpDir if (path.isAbsolute(name) && !name.startsWith(tmpDir)) { throw new Error(`${option} option must be relative to "${tmpDir}", found "${name}".`); } let resolvedPath = _resolvePath(name, tmpDir); if (!resolvedPath.startsWith(tmpDir)) throw new Error(`${option} option must be relative to "${tmpDir}", found "${resolvedPath}".`); } } /** * Helper for testing against EBADF to compensate changes made to Node 7.x under Windows. * * @private */ function _isEBADF(error) { return _isExpectedError(error, -EBADF, 'EBADF'); } /** * Helper for testing against ENOENT to compensate changes made to Node 7.x under Windows. * * @private */ function _isENOENT(error) { return _isExpectedError(error, -ENOENT, 'ENOENT'); } /** * Helper to determine whether the expected error code matches the actual code and errno, * which will differ between the supported node versions. * * - Node >= 7.0: * error.code {string} * error.errno {number} any numerical value will be negated * * CAVEAT * * On windows, the errno for EBADF is -4083 but os.constants.errno.EBADF is different and we must assume that ENOENT * is no different here. * * @param {SystemError} error * @param {number} errno * @param {string} code * @private */ function _isExpectedError(error, errno, code) { return IS_WIN32 ? error.code === code : error.code === code && error.errno === errno; } /** * Sets the graceful cleanup. * * If graceful cleanup is set, tmp will remove all controlled temporary objects on process exit, otherwise the * temporary objects will remain in place, waiting to be cleaned up on system restart or otherwise scheduled temporary * object removals. */ function setGracefulCleanup() { _gracefulCleanup = true; } /** * Returns the currently configured tmp dir from os.tmpdir(). * * @private * @param {?Options} options * @returns {string} the currently configured tmp dir */ function _getTmpDir(options) { return path.resolve(_sanitizeName(options && options.tmpdir || os.tmpdir())); } // Install process exit listener process.addListener(EXIT, _garbageCollector); /** * Configuration options. * * @typedef {Object} Options * @property {?boolean} keep the temporary object (file or dir) will not be garbage collected * @property {?number} tries the number of tries before give up the name generation * @property (?int) mode the access mode, defaults are 0o700 for directories and 0o600 for files * @property {?string} template the "mkstemp" like filename template * @property {?string} name fixed name relative to tmpdir or the specified dir option * @property {?string} dir tmp directory relative to the root tmp directory in use * @property {?string} prefix prefix for the generated name * @property {?string} postfix postfix for the generated name * @property {?string} tmpdir the root tmp directory which overrides the os tmpdir * @property {?boolean} unsafeCleanup recursively removes the created temporary directory, even when it's not empty * @property {?boolean} detachDescriptor detaches the file descriptor, caller is responsible for closing the file, tmp will no longer try closing the file during garbage collection * @property {?boolean} discardDescriptor discards the file descriptor (closes file, fd is -1), tmp will no longer try closing the file during garbage collection */ /** * @typedef {Object} FileSyncObject * @property {string} name the name of the file * @property {string} fd the file descriptor or -1 if the fd has been discarded * @property {fileCallback} removeCallback the callback function to remove the file */ /** * @typedef {Object} DirSyncObject * @property {string} name the name of the directory * @property {fileCallback} removeCallback the callback function to remove the directory */ /** * @callback tmpNameCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name */ /** * @callback fileCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {number} fd the file descriptor or -1 if the fd had been discarded * @param {cleanupCallback} fn the cleanup callback function */ /** * @callback fileCallbackSync * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {number} fd the file descriptor or -1 if the fd had been discarded * @param {cleanupCallbackSync} fn the cleanup callback function */ /** * @callback dirCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {cleanupCallback} fn the cleanup callback function */ /** * @callback dirCallbackSync * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {cleanupCallbackSync} fn the cleanup callback function */ /** * Removes the temporary created file or directory. * * @callback cleanupCallback * @param {simpleCallback} [next] function to call whenever the tmp object needs to be removed */ /** * Removes the temporary created file or directory. * * @callback cleanupCallbackSync */ /** * Callback function for function composition. * @see {@link https://github.com/raszi/node-tmp/issues/57|raszi/node-tmp#57} * * @callback simpleCallback */ // exporting all the needed methods // evaluate _getTmpDir() lazily, mainly for simplifying testing but it also will // allow users to reconfigure the temporary directory Object.defineProperty(module.exports, "tmpdir", ({ enumerable: true, configurable: false, get: function () { return _getTmpDir(); } })); module.exports.dir = dir; module.exports.dirSync = dirSync; module.exports.file = file; module.exports.fileSync = fileSync; module.exports.tmpName = tmpName; module.exports.tmpNameSync = tmpNameSync; module.exports.setGracefulCleanup = setGracefulCleanup; /***/ }), /***/ 63688: /***/ ((module) => { "use strict"; module.exports = function (Yallist) { Yallist.prototype[Symbol.iterator] = function* () { for (let walker = this.head; walker; walker = walker.next) { yield walker.value } } } /***/ }), /***/ 52426: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = Yallist Yallist.Node = Node Yallist.create = Yallist function Yallist (list) { var self = this if (!(self instanceof Yallist)) { self = new Yallist() } self.tail = null self.head = null self.length = 0 if (list && typeof list.forEach === 'function') { list.forEach(function (item) { self.push(item) }) } else if (arguments.length > 0) { for (var i = 0, l = arguments.length; i < l; i++) { self.push(arguments[i]) } } return self } Yallist.prototype.removeNode = function (node) { if (node.list !== this) { throw new Error('removing node which does not belong to this list') } var next = node.next var prev = node.prev if (next) { next.prev = prev } if (prev) { prev.next = next } if (node === this.head) { this.head = next } if (node === this.tail) { this.tail = prev } node.list.length-- node.next = null node.prev = null node.list = null return next } Yallist.prototype.unshiftNode = function (node) { if (node === this.head) { return } if (node.list) { node.list.removeNode(node) } var head = this.head node.list = this node.next = head if (head) { head.prev = node } this.head = node if (!this.tail) { this.tail = node } this.length++ } Yallist.prototype.pushNode = function (node) { if (node === this.tail) { return } if (node.list) { node.list.removeNode(node) } var tail = this.tail node.list = this node.prev = tail if (tail) { tail.next = node } this.tail = node if (!this.head) { this.head = node } this.length++ } Yallist.prototype.push = function () { for (var i = 0, l = arguments.length; i < l; i++) { push(this, arguments[i]) } return this.length } Yallist.prototype.unshift = function () { for (var i = 0, l = arguments.length; i < l; i++) { unshift(this, arguments[i]) } return this.length } Yallist.prototype.pop = function () { if (!this.tail) { return undefined } var res = this.tail.value this.tail = this.tail.prev if (this.tail) { this.tail.next = null } else { this.head = null } this.length-- return res } Yallist.prototype.shift = function () { if (!this.head) { return undefined } var res = this.head.value this.head = this.head.next if (this.head) { this.head.prev = null } else { this.tail = null } this.length-- return res } Yallist.prototype.forEach = function (fn, thisp) { thisp = thisp || this for (var walker = this.head, i = 0; walker !== null; i++) { fn.call(thisp, walker.value, i, this) walker = walker.next } } Yallist.prototype.forEachReverse = function (fn, thisp) { thisp = thisp || this for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { fn.call(thisp, walker.value, i, this) walker = walker.prev } } Yallist.prototype.get = function (n) { for (var i = 0, walker = this.head; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.next } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.getReverse = function (n) { for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.prev } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.map = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.head; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.next } return res } Yallist.prototype.mapReverse = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.tail; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.prev } return res } Yallist.prototype.reduce = function (fn, initial) { var acc var walker = this.head if (arguments.length > 1) { acc = initial } else if (this.head) { walker = this.head.next acc = this.head.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = 0; walker !== null; i++) { acc = fn(acc, walker.value, i) walker = walker.next } return acc } Yallist.prototype.reduceReverse = function (fn, initial) { var acc var walker = this.tail if (arguments.length > 1) { acc = initial } else if (this.tail) { walker = this.tail.prev acc = this.tail.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = this.length - 1; walker !== null; i--) { acc = fn(acc, walker.value, i) walker = walker.prev } return acc } Yallist.prototype.toArray = function () { var arr = new Array(this.length) for (var i = 0, walker = this.head; walker !== null; i++) { arr[i] = walker.value walker = walker.next } return arr } Yallist.prototype.toArrayReverse = function () { var arr = new Array(this.length) for (var i = 0, walker = this.tail; walker !== null; i++) { arr[i] = walker.value walker = walker.prev } return arr } Yallist.prototype.slice = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = 0, walker = this.head; walker !== null && i < from; i++) { walker = walker.next } for (; walker !== null && i < to; i++, walker = walker.next) { ret.push(walker.value) } return ret } Yallist.prototype.sliceReverse = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { walker = walker.prev } for (; walker !== null && i > from; i--, walker = walker.prev) { ret.push(walker.value) } return ret } Yallist.prototype.splice = function (start, deleteCount, ...nodes) { if (start > this.length) { start = this.length - 1 } if (start < 0) { start = this.length + start; } for (var i = 0, walker = this.head; walker !== null && i < start; i++) { walker = walker.next } var ret = [] for (var i = 0; walker && i < deleteCount; i++) { ret.push(walker.value) walker = this.removeNode(walker) } if (walker === null) { walker = this.tail } if (walker !== this.head && walker !== this.tail) { walker = walker.prev } for (var i = 0; i < nodes.length; i++) { walker = insert(this, walker, nodes[i]) } return ret; } Yallist.prototype.reverse = function () { var head = this.head var tail = this.tail for (var walker = head; walker !== null; walker = walker.prev) { var p = walker.prev walker.prev = walker.next walker.next = p } this.head = tail this.tail = head return this } function insert (self, node, value) { var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self) if (inserted.next === null) { self.tail = inserted } if (inserted.prev === null) { self.head = inserted } self.length++ return inserted } function push (self, item) { self.tail = new Node(item, self.tail, null, self) if (!self.head) { self.head = self.tail } self.length++ } function unshift (self, item) { self.head = new Node(item, null, self.head, self) if (!self.tail) { self.tail = self.head } self.length++ } function Node (value, prev, next, list) { if (!(this instanceof Node)) { return new Node(value, prev, next, list) } this.list = list this.value = value if (prev) { prev.next = this this.prev = prev } else { this.prev = null } if (next) { next.prev = this this.next = next } else { this.next = null } } try { // add if support for Symbol.iterator is present __webpack_require__(63688)(Yallist) } catch (er) {} /***/ }), /***/ 45339: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MissingSubProjectError = void 0; var missing_sub_project_error_1 = __webpack_require__(43749); Object.defineProperty(exports, "MissingSubProjectError", ({ enumerable: true, get: function () { return missing_sub_project_error_1.MissingSubProjectError; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 43749: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MissingSubProjectError = void 0; class MissingSubProjectError extends Error { constructor(subProject, allSubProjectNames) { const msg = !allSubProjectNames.length ? 'No projects found.' : `Found these projects: ${allSubProjectNames}`; super(`Specified sub-project not found: "${subProject}". ` + msg); this.name = 'MissingSubProjectError'; this.subProject = subProject; this.allProjects = allSubProjectNames; Error.captureStackTrace(this, MissingSubProjectError); } } exports.MissingSubProjectError = MissingSubProjectError; //# sourceMappingURL=missing-sub-project-error.js.map /***/ }), /***/ 89173: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getGradleAttributesPretty = void 0; const chalk = __webpack_require__(35337); function getGradleAttributesPretty(output) { try { const lines = output.split('\n'); if (lines === null) { return undefined; } let jsonLine = null; lines.forEach((l) => { const line = l.trim(); // Extract attribute information via JSONATTRS marker: if (/^JSONATTRS /.test(line)) { if (jsonLine === null) { jsonLine = line.substr(10); } } }); const jsonAttrs = JSON.parse(jsonLine); const attrNameWidth = Math.max(...Object.keys(jsonAttrs).map((name) => name.length)); const jsonAttrsPretty = Object.keys(jsonAttrs) .map((name) => chalk.whiteBright(leftPad(name, attrNameWidth)) + ': ' + chalk.gray(jsonAttrs[name].join(', '))) .join('\n'); return jsonAttrsPretty; } catch (e) { return undefined; } } exports.getGradleAttributesPretty = getGradleAttributesPretty; // function leftPad(s, n) { return ' '.repeat(Math.max(n - s.length, 0)) + s; } //# sourceMappingURL=gradle-attributes-pretty.js.map /***/ }), /***/ 23012: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.findChildren = exports.buildGraph = void 0; const dep_graph_1 = __webpack_require__(23423); async function buildGraph(gradleGraph, rootPkgName, projectVersion, verbose, coordinateMap) { const pkgManager = { name: 'gradle' }; const isEmptyGraph = !gradleGraph || Object.keys(gradleGraph).length === 0; const depGraphBuilder = new dep_graph_1.DepGraphBuilder(pkgManager, { name: rootPkgName, version: projectVersion || '0.0.0', }); if (isEmptyGraph) { return depGraphBuilder.build(); } const visitedMap = {}; const queue = []; queue.push(...findChildren('root-node', [], gradleGraph)); // queue direct dependencies // breadth first search while (queue.length > 0) { const item = queue.shift(); if (!item) continue; let { id, parentId } = item; const { ancestry } = item; // take a copy as id maybe mutated below and we need this id when finding childing in GradleGraph const gradleGraphId = `${id}`; const node = gradleGraph[id]; if (!node) continue; let { name = 'unknown', version = 'unknown' } = node; let pkgIdProvenance = undefined; if (coordinateMap) { if (coordinateMap[id]) { id = coordinateMap[id]; const [newName, newVersion] = id.split('@'); if (name !== newName || version !== newVersion) { pkgIdProvenance = `${name}@${version}`; // record pkg id provenance if re coordinated } name = newName; version = newVersion; } if (coordinateMap[parentId]) { parentId = coordinateMap[parentId]; } } const visited = visitedMap[id]; if (!verbose && visited) { const prunedId = id + ':pruned'; depGraphBuilder.addPkgNode({ name, version }, prunedId, createNodeInfo(pkgIdProvenance, 'true')); depGraphBuilder.connectDep(parentId, prunedId); continue; // don't queue any more children } if (verbose && ancestry.includes(id)) { const prunedId = id + ':pruned'; depGraphBuilder.addPkgNode(visited, prunedId, createNodeInfo(pkgIdProvenance, 'cyclic')); depGraphBuilder.connectDep(parentId, prunedId); continue; // don't queue any more children } if (verbose && visited) { // use visited node when omitted dependencies found (verbose) depGraphBuilder.addPkgNode(visited, id, createNodeInfo(pkgIdProvenance)); depGraphBuilder.connectDep(parentId, id); } else { depGraphBuilder.addPkgNode({ name, version }, id, createNodeInfo(pkgIdProvenance)); depGraphBuilder.connectDep(parentId, id); visitedMap[id] = { name, version }; } // Remember to push updated ancestry here queue.push(...findChildren(gradleGraphId, [...ancestry, id], gradleGraph)); // queue children } return depGraphBuilder.build(); } exports.buildGraph = buildGraph; function createNodeInfo(pkgIdProvenance, pruned) { const labels = {}; if (pruned) labels.pruned = pruned; if (pkgIdProvenance) labels.pkgIdProvenance = pkgIdProvenance; return Object.keys(labels).length ? { labels } : undefined; } function findChildren(parentId, ancestry, gradleGraph) { var _a; const result = []; for (const id of Object.keys(gradleGraph)) { const node = gradleGraph[id]; if ((_a = node === null || node === void 0 ? void 0 : node.parentIds) === null || _a === void 0 ? void 0 : _a.includes(parentId)) { result.push({ id, ancestry, parentId }); } } return result; } exports.findChildren = findChildren; //# sourceMappingURL=graph.js.map /***/ }), /***/ 71673: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.exportsForTests = exports.processProjectsInExtractedJSON = exports.getGradleVersion = exports.inspect = exports.debugLog = void 0; const os = __webpack_require__(22037); const fs = __webpack_require__(57147); const path = __webpack_require__(71017); const subProcess = __webpack_require__(84335); const tmp = __webpack_require__(84688); const pMap = __webpack_require__(86301); const chalk = __webpack_require__(35337); const cli_interface_1 = __webpack_require__(43548); const errors_1 = __webpack_require__(45339); const gradle_attributes_pretty_1 = __webpack_require__(89173); const graph_1 = __webpack_require__(23012); const search_1 = __webpack_require__(45479); const debugModule = __webpack_require__(15158); // To enable debugging output, use `snyk -d` let logger = null; function debugLog(s) { if (logger === null) { // Lazy init: Snyk CLI needs to process the CLI argument "-d" first. // TODO(BST-648): more robust handling of the debug settings if (process.env.DEBUG) { debugModule.enable(process.env.DEBUG); } logger = debugModule('snyk-gradle-plugin'); } logger(s); } exports.debugLog = debugLog; const cannotResolveVariantMarkers = [ 'Cannot choose between the following', 'Could not select value from candidates', 'Unable to find a matching variant of project', ]; // General implementation. The result type depends on the runtime type of `options`. async function inspect(root, targetFile, options, snykHttpClient) { debugLog('Gradle inspect called with: ' + JSON.stringify({ root, targetFile, allSubProjects: options === null || options === void 0 ? void 0 : options.allSubProjects, subProject: options === null || options === void 0 ? void 0 : options.subProject, })); if (!options) { options = { dev: false }; } let subProject = options.subProject; if (subProject) { subProject = subProject.trim(); options.subProject = subProject; } const plugin = { name: 'bundled:gradle', runtime: 'unknown', targetFile: targetFileFilteredForCompatibility(targetFile), meta: {}, }; if (cli_interface_1.legacyPlugin.isMultiSubProject(options)) { if (subProject) { throw new Error('gradle-sub-project flag is incompatible with multiDepRoots'); } const scannedProjects = await getAllDepsAllProjects(root, targetFile, options, snykHttpClient); plugin.meta = plugin.meta || {}; return { plugin, scannedProjects, }; } const depGraphAndDepRootNames = await getAllDepsOneProject(root, targetFile, options, snykHttpClient, subProject); if (depGraphAndDepRootNames.allSubProjectNames) { plugin.meta = plugin.meta || {}; plugin.meta.allSubProjectNames = depGraphAndDepRootNames.allSubProjectNames; } return { plugin, package: null, dependencyGraph: depGraphAndDepRootNames.depGraph, meta: { gradleProjectName: depGraphAndDepRootNames.gradleProjectName, versionBuildInfo: depGraphAndDepRootNames.versionBuildInfo, }, }; } exports.inspect = inspect; // See the comment for DepRoot.targetFile // Note: for Gradle, we are not returning the name unless it's a .kts file. // This is a workaround for a project naming problem happening in Registry // (legacy projects are named without "build.gradle" attached to them). // See ticket BST-529 re permanent solution. function targetFileFilteredForCompatibility(targetFile) { return path.basename(targetFile) === 'build.gradle.kts' ? targetFile : undefined; } function extractJsonFromScriptOutput(stdoutText) { const lines = stdoutText.split('\n'); let jsonLine = null; lines.forEach((l) => { if (/^JSONDEPS /.test(l)) { if (jsonLine !== null) { debugLog('More than one line with "JSONDEPS " prefix was returned;'); debugLog('First line: ' + jsonLine); debugLog('Current line:' + l.substr(9)); // TODO (@tardis): the init.gradle should protect against this using 'snykDepsConfExecuted' flag // the longer term fix here is to make multiple snyk graph outputs impossible by interacting with // Gradle API in a more consistent way. // For now, assume the first JSONDEPS found was correct return; } jsonLine = l.substr(9); } }); if (jsonLine === null) { throw new Error('No line prefixed with "JSONDEPS " was returned; full output:\n' + stdoutText); } debugLog('The command produced JSONDEPS output of ' + jsonLine.length + ' characters'); return JSON.parse(jsonLine); } async function getAllDepsOneProject(root, targetFile, options, snykHttpClient, subProject) { const allProjectDeps = await getAllDeps(root, targetFile, options, snykHttpClient); const allSubProjectNames = allProjectDeps.allSubProjectNames; return getTargetProject(subProject, allProjectDeps, allSubProjectNames); } function getTargetProject(subProject, allProjectDeps, allSubProjectNames) { const { projects, defaultProject, defaultProjectKey, versionBuildInfo } = allProjectDeps; let gradleProjectName = defaultProject; if (subProject) { // TODO: we don't want to break the existing implementation of --sub-project using name // we would like a relative path instead to have a unique identifier if (subProject != '.') { subProject = allSubProjectNames.find((it) => it === subProject) || allSubProjectNames.find((it) => it.match(`/${subProject}`)) || subProject; } if (!allProjectDeps.projects || !allProjectDeps.projects[subProject]) { throw new errors_1.MissingSubProjectError(subProject, allSubProjectNames); } gradleProjectName = `${allProjectDeps.defaultProject}/${subProject}`; } const targetProject = subProject || defaultProjectKey; const { depGraph } = projects[targetProject]; return { depGraph, allSubProjectNames, gradleProjectName, versionBuildInfo, }; } async function getAllDepsAllProjects(root, targetFile, options, snykHttpClient) { const allProjectDeps = await getAllDeps(root, targetFile, options, snykHttpClient); return Object.keys(allProjectDeps.projects).map((projectId) => { const { defaultProject } = allProjectDeps; const gradleProjectName = projectId === defaultProject ? defaultProject : `${defaultProject}/${projectId}`; return { targetFile: targetFileFilteredForCompatibility(allProjectDeps.projects[projectId].targetFile), meta: { gradleProjectName, projectName: gradleProjectName, versionBuildInfo: allProjectDeps.versionBuildInfo, targetFile: allProjectDeps.projects[projectId].targetFile, }, depGraph: allProjectDeps.projects[projectId].depGraph, }; }); } const reEcho = /^SNYKECHO (.*)$/; async function printIfEcho(line) { const maybeMatch = reEcho.exec(line); if (maybeMatch) { debugLog(maybeMatch[1]); } } async function injectedPlugin(scriptName) { let initGradleAsset = null; if (/index.js$/.test(__filename)) { // running from ./dist // path.join call has to be exactly in this format, needed by "pkg" to build a standalone Snyk CLI binary: // https://www.npmjs.com/package/pkg#detecting-assets-in-source-code initGradleAsset = path.join(__dirname, '../lib', scriptName); } else if (/index.ts$/.test(__filename)) { // running from ./lib initGradleAsset = path.join(__dirname, scriptName); } else { throw new Error(`Cannot locate Snyk ${scriptName} script`); } // We could be running from a bundled CLI generated by `pkg`. // The Node filesystem in that case is not real: https://github.com/zeit/pkg#snapshot-filesystem // Copying the injectable script into a temp file. try { const tmpInitGradle = tmp.fileSync({ postfix: `-${scriptName}` }); fs.writeSync(tmpInitGradle.fd, fs.readFileSync(initGradleAsset)); return { injectedPluginFilePath: tmpInitGradle.name, cleanupCallback: tmpInitGradle.removeCallback, }; } catch (error) { error.message = error.message + '\n\n' + 'Failed to create a temporary file to host Snyk init script for Gradle build analysis.'; throw error; } } // when running a project is making use of gradle wrapper, the first time we run `gradlew -v`, the download // process happens, cluttering the parsing of the gradle output. // will extract the needed data using a regex function cleanupVersionOutput(gradleVersionOutput) { // Everything since the first "------" line. // [\s\S] used instead of . as it's the easiest way to match \n too const matchedData = gradleVersionOutput.match(/(-{60}[\s\S]+$)/g); if (matchedData) { return matchedData[0]; } debugLog('cannot parse gradle version output:' + gradleVersionOutput); return ''; } function getVersionBuildInfo(gradleVersionOutput) { try { const cleanedVersionOutput = cleanupVersionOutput(gradleVersionOutput); if (cleanedVersionOutput !== '') { const gradleOutputArray = cleanedVersionOutput.split(/\r\n|\r|\n/); // from first 3 new lines, we get the gradle version const gradleVersion = gradleOutputArray[1].split(' ')[1].trim(); const versionMetaInformation = gradleOutputArray.slice(4); // from line 4 until the end we get multiple meta information such as Java, Groovy, Kotlin, etc. const metaBuildVersion = {}; // Select the lines in "Attribute: value format" versionMetaInformation .filter((value) => value && value.length > 0 && value.includes(': ')) .map((value) => value.split(/(.*): (.*)/)) .forEach((splitValue) => (metaBuildVersion[toCamelCase(splitValue[1].trim())] = splitValue[2].trim())); return { gradleVersion, metaBuildVersion, }; } } catch (error) { debugLog('version build info not present, skipping ahead: ' + error); } } async function getGradleVersion(root, command, args) { debugLog('`gradle -v` command run: ' + command); let gradleVersionOutput = '[COULD NOT RUN gradle -v]'; const completeArgs = args ? args.concat(['-v']) : ['-v']; try { gradleVersionOutput = await subProcess.execute(command, completeArgs, { cwd: root, }); } catch (_) { // intentionally empty } return gradleVersionOutput; } exports.getGradleVersion = getGradleVersion; async function getAllDepsWithPlugin(root, targetFile, options, gradleVersion) { const command = getCommand(root, targetFile); const { injectedPluginFilePath, cleanupCallback } = await injectedPlugin('init.gradle'); const args = buildArgs(root, targetFile, injectedPluginFilePath, options, gradleVersion); const fullCommandText = 'gradle command: ' + command + ' ' + args.join(' '); debugLog('Executing ' + fullCommandText); const stdoutText = await subProcess.execute(command, args, { cwd: root }, printIfEcho); if (cleanupCallback) { cleanupCallback(); } const extractedJSON = extractJsonFromScriptOutput(stdoutText); const jsonAttrsPretty = (0, gradle_attributes_pretty_1.getGradleAttributesPretty)(stdoutText); logger(`The following attributes and their possible values were found in your configurations: ${jsonAttrsPretty}`); return extractedJSON; } function splitCoordinate(coordinate) { const coordTest = /^[\w.-]+:[\w.-]+@[\w.-]+$/.test(coordinate); if (!coordTest) return {}; const [groupId, artifactId, version] = coordinate.split(/:|@/); const pomCoord = {}; pomCoord.artifactId = artifactId; pomCoord.groupId = groupId; pomCoord.version = version; return pomCoord; } async function getAllDeps(root, targetFile, options, snykHttpClient) { const command = getCommand(root, targetFile); const gradleVersion = await getGradleVersion(root, command, []); if (gradleVersion.match(/Gradle 1/)) { throw new Error('Gradle 1.x is not supported'); } try { const extractedJSON = await getAllDepsWithPlugin(root, targetFile, options, gradleVersion); const versionBuildInfo = getVersionBuildInfo(gradleVersion); if (versionBuildInfo) { extractedJSON.versionBuildInfo = versionBuildInfo; } const coordinateMap = {}; if (extractedJSON.sha1Map) { const getCoordinateFromHash = async (hash) => { const originalCoordinate = extractedJSON.sha1Map[hash]; const depCoord = splitCoordinate(originalCoordinate); try { const coordinate = await (0, search_1.getMavenPackageInfo)(hash, depCoord, snykHttpClient); coordinateMap[originalCoordinate] = coordinate; } catch (err) { debugLog(err); } }; await pMap(Object.keys(extractedJSON.sha1Map), getCoordinateFromHash, { concurrency: 100, }); } return await processProjectsInExtractedJSON(extractedJSON, options['print-graph'], coordinateMap); } catch (err) { const error = err; const gradleErrorMarkers = /^\s*>\s.*$/; const gradleErrorEssence = error.message .split('\n') .filter((l) => gradleErrorMarkers.test(l)) .join('\n'); const orange = chalk.rgb(255, 128, 0); const blackOnYellow = chalk.bgYellowBright.black; const gradleVersionOutput = orange(gradleVersion); let mainErrorMessage = `Error running Gradle dependency analysis. Please ensure you are calling the \`snyk\` command with correct arguments. If the problem persists, contact support@snyk.io, providing the full error message from above, starting with ===== DEBUG INFORMATION START =====.`; // Special case for Android, where merging the configurations is sometimes // impossible. // There are no automated tests for this yet (setting up Android SDK is quite problematic). // See test/manual/README.md const jsonAttrsPretty = (0, gradle_attributes_pretty_1.getGradleAttributesPretty)(error.message); if (jsonAttrsPretty) { logger(`The following attributes and their possible values were found in your configurations: ${jsonAttrsPretty}`); } if (cannotResolveVariantMarkers.find((m) => error.message.includes(m))) { mainErrorMessage = `Error running Gradle dependency analysis. It seems like you are scanning an Android build with ambiguous dependency variants. We cannot automatically resolve dependencies for such builds. You have several options to make dependency resolution rules more specific: 1. Run Snyk CLI tool with an attribute filter, e.g.: ${chalk.whiteBright('snyk test --all-sub-projects --configuration-attributes=buildtype:release,usage:java-runtime')} The filter will select matching attributes from those found in your configurations, use them to select matching configuration(s) to be used to resolve dependencies. Any sub-string of the full attribute name is enough. Select the values for the attributes that would allow to unambiguously select the correct dependency variant. The Gradle error message above should contain information about attributes found in different variants. Suggested attributes: buildtype, usage and your "flavor dimension" for Android builds. The following attributes and their possible values were found in your configurations: ${jsonAttrsPretty} 2. Run Snyk CLI tool for specific configuration(s), e.g.: ${chalk.whiteBright("snyk test --gradle-sub-project=my-app --configuration-matching='^releaseRuntimeClasspath$'")} (note that some configurations won't be present in every your subproject) 3. Converting your subproject dependency specifications from the form of ${chalk.whiteBright("implementation project(':mymodule')")} to ${chalk.whiteBright("implementation project(path: ':mymodule', configuration: 'default')")}`; } error.message = `${chalk.red.bold('Gradle Error (short):\n' + gradleErrorEssence)} ${blackOnYellow('===== DEBUG INFORMATION START =====')} ${orange(gradleVersionOutput)} ${orange(error.message)} ${blackOnYellow('===== DEBUG INFORMATION END =====')} ${chalk.red.bold(mainErrorMessage)}`; throw error; } } async function processProjectsInExtractedJSON(extractedJSON, verbose, coordinateMap) { for (const projectId in extractedJSON.projects) { const { defaultProject, defaultProjectKey } = extractedJSON; const { gradleGraph, projectVersion } = extractedJSON.projects[projectId]; if (!gradleGraph) { continue; } const isSubProject = projectId !== defaultProjectKey; let rootPkgName = defaultProject; if (isSubProject) { rootPkgName = `${defaultProject}/${projectId}`; } extractedJSON.projects[projectId].depGraph = await (0, graph_1.buildGraph)(gradleGraph, rootPkgName, projectVersion, verbose, coordinateMap); // this property usage ends here delete extractedJSON.projects[projectId].gradleGraph; } return extractedJSON; } exports.processProjectsInExtractedJSON = processProjectsInExtractedJSON; function toCamelCase(input) { input = input .toLowerCase() .replace(/(?:(^.)|([-_\s]+.))/g, (match) => { return match.charAt(match.length - 1).toUpperCase(); }); return input.charAt(0).toLowerCase() + input.substring(1); } function getCommand(root, targetFile) { const isWinLocal = /^win/.test(os.platform()); // local check, can be stubbed in tests const wrapperScript = isWinLocal ? 'gradlew.bat' : './gradlew'; // try to find a sibling wrapper script first let pathToWrapper = path.resolve(root, path.dirname(targetFile), wrapperScript); if (fs.existsSync(pathToWrapper)) { return pathToWrapper; } // now try to find a wrapper in the root pathToWrapper = path.resolve(root, wrapperScript); if (fs.existsSync(pathToWrapper)) { return pathToWrapper; } return 'gradle'; } function buildArgs(root, targetFile, initGradlePath, options, gradleVersion) { let args = []; const taskName = options.gradleNormalizeDeps ? 'snykNormalizedResolvedDepsJson' : 'snykResolvedDepsJson'; args.push(taskName, '-q'); if (targetFile) { const resolvedTargetFilePath = path.resolve(root, targetFile); if (!fs.existsSync(resolvedTargetFilePath)) { throw new Error('File not found: "' + resolvedTargetFilePath + '"'); } args.push('--build-file'); args.push(resolvedTargetFilePath); } // Arguments to init script are supplied as properties: https://stackoverflow.com/a/48370451 if (options['configuration-matching']) { args.push(`-Pconfiguration=${options['configuration-matching']}`); } if (options['configuration-attributes']) { args.push(`-PconfAttr=${options['configuration-attributes']}`); } if (options.initScript) { const formattedInitScript = path.resolve(options.initScript); args.push('--init-script', formattedInitScript); } const isWin = /^win/.test(os.platform()); if (isWin && !options.daemon) { args.push('--no-daemon'); } // Parallel builds can cause race conditions and multiple JSONDEPS lines in the output // Gradle 4.3.0+ has `--no-parallel` flag, but we want to support older versions. // Not `=false` to be compatible with 3.5.x: https://github.com/gradle/gradle/issues/1827 args.push('-Dorg.gradle.parallel='); // Since version 4.3.0+ Gradle uses different console output mechanism. Default mode is 'auto', // if Gradle is attached to a terminal. It means build output will use ANSI control characters // to generate the rich output, therefore JSON cannot be parsed. args.push('-Dorg.gradle.console=plain'); if (!cli_interface_1.legacyPlugin.isMultiSubProject(options)) { args.push('-PonlySubProject=' + (options.subProject || '.')); } args.push('-I', initGradlePath); if (options.args) { args.push(...options.args); } // Gradle 7 introduced configuration caching which we don't support yet // If it is enabled in a gradle.properties file, it can be disabled on the command line with --no-configuration-cache if (gradleVersion.match(/Gradle 7/) || gradleVersion.match(/Gradle 8/)) args.push('--no-configuration-cache'); // There might be a legacy --configuration option in 'args'. // It has been superseded by --configuration-matching option for Snyk CLI (see buildArgs), // but we are handling it to support the legacy setups. args.forEach((a, i) => { // Transform --configuration=foo args[i] = a.replace(/^--configuration[= ]([a-zA-Z_]+)/, `-Pconfiguration=^$1$$`); // Transform --configuration foo if (a === '--configuration') { args[i] = `-Pconfiguration=^${args[i + 1]}$`; args[i + 1] = ''; } }); const unsupportedArgs = ['--configuration-cache']; args = args.filter((arg) => { if (unsupportedArgs.includes(arg)) { debugLog(`Argument ${arg} not currently supported by Snyk.`); return false; } else return true; }); return args.filter(Boolean); } exports.exportsForTests = { buildArgs, extractJsonFromScriptOutput, getVersionBuildInfo, toCamelCase, getGradleAttributesPretty: gradle_attributes_pretty_1.getGradleAttributesPretty, splitCoordinate, }; //# sourceMappingURL=index.js.map /***/ }), /***/ 45479: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getMavenPackageInfo = void 0; const packageurl_js_1 = __webpack_require__(38382); const _1 = __webpack_require__(71673); const PACKAGE_SEARCH_TYPE = 'maven'; const PACKAGE_SEARCH_VERSION = '2022-09-21~beta'; async function getMavenPackageInfo(sha1, depCoords, snykHttpClient) { var _a; const { res, body } = await snykHttpClient({ method: 'get', // base URL defaults to SNYK_API_REST_URL="https://api.snyk.io/rest" path: `/packages`, qs: { version: PACKAGE_SEARCH_VERSION, /* eslint-disable @typescript-eslint/camelcase */ package_type: PACKAGE_SEARCH_TYPE, package_sha1: sha1, package_namespace: depCoords.groupId, package_name: depCoords.artifactId, package_version: depCoords.version, /* eslint-enable @typescript-eslint/camelcase */ }, }); if ((res === null || res === void 0 ? void 0 : res.statusCode) >= 400 || !body) { (0, _1.debugLog)(`Failed to resolve ${JSON.stringify(depCoords)} using sha1 '${sha1}.`); } let groupId; let artifactId; let version; try { const purlString = (_a = body === null || body === void 0 ? void 0 : body.data[0]) === null || _a === void 0 ? void 0 : _a.id; const pkg = packageurl_js_1.PackageURL.fromString(purlString); const { namespace, name, version: pkgVersion } = pkg; groupId = namespace; artifactId = name; version = pkgVersion; } catch (_error) { (0, _1.debugLog)(`Failed to parse purl components for ${JSON.stringify(depCoords)} using sha1 '${sha1}.`); } const groupIdString = groupId || 'unknown'; const artifactIdString = artifactId || `${depCoords.artifactId ? `${depCoords.artifactId}-` : ''}${sha1}`; const versionString = version || 'unknown'; return `${groupIdString}:${artifactIdString}@${versionString}`; } exports.getMavenPackageInfo = getMavenPackageInfo; //# sourceMappingURL=search.js.map /***/ }), /***/ 84335: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.execute = void 0; const childProcess = __webpack_require__(32081); const shescape_1 = __webpack_require__(79114); const os = __webpack_require__(22037); const debugModule = __webpack_require__(15158); const debugLogging = debugModule('snyk-gradle-plugin'); // Executes a subprocess. Resolves successfully with stdout contents if the exit code is 0. function execute(command, args, options, perLineCallback) { const spawnOptions = { shell: false, env: { ...process.env }, }; if (options === null || options === void 0 ? void 0 : options.cwd) { spawnOptions.cwd = options.cwd; } if (options === null || options === void 0 ? void 0 : options.env) { spawnOptions.env = { ...process.env, ...options.env }; } args = (0, shescape_1.escapeAll)(args, spawnOptions); if (/^win/.test(os.platform())) { spawnOptions.windowsVerbatimArguments = true; // makes windows process " correctly const updated = updateCommandAndArgsForWindows(command, args); command = updated.command; args = updated.args; } // Before spawning an external process, we look if we need to restore the system proxy configuration, // which overides the cli internal proxy configuration. if (process.env.SNYK_SYSTEM_HTTP_PROXY !== undefined) { spawnOptions.env.HTTP_PROXY = process.env.SNYK_SYSTEM_HTTP_PROXY; } if (process.env.SNYK_SYSTEM_HTTPS_PROXY !== undefined) { spawnOptions.env.HTTPS_PROXY = process.env.SNYK_SYSTEM_HTTPS_PROXY; } if (process.env.SNYK_SYSTEM_NO_PROXY !== undefined) { spawnOptions.env.NO_PROXY = process.env.SNYK_SYSTEM_NO_PROXY; } return new Promise((resolve, reject) => { let stdout = ''; let stderr = ''; const proc = childProcess.spawn(command, args, spawnOptions); proc.stdout.on('data', (data) => { const strData = data.toString(); stdout = stdout + strData; if (perLineCallback) { strData.split('\n').forEach(perLineCallback); } }); proc.stderr.on('data', (data) => { stderr = stderr + data; }); proc.on('error', (error) => { stderr = stderr + error; }); proc.on('close', (code) => { if (code !== 0) { const fullCommand = command + ' ' + args.join(' '); return reject(new Error(` >>> command: ${fullCommand} >>> exit code: ${code} >>> stdout: ${stdout} >>> stderr: ${stderr} `)); } if (stderr) { debugLogging('subprocess exit code = 0, but stderr was not empty: ' + stderr); } resolve(stdout); }); }); } exports.execute = execute; function updateCommandAndArgsForWindows(command, args) { args = (0, shescape_1.quoteAll)(args); // to handle any spaces in args relating to file path if (command !== 'gradle') { // when command is not gradle we need to wrap the command in " // then wrap the combined string of all args to enable windows to interpret the command correctly args = [`"${command}"`, ...args]; args = ['/c', `"${args.join(' ')}"`]; } else { args = ['/c', command, ...args]; } return { command: 'cmd.exe', args }; } //# sourceMappingURL=sub-process.js.map /***/ }), /***/ 43548: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.legacyCommon = exports.legacyMonitor = exports.legacyPlugin = void 0; const legacy_1 = __webpack_require__(37755); Object.defineProperty(exports, "legacyPlugin", ({ enumerable: true, get: function () { return legacy_1.plugin; } })); Object.defineProperty(exports, "legacyMonitor", ({ enumerable: true, get: function () { return legacy_1.monitor; } })); Object.defineProperty(exports, "legacyCommon", ({ enumerable: true, get: function () { return legacy_1.common; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 76841: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); //# sourceMappingURL=common.js.map /***/ }), /***/ 37755: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.common = exports.monitor = exports.plugin = void 0; const plugin = __webpack_require__(80415); exports.plugin = plugin; const monitor = __webpack_require__(44994); exports.monitor = monitor; const common = __webpack_require__(76841); exports.common = common; //# sourceMappingURL=index.js.map /***/ }), /***/ 44994: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); //# sourceMappingURL=monitor.js.map /***/ }), /***/ 80415: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isMultiResult = exports.isMultiSubProject = exports.adaptSingleProjectPlugin = void 0; function adaptSingleProjectPlugin(plugin) { return { inspect: (root, targetFile, options) => { if (options && isMultiSubProject(options)) { const name = plugin.pluginName ? plugin.pluginName() : '[unknown]'; throw new Error(`Plugin ${name} does not support scanning multiple sub-projects`); } else { return plugin.inspect(root, targetFile, options); } } }; } exports.adaptSingleProjectPlugin = adaptSingleProjectPlugin; function isMultiSubProject(options) { return options.allSubProjects; } exports.isMultiSubProject = isMultiSubProject; function isMultiResult(res) { return !!res.scannedProjects; } exports.isMultiResult = isMultiResult; //# sourceMappingURL=plugin.js.map /***/ }), /***/ 44426: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DepGraphBuilder = void 0; const graphlib = __webpack_require__(88256); const dep_graph_1 = __webpack_require__(90848); class DepGraphBuilder { constructor(pkgManager, rootPkg) { this._pkgs = {}; this._pkgNodes = {}; const graph = new graphlib.Graph({ directed: true, multigraph: false, compound: false, }); if (!rootPkg) { rootPkg = { name: '_root', version: '0.0.0', }; } this._rootNodeId = 'root-node'; this._rootPkgId = DepGraphBuilder._getPkgId(rootPkg); this._pkgs[this._rootPkgId] = rootPkg; graph.setNode(this._rootNodeId, { pkgId: this._rootPkgId }); this._pkgNodes[this._rootPkgId] = new Set([this._rootNodeId]); this._graph = graph; this._pkgManager = pkgManager; } get rootNodeId() { return this._rootNodeId; } static _getPkgId(pkg) { return `${pkg.name}@${pkg.version || ''}`; } getPkgs() { return Object.values(this._pkgs); } // TODO: this can create disconnected nodes addPkgNode(pkgInfo, nodeId, nodeInfo) { if (nodeId === this._rootNodeId) { throw new Error('DepGraphBuilder.addPkgNode() cant override root node'); } const pkgId = DepGraphBuilder._getPkgId(pkgInfo); this._pkgs[pkgId] = pkgInfo; this._pkgNodes[pkgId] = this._pkgNodes[pkgId] || new Set(); this._pkgNodes[pkgId].add(nodeId); this._graph.setNode(nodeId, { pkgId, info: nodeInfo }); return this; } // TODO: this can create cycles connectDep(parentNodeId, depNodeId) { if (!this._graph.hasNode(parentNodeId)) { throw new Error('parentNodeId does not exist'); } if (!this._graph.hasNode(depNodeId)) { throw new Error('depNodeId does not exist'); } this._graph.setEdge(parentNodeId, depNodeId); return this; } build() { return new dep_graph_1.DepGraphImpl(this._graph, this._rootNodeId, this._pkgs, this._pkgNodes, this._pkgManager); } } exports.DepGraphBuilder = DepGraphBuilder; //# sourceMappingURL=builder.js.map /***/ }), /***/ 68893: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createFromJSON = exports.SUPPORTED_SCHEMA_RANGE = void 0; const semver = __webpack_require__(18938); const graphlib = __webpack_require__(88256); const errors_1 = __webpack_require__(77965); const validate_graph_1 = __webpack_require__(2548); const dep_graph_1 = __webpack_require__(90848); exports.SUPPORTED_SCHEMA_RANGE = '^1.0.0'; /** * Create a DepGraph instance from a JSON representation of a dep graph. This * is typically used after passing the graph over the wire as `DepGraphData`. */ function createFromJSON(depGraphData) { validateDepGraphData(depGraphData); const graph = new graphlib.Graph({ directed: true, multigraph: false, compound: false, }); const pkgs = {}; const pkgNodes = {}; for (const { id, info } of depGraphData.pkgs) { pkgs[id] = info.version ? info : Object.assign(Object.assign({}, info), { version: undefined }); } for (const node of depGraphData.graph.nodes) { const pkgId = node.pkgId; if (!pkgNodes[pkgId]) { pkgNodes[pkgId] = new Set(); } pkgNodes[pkgId].add(node.nodeId); graph.setNode(node.nodeId, { pkgId, info: node.info }); } for (const node of depGraphData.graph.nodes) { for (const depNodeId of node.deps) { graph.setEdge(node.nodeId, depNodeId.nodeId); } } validate_graph_1.validateGraph(graph, depGraphData.graph.rootNodeId, pkgs, pkgNodes); return new dep_graph_1.DepGraphImpl(graph, depGraphData.graph.rootNodeId, pkgs, pkgNodes, depGraphData.pkgManager); } exports.createFromJSON = createFromJSON; function assert(condition, msg) { if (!condition) { throw new errors_1.ValidationError(msg); } } function validateDepGraphData(depGraphData) { assert(!!semver.valid(depGraphData.schemaVersion) && semver.satisfies(depGraphData.schemaVersion, exports.SUPPORTED_SCHEMA_RANGE), `dep-graph schemaVersion not in "${exports.SUPPORTED_SCHEMA_RANGE}"`); assert(depGraphData.pkgManager && !!depGraphData.pkgManager.name, '.pkgManager.name is missing'); const pkgsMap = depGraphData.pkgs.reduce((acc, cur) => { assert(!(cur.id in acc), 'more than one pkg with same id'); assert(!!cur.info, '.pkgs item missing .info'); acc[cur.id] = cur.info; return acc; }, {}); const nodesMap = depGraphData.graph.nodes.reduce((acc, cur) => { assert(!(cur.nodeId in acc), 'more than on node with same id'); acc[cur.nodeId] = cur; return acc; }, {}); const rootNodeId = depGraphData.graph.rootNodeId; const rootNode = nodesMap[rootNodeId]; assert(rootNodeId in nodesMap, `.${rootNodeId} root graph node is missing`); const rootPkgId = rootNode.pkgId; assert(rootPkgId in pkgsMap, `.${rootPkgId} root pkg missing`); assert(nodesMap[rootNodeId].pkgId === rootPkgId, `the root node .pkgId should be "${rootPkgId}"`); const pkgIds = Object.keys(pkgsMap); // NOTE: this name@version check is very strict, // we can relax it later, it just makes things easier now assert(pkgIds.filter((pkgId) => pkgId !== dep_graph_1.DepGraphImpl.getPkgId(pkgsMap[pkgId])) .length === 0, 'pkgs ids should be name@version'); assert(Object.values(nodesMap).filter((node) => !(node.pkgId in pkgsMap)) .length === 0, 'some instance nodes belong to non-existing pkgIds'); assert(Object.values(pkgsMap).filter((pkg) => !pkg.name) .length === 0, 'some .pkgs elements have no .name field'); } //# sourceMappingURL=create-from-json.js.map /***/ }), /***/ 90848: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DepGraphImpl = void 0; const _isEqual = __webpack_require__(72307); const graphlib = __webpack_require__(88256); const create_from_json_1 = __webpack_require__(68893); class DepGraphImpl { constructor(_graph, _rootNodeId, _pkgs, _pkgNodes, _pkgManager) { this._graph = _graph; this._rootNodeId = _rootNodeId; this._pkgs = _pkgs; this._pkgNodes = _pkgNodes; this._pkgManager = _pkgManager; this._countNodePathsToRootCache = new Map(); this._rootPkgId = _graph.node(_rootNodeId).pkgId; this._pkgList = Object.values(_pkgs); this._depPkgsList = this._pkgList.filter((pkg) => pkg !== this.rootPkg); } static getPkgId(pkg) { return `${pkg.name}@${pkg.version || ''}`; } get pkgManager() { return this._pkgManager; } get rootPkg() { return this._pkgs[this._rootPkgId]; } get rootNodeId() { return this._rootNodeId; } /** * Get all unique packages in the graph (including the root package) */ getPkgs() { return this._pkgList; } /** * Get all unique packages in the graph (excluding the root package) */ getDepPkgs() { return this._depPkgsList; } getPkgNodes(pkg) { const pkgId = DepGraphImpl.getPkgId(pkg); const nodes = []; for (const nodeId of Array.from(this._pkgNodes[pkgId])) { const graphNode = this.getGraphNode(nodeId); nodes.push({ info: graphNode.info || {}, }); } return nodes; } getNode(nodeId) { return this.getGraphNode(nodeId).info || {}; } getNodePkg(nodeId) { return this._pkgs[this.getGraphNode(nodeId).pkgId]; } getPkgNodeIds(pkg) { const pkgId = DepGraphImpl.getPkgId(pkg); if (!this._pkgs[pkgId]) { throw new Error(`no such pkg: ${pkgId}`); } return Array.from(this._pkgNodes[pkgId]); } getNodeDepsNodeIds(nodeId) { const deps = this._graph.successors(nodeId); if (!deps) { throw new Error(`no such node: ${nodeId}`); } return deps; } getNodeParentsNodeIds(nodeId) { const parents = this._graph.predecessors(nodeId); if (!parents) { throw new Error(`no such node: ${nodeId}`); } return parents; } hasCycles() { // `isAcyclic` is expensive, so memoize if (this._hasCycles === undefined) { this._hasCycles = !graphlib.alg.isAcyclic(this._graph); } return this._hasCycles; } pkgPathsToRoot(pkg, opts) { const pathsToRoot = []; const limit = opts === null || opts === void 0 ? void 0 : opts.limit; for (const nodeId of this.getPkgNodeIds(pkg)) { const pathsFromNodeToRoot = this.pathsFromNodeToRoot(nodeId, [], { limit, }); for (const path of pathsFromNodeToRoot) { pathsToRoot.push(path); } if (limit && pathsToRoot.length >= limit) { break; } } // note: sorting to get shorter paths first - // it's nicer - and better resembles older behaviour return pathsToRoot.sort((a, b) => a.length - b.length); } countPathsToRoot(pkg) { let count = 0; for (const nodeId of this.getPkgNodeIds(pkg)) { count += this.countNodePathsToRoot(nodeId); } return count; } equals(other, { compareRoot = true } = {}) { let otherDepGraph; if (other instanceof DepGraphImpl) { otherDepGraph = other; } else { // At runtime theoretically we can have multiple versions of // @snyk/dep-graph. If "other" is not an instance of the same class it is // safer to rebuild it from JSON. otherDepGraph = create_from_json_1.createFromJSON(other.toJSON()); } // In theory, for the graphs created by standard means, `_.isEquals(this._data, otherDepGraph._data)` // should suffice, since node IDs will be generated in a predictable way. // However, there might be different versions of graph and inconsistencies // in the ordering of the arrays, so we perform a deep comparison. return this.nodeEquals(this, this.rootNodeId, otherDepGraph, otherDepGraph.rootNodeId, compareRoot); } directDepsLeadingTo(pkg) { const pkgNodes = this.getPkgNodeIds(pkg); const directDeps = this.getNodeDepsNodeIds(this.rootNodeId); const nodes = directDeps.filter((directDep) => { const reachableNodes = graphlib.alg.postorder(this._graph, [directDep]); return reachableNodes.filter((node) => pkgNodes.includes(node)).length; }); return nodes.map((node) => this.getNodePkg(node)); } /** * Create a JSON representation of a dep graph. This is typically used to * send the dep graph over the wire */ toJSON() { const nodeIds = this._graph.nodes(); const nodes = nodeIds.reduce((acc, nodeId) => { const deps = (this._graph.successors(nodeId) || []).map((depNodeId) => ({ nodeId: depNodeId, })); const node = this._graph.node(nodeId); const elem = { nodeId, pkgId: node.pkgId, deps, }; if (node.info && Object.keys(node.info).length > 0) { elem.info = node.info; } acc.push(elem); return acc; }, []); const pkgs = Object.keys(this._pkgs).map((pkgId) => ({ id: pkgId, info: this._pkgs[pkgId], })); return { schemaVersion: DepGraphImpl.SCHEMA_VERSION, pkgManager: this._pkgManager, pkgs, graph: { rootNodeId: this._rootNodeId, nodes, }, }; } nodeEquals(graphA, nodeIdA, graphB, nodeIdB, compareRoot, traversedPairs = new Set()) { // Skip root nodes comparision if needed. if (compareRoot || (nodeIdA !== graphA.rootNodeId && nodeIdB !== graphB.rootNodeId)) { const pkgA = graphA.getNodePkg(nodeIdA); const pkgB = graphB.getNodePkg(nodeIdB); // Compare PkgInfo (name and version). if (!_isEqual(pkgA, pkgB)) { return false; } const infoA = graphA.getNode(nodeIdA); const infoB = graphB.getNode(nodeIdB); // Compare NodeInfo (VersionProvenance and labels). if (!_isEqual(infoA, infoB)) { return false; } } let depsA = graphA.getNodeDepsNodeIds(nodeIdA); let depsB = graphB.getNodeDepsNodeIds(nodeIdB); // Number of dependencies should be the same. if (depsA.length !== depsB.length) { return false; } // Sort dependencies by name@version string. const sortFn = (graph) => (idA, idB) => { const pkgA = graph.getNodePkg(idA); const pkgB = graph.getNodePkg(idB); return DepGraphImpl.getPkgId(pkgA).localeCompare(DepGraphImpl.getPkgId(pkgB)); }; depsA = depsA.sort(sortFn(graphA)); depsB = depsB.sort(sortFn(graphB)); // Compare Each dependency recursively. for (let i = 0; i < depsA.length; i++) { const pairKey = `${depsA[i]}_${depsB[i]}`; // Prevent cycles. if (traversedPairs.has(pairKey)) { continue; } traversedPairs.add(pairKey); if (!this.nodeEquals(graphA, depsA[i], graphB, depsB[i], compareRoot, traversedPairs)) { return false; } } return true; } getGraphNode(nodeId) { const node = this._graph.node(nodeId); if (!node) { throw new Error(`no such node: ${nodeId}`); } return node; } pathsFromNodeToRoot(nodeId, ancestors = [], opts) { const parentNodesIds = this.getNodeParentsNodeIds(nodeId); const pkgInfo = this.getNodePkg(nodeId); if (parentNodesIds.length === 0) { return [[pkgInfo]]; } const allPaths = []; ancestors = ancestors.concat(nodeId); const limit = opts.limit; for (const id of parentNodesIds) { if (ancestors.includes(id)) continue; const pathsFromNodeToRoot = this.pathsFromNodeToRoot(id, ancestors, opts); pathsFromNodeToRoot.forEach((path) => allPaths.push([pkgInfo].concat(path))); if (limit && allPaths.length >= limit) { break; } } return allPaths; } countNodePathsToRoot(nodeId, ancestors = []) { if (ancestors.includes(nodeId)) { return 0; } if (this._countNodePathsToRootCache.has(nodeId)) { return this._countNodePathsToRootCache.get(nodeId) || 0; } const parentNodesIds = this.getNodeParentsNodeIds(nodeId); if (parentNodesIds.length === 0) { this._countNodePathsToRootCache.set(nodeId, 1); return 1; } ancestors = ancestors.concat(nodeId); const count = parentNodesIds.reduce((acc, parentNodeId) => { return acc + this.countNodePathsToRoot(parentNodeId, ancestors); }, 0); this._countNodePathsToRootCache.set(nodeId, count); return count; } } exports.DepGraphImpl = DepGraphImpl; DepGraphImpl.SCHEMA_VERSION = '1.2.0'; //# sourceMappingURL=dep-graph.js.map /***/ }), /***/ 91634: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CustomError = void 0; class CustomError extends Error { constructor(message) { super(message); Object.setPrototypeOf(this, CustomError.prototype); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; } } exports.CustomError = CustomError; //# sourceMappingURL=custom-error.js.map /***/ }), /***/ 77965: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ValidationError = void 0; const validation_error_1 = __webpack_require__(44205); Object.defineProperty(exports, "ValidationError", ({ enumerable: true, get: function () { return validation_error_1.ValidationError; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 44205: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ValidationError = void 0; const custom_error_1 = __webpack_require__(91634); class ValidationError extends custom_error_1.CustomError { constructor(message) { super(message); Object.setPrototypeOf(this, ValidationError.prototype); } } exports.ValidationError = ValidationError; //# sourceMappingURL=validation-error.js.map /***/ }), /***/ 2548: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.validateGraph = void 0; const graphlib = __webpack_require__(88256); const errors_1 = __webpack_require__(77965); function assert(condition, msg) { if (!condition) { throw new errors_1.ValidationError(msg); } } function validateGraph(graph, rootNodeId, pkgs, pkgNodes) { assert((graph.predecessors(rootNodeId) || []).length === 0, `"${rootNodeId}" is not really the root`); const reachableFromRoot = graphlib.alg.postorder(graph, [rootNodeId]); const nodeIds = graph.nodes(); assert(JSON.stringify(nodeIds.sort()) === JSON.stringify(reachableFromRoot.sort()), 'not all graph nodes are reachable from root'); const pkgIds = Object.keys(pkgs); const pkgsWithoutInstances = pkgIds.filter((pkgId) => !pkgNodes[pkgId] || pkgNodes[pkgId].size === 0); assert(pkgsWithoutInstances.length === 0, 'not all pkgs have instance nodes'); } exports.validateGraph = validateGraph; //# sourceMappingURL=validate-graph.js.map /***/ }), /***/ 61501: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.dfs = void 0; const each = __webpack_require__(43590); /* * A helper that preforms a pre- or post-order traversal on the input graph * and returns the nodes in the order they were visited. If the graph is * undirected then this algorithm will navigate using neighbors. If the graph * is directed then this algorithm will navigate using successors. * * Order must be one of "pre" or "post". */ function dfs(g, vs, order) { if (!Array.isArray(vs)) { vs = [vs]; } const navigation = (g.isDirected() ? g.successors : g.neighbors).bind(g); const acc = []; const visited = {}; each(vs, (v) => { if (!g.hasNode(v)) { throw new Error('Graph does not have node: ' + v); } doDfs(g, v, order === 'post', visited, navigation, acc); }); return acc; } exports.dfs = dfs; function doDfs(g, v, postorder, visited, navigation, acc) { if (!(v in visited)) { visited[v] = true; if (!postorder) { acc.push(v); } each(navigation(v), function (w) { doDfs(g, w, postorder, visited, navigation, acc); }); if (postorder) { acc.push(v); } } } //# sourceMappingURL=dfs.js.map /***/ }), /***/ 126: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isAcyclic = void 0; const topsort_1 = __webpack_require__(11255); function isAcyclic(g) { try { topsort_1.topsort(g); } catch (e) { if (e instanceof topsort_1.CycleException) { return false; } throw e; } return true; } exports.isAcyclic = isAcyclic; //# sourceMappingURL=is-acyclic.js.map /***/ }), /***/ 8547: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.postorder = void 0; const dfs_1 = __webpack_require__(61501); function postorder(g, vs) { return dfs_1.dfs(g, vs, 'post'); } exports.postorder = postorder; //# sourceMappingURL=postorder.js.map /***/ }), /***/ 11255: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CycleException = exports.topsort = void 0; const each = __webpack_require__(43590); const size = __webpack_require__(27946); function topsort(g) { const visited = {}; const stack = {}; const results = []; function visit(node) { if (node in stack) { throw new CycleException(); } if (!(node in visited)) { stack[node] = true; visited[node] = true; each(g.predecessors(node), visit); delete stack[node]; results.push(node); } } each(g.sinks(), visit); if (size(visited) !== g.nodeCount()) { throw new CycleException(); } return results; } exports.topsort = topsort; class CycleException extends Error { } exports.CycleException = CycleException; //# sourceMappingURL=topsort.js.map /***/ }), /***/ 29481: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Graph = void 0; /* eslint-disable prefer-rest-params */ /* eslint-disable @typescript-eslint/no-this-alias */ const constant = __webpack_require__(4254); const each = __webpack_require__(43590); const _filter = __webpack_require__(43590); const isEmpty = __webpack_require__(99245); const isFunction = __webpack_require__(98423); const isUndefined = __webpack_require__(28801); const keys = __webpack_require__(44799); const reduce = __webpack_require__(34766); const union = __webpack_require__(96744); const values = __webpack_require__(17720); const DEFAULT_EDGE_NAME = '\x00'; const GRAPH_NODE = '\x00'; const EDGE_KEY_DELIM = '\x01'; // Implementation notes: // // * Node id query functions should return string ids for the nodes // * Edge id query functions should return an "edgeObj", edge object, that is // composed of enough information to uniquely identify an edge: {v, w, name}. // * Internally we use an "edgeId", a stringified form of the edgeObj, to // reference edges. This is because we need a performant way to look these // edges up and, object properties, which have string keys, are the closest // we're going to get to a performant hashtable in JavaScript. class Graph { constructor(opts) { var _a, _b, _c; /* Number of nodes in the graph. Should only be changed by the implementation. */ this._nodeCount = 0; /* Number of edges in the graph. Should only be changed by the implementation. */ this._edgeCount = 0; this._isDirected = (_a = opts === null || opts === void 0 ? void 0 : opts.directed) !== null && _a !== void 0 ? _a : true; this._isMultigraph = (_b = opts === null || opts === void 0 ? void 0 : opts.multigraph) !== null && _b !== void 0 ? _b : false; this._isCompound = (_c = opts === null || opts === void 0 ? void 0 : opts.compound) !== null && _c !== void 0 ? _c : false; // Label for the graph itself this._label = undefined; // Defaults to be set when creating a new node this._defaultNodeLabelFn = constant(undefined); // Defaults to be set when creating a new edge this._defaultEdgeLabelFn = constant(undefined); // v -> label this._nodes = {}; if (this._isCompound) { // v -> parent this._parent = {}; // v -> children this._children = {}; this._children[GRAPH_NODE] = {}; } // v -> edgeObj this._in = {}; // u -> v -> Number this._preds = {}; // v -> edgeObj this._out = {}; // v -> w -> Number this._sucs = {}; // e -> edgeObj this._edgeObjs = {}; // e -> label this._edgeLabels = {}; } /* === Graph functions ========= */ isDirected() { return this._isDirected; } isMultigraph() { return this._isMultigraph; } isCompound() { return this._isCompound; } setGraph(label) { this._label = label; return this; } graph() { return this._label; } /* === Node functions ========== */ setDefaultNodeLabel(newDefault) { if (!isFunction(newDefault)) { newDefault = constant(newDefault); } this._defaultNodeLabelFn = newDefault; return this; } nodeCount() { return this._nodeCount; } nodes() { return keys(this._nodes); } sources() { const self = this; return _filter(this.nodes(), function (v) { return isEmpty(self._in[v]); }); } sinks() { const self = this; return _filter(this.nodes(), function (v) { return isEmpty(self._out[v]); }); } setNodes(vs, value) { const args = arguments; const self = this; each(vs, function (v) { if (args.length > 1) { self.setNode(v, value); } else { self.setNode(v); } }); return this; } setNode(v, value) { if (v in this._nodes) { if (arguments.length > 1) { this._nodes[v] = value; } return this; } this._nodes[v] = arguments.length > 1 ? value : this._defaultNodeLabelFn(v); if (this._isCompound) { this._parent[v] = GRAPH_NODE; this._children[v] = {}; this._children[GRAPH_NODE][v] = true; } this._in[v] = {}; this._preds[v] = {}; this._out[v] = {}; this._sucs[v] = {}; ++this._nodeCount; return this; } node(v) { return this._nodes[v]; } hasNode(v) { return v in this._nodes; } removeNode(v) { const self = this; if (v in this._nodes) { const removeEdge = function (e) { self.removeEdge(self._edgeObjs[e]); }; delete this._nodes[v]; if (this._isCompound) { this._removeFromParentsChildList(v); delete this._parent[v]; each(this.children(v), function (child) { self.setParent(child); }); delete this._children[v]; } each(keys(this._in[v]), removeEdge); delete this._in[v]; delete this._preds[v]; each(keys(this._out[v]), removeEdge); delete this._out[v]; delete this._sucs[v]; --this._nodeCount; } return this; } setParent(v, parent) { if (!this._isCompound) { throw new Error('Cannot set parent in a non-compound graph'); } if (isUndefined(parent)) { parent = GRAPH_NODE; } else { // Coerce parent to string parent += ''; for (let ancestor = parent; !isUndefined(ancestor); ancestor = this.parent(ancestor)) { if (ancestor === v) { throw new Error('Setting ' + parent + ' as parent of ' + v + ' would create a cycle'); } } this.setNode(parent); } this.setNode(v); this._removeFromParentsChildList(v); this._parent[v] = parent; this._children[parent][v] = true; return this; } _removeFromParentsChildList(v) { delete this._children[this._parent[v]][v]; } parent(v) { if (this._isCompound) { const parent = this._parent[v]; if (parent !== GRAPH_NODE) { return parent; } } } children(v) { if (isUndefined(v)) { v = GRAPH_NODE; } if (this._isCompound) { const children = this._children[v]; if (children) { return keys(children); } } else if (v === GRAPH_NODE) { return this.nodes(); } else if (this.hasNode(v)) { return []; } } predecessors(v) { const predsV = this._preds[v]; if (predsV) { return keys(predsV); } } successors(v) { const sucsV = this._sucs[v]; if (sucsV) { return keys(sucsV); } } neighbors(v) { const preds = this.predecessors(v); if (preds) { return union(preds, this.successors(v)); } } isLeaf(v) { let neighbors; if (this.isDirected()) { neighbors = this.successors(v); } else { neighbors = this.neighbors(v); } return neighbors.length === 0; } filterNodes(filter) { const copy = new Graph({ directed: this._isDirected, multigraph: this._isMultigraph, compound: this._isCompound, }); copy.setGraph(this.graph()); const self = this; each(this._nodes, function (value, v) { if (filter(v)) { copy.setNode(v, value); } }); each(this._edgeObjs, function (e) { if (copy.hasNode(e.v) && copy.hasNode(e.w)) { copy.setEdge(e, self.edge(e)); } }); const parents = {}; function findParent(v) { const parent = self.parent(v); if (parent === undefined || copy.hasNode(parent)) { parents[v] = parent; return parent; } else if (parent in parents) { return parents[parent]; } else { return findParent(parent); } } if (this._isCompound) { each(copy.nodes(), function (v) { copy.setParent(v, findParent(v)); }); } return copy; } /* === Edge functions ========== */ setDefaultEdgeLabel(newDefault) { if (!isFunction(newDefault)) { newDefault = constant(newDefault); } this._defaultEdgeLabelFn = newDefault; return this; } edgeCount() { return this._edgeCount; } edges() { return values(this._edgeObjs); } setPath(vs, value) { const self = this; const args = arguments; reduce(vs, function (v, w) { if (args.length > 1) { self.setEdge(v, w, value); } else { self.setEdge(v, w); } return w; }); return this; } // eslint-disable-next-line @typescript-eslint/no-unused-vars setEdge(...args) { let v, w, name, value; let valueSpecified = false; const arg0 = arguments[0]; if (typeof arg0 === 'object' && arg0 !== null && 'v' in arg0) { v = arg0.v; w = arg0.w; name = arg0.name; if (arguments.length === 2) { value = arguments[1]; valueSpecified = true; } } else { v = arg0; w = arguments[1]; name = arguments[3]; if (arguments.length > 2) { value = arguments[2]; valueSpecified = true; } } v = '' + v; w = '' + w; if (!isUndefined(name)) { name = '' + name; } const e = edgeArgsToId(this._isDirected, v, w, name); if (e in this._edgeLabels) { if (valueSpecified) { this._edgeLabels[e] = value; } return this; } if (!isUndefined(name) && !this._isMultigraph) { throw new Error('Cannot set a named edge when isMultigraph = false'); } // It didn't exist, so we need to create it. // First ensure the nodes exist. this.setNode(v); this.setNode(w); this._edgeLabels[e] = valueSpecified ? value : this._defaultEdgeLabelFn(v, w, name); const edgeObj = edgeArgsToObj(this._isDirected, v, w, name); // Ensure we add undirected edges in a consistent way. v = edgeObj.v; w = edgeObj.w; Object.freeze(edgeObj); this._edgeObjs[e] = edgeObj; incrementOrInitEntry(this._preds[w], v); incrementOrInitEntry(this._sucs[v], w); this._in[w][e] = edgeObj; this._out[v][e] = edgeObj; this._edgeCount++; return this; } edge(v, w, name) { const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); return this._edgeLabels[e]; } hasEdge(v, w, name) { const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); return e in this._edgeLabels; } removeEdge(v, w, name) { const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); const edge = this._edgeObjs[e]; if (edge) { v = edge.v; w = edge.w; delete this._edgeLabels[e]; delete this._edgeObjs[e]; decrementOrRemoveEntry(this._preds[w], v); decrementOrRemoveEntry(this._sucs[v], w); delete this._in[w][e]; delete this._out[v][e]; this._edgeCount--; } return this; } inEdges(v, u) { const inV = this._in[v]; if (inV) { const edges = values(inV); if (!u) { return edges; } return _filter(edges, function (edge) { return edge.v === u; }); } } outEdges(v, w) { const outV = this._out[v]; if (outV) { const edges = values(outV); if (!w) { return edges; } return _filter(edges, function (edge) { return edge.w === w; }); } } nodeEdges(v, w) { const inEdges = this.inEdges(v, w); if (inEdges) { return inEdges.concat(this.outEdges(v, w)); } } } exports.Graph = Graph; function incrementOrInitEntry(map, k) { if (map[k]) { map[k]++; } else { map[k] = 1; } } function decrementOrRemoveEntry(map, k) { if (!--map[k]) { delete map[k]; } } function edgeArgsToId(isDirected, v_, w_, name) { let v = '' + v_; let w = '' + w_; if (!isDirected && v > w) { const tmp = v; v = w; w = tmp; } return (v + EDGE_KEY_DELIM + w + EDGE_KEY_DELIM + (isUndefined(name) ? DEFAULT_EDGE_NAME : name)); } function edgeArgsToObj(isDirected, v_, w_, name) { let v = '' + v_; let w = '' + w_; if (!isDirected && v > w) { const tmp = v; v = w; w = tmp; } const edgeObj = { v: v, w: w }; if (name) { edgeObj.name = name; } return edgeObj; } function edgeObjToId(isDirected, edgeObj) { return edgeArgsToId(isDirected, edgeObj.v, edgeObj.w, edgeObj.name); } //# sourceMappingURL=graph.js.map /***/ }), /***/ 88256: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.alg = exports.Graph = void 0; var graph_1 = __webpack_require__(29481); Object.defineProperty(exports, "Graph", ({ enumerable: true, get: function () { return graph_1.Graph; } })); const is_acyclic_1 = __webpack_require__(126); const postorder_1 = __webpack_require__(8547); exports.alg = { isAcyclic: is_acyclic_1.isAcyclic, postorder: postorder_1.postorder, }; //# sourceMappingURL=index.js.map /***/ }), /***/ 23423: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.legacy = exports.Errors = exports.DepGraphBuilder = exports.createFromJSON = void 0; var create_from_json_1 = __webpack_require__(68893); Object.defineProperty(exports, "createFromJSON", ({ enumerable: true, get: function () { return create_from_json_1.createFromJSON; } })); var builder_1 = __webpack_require__(44426); Object.defineProperty(exports, "DepGraphBuilder", ({ enumerable: true, get: function () { return builder_1.DepGraphBuilder; } })); const Errors = __webpack_require__(77965); exports.Errors = Errors; const legacy = __webpack_require__(9573); exports.legacy = legacy; //# sourceMappingURL=index.js.map /***/ }), /***/ 23844: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.partitionCycles = exports.getCycle = void 0; function getCycle(ancestors, nodeId) { if (!ancestors.includes(nodeId)) { return null; } // first item is where the cycle starts and ends. return ancestors.slice(ancestors.indexOf(nodeId)); } exports.getCycle = getCycle; function partitionCycles(nodeId, allCyclesTheNodeIsPartOf) { const cyclesStartWithThisNode = []; const cyclesWithThisNode = []; for (const cycle of allCyclesTheNodeIsPartOf) { const nodeStartsCycle = cycle[0] === nodeId; if (nodeStartsCycle) { cyclesStartWithThisNode.push(cycle); } else { cyclesWithThisNode.push(cycle); } } return { cyclesStartWithThisNode, cyclesWithThisNode }; } exports.partitionCycles = partitionCycles; //# sourceMappingURL=cycles.js.map /***/ }), /***/ 9573: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.graphToDepTree = exports.depTreeToGraph = void 0; const crypto = __webpack_require__(6113); const event_loop_spinner_1 = __webpack_require__(77158); const builder_1 = __webpack_require__(44426); const objectHash = __webpack_require__(62874); const cycles_1 = __webpack_require__(23844); const memiozation_1 = __webpack_require__(71908); function addLabel(dep, key, value) { if (!dep.labels) { dep.labels = {}; } dep.labels[key] = value; } /** * @deprecated Don't use dep trees as an intermediate step, because they are * large structures, resulting in high memory usage and high CPU costs from * serializing / deserializing. Instead, create a graph directly with * {@link DepGraphBuilder} */ async function depTreeToGraph(depTree, pkgManagerName) { const rootPkg = { name: depTree.name, version: depTree.version || undefined, }; const pkgManagerInfo = { name: pkgManagerName, }; const targetOS = depTree.targetOS; if (targetOS) { pkgManagerInfo.repositories = [ { alias: `${targetOS.name}:${targetOS.version}`, }, ]; } const builder = new builder_1.DepGraphBuilder(pkgManagerInfo, rootPkg); await buildGraph(builder, depTree, depTree.name, true); const depGraph = await builder.build(); return shortenNodeIds(depGraph); } exports.depTreeToGraph = depTreeToGraph; async function buildGraph(builder, depTree, pkgName, isRoot = false, memoizationMap = new Map()) { if (memoizationMap.has(depTree)) { return memoizationMap.get(depTree); } const getNodeId = (name, version, hashId) => `${name}@${version || ''}|${hashId}`; const depNodesIds = []; const hash = crypto.createHash('sha1'); if (depTree.versionProvenance) { hash.update(objectHash(depTree.versionProvenance)); } if (depTree.labels) { hash.update(objectHash(depTree.labels)); } const deps = depTree.dependencies || {}; // filter-out invalid null deps (shouldn't happen - but did...) const depNames = Object.keys(deps).filter((d) => !!deps[d]); for (const depName of depNames.sort()) { const dep = deps[depName]; const subtreeHash = await buildGraph(builder, dep, depName, false, memoizationMap); const depPkg = { name: depName, version: dep.version, }; const depNodeId = getNodeId(depPkg.name, depPkg.version, subtreeHash); depNodesIds.push(depNodeId); const nodeInfo = {}; if (dep.versionProvenance) { nodeInfo.versionProvenance = dep.versionProvenance; } if (dep.labels) { nodeInfo.labels = dep.labels; } builder.addPkgNode(depPkg, depNodeId, nodeInfo); hash.update(depNodeId); } const treeHash = hash.digest('hex'); let pkgNodeId; if (isRoot) { pkgNodeId = builder.rootNodeId; } else { // we don't assume depTree has a .name to support output of `npm list --json` const pkg = { name: pkgName, version: depTree.version, }; pkgNodeId = getNodeId(pkg.name, pkg.version, treeHash); const nodeInfo = {}; if (depTree.versionProvenance) { nodeInfo.versionProvenance = depTree.versionProvenance; } if (depTree.labels) { nodeInfo.labels = depTree.labels; } builder.addPkgNode(pkg, pkgNodeId, nodeInfo); } for (const depNodeId of depNodesIds) { builder.connectDep(pkgNodeId, depNodeId); } if (depNodesIds.length > 0 && event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } memoizationMap.set(depTree, treeHash); return treeHash; } async function shortenNodeIds(depGraph) { const builder = new builder_1.DepGraphBuilder(depGraph.pkgManager, depGraph.rootPkg); const nodesMap = {}; // create nodes with shorter ids for (const pkg of depGraph.getPkgs()) { const nodeIds = depGraph.getPkgNodeIds(pkg); for (let i = 0; i < nodeIds.length; i++) { const nodeId = nodeIds[i]; if (nodeId === depGraph.rootNodeId) { continue; } const nodeInfo = depGraph.getNode(nodeId); let newNodeId; if (nodeIds.length === 1) { newNodeId = `${trimAfterLastSep(nodeId, '|')}`; } else { newNodeId = `${trimAfterLastSep(nodeId, '|')}|${i + 1}`; } nodesMap[nodeId] = newNodeId; builder.addPkgNode(pkg, newNodeId, nodeInfo); } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } // connect nodes for (const pkg of depGraph.getPkgs()) { for (const nodeId of depGraph.getPkgNodeIds(pkg)) { for (const depNodeId of depGraph.getNodeDepsNodeIds(nodeId)) { const parentNode = nodesMap[nodeId] || nodeId; const childNode = nodesMap[depNodeId] || depNodeId; builder.connectDep(parentNode, childNode); } } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } return builder.build(); } /** * @deprecated Don't use dep trees. You should adapt your code to use graphs, * and enhance the dep-graph library if there is missing functionality from * the graph structure */ async function graphToDepTree(depGraphInterface, pkgType, opts = { deduplicateWithinTopLevelDeps: false }) { const depGraph = depGraphInterface; const [depTree] = await buildSubtree(depGraph, depGraph.rootNodeId, opts.deduplicateWithinTopLevelDeps ? null : false); depTree.type = depGraph.pkgManager.name; depTree.packageFormatVersion = constructPackageFormatVersion(pkgType); const targetOS = constructTargetOS(depGraph); if (targetOS) { depTree.targetOS = targetOS; } return depTree; } exports.graphToDepTree = graphToDepTree; function constructPackageFormatVersion(pkgType) { if (pkgType === 'maven') { pkgType = 'mvn'; } return `${pkgType}:0.0.1`; } function constructTargetOS(depGraph) { if (['apk', 'apt', 'deb', 'rpm', 'linux'].indexOf(depGraph.pkgManager.name) === -1) { // .targetOS is undefined unless its a linux pkgManager return; } if (!depGraph.pkgManager.repositories || !depGraph.pkgManager.repositories.length || !depGraph.pkgManager.repositories[0].alias) { throw new Error('Incomplete .pkgManager, could not create .targetOS'); } const [name, version] = depGraph.pkgManager.repositories[0].alias.split(':'); return { name, version }; } async function buildSubtree(depGraph, nodeId, maybeDeduplicationSet = false, // false = disabled; null = not in deduplication scope yet ancestors = [], memoizationMap = new Map()) { if (!maybeDeduplicationSet) { const memoizedDepTree = memiozation_1.getMemoizedDepTree(nodeId, ancestors, memoizationMap); if (memoizedDepTree) { return [memoizedDepTree, undefined]; } } const isRoot = nodeId === depGraph.rootNodeId; const nodePkg = depGraph.getNodePkg(nodeId); const nodeInfo = depGraph.getNode(nodeId); const depTree = {}; depTree.name = nodePkg.name; depTree.version = nodePkg.version; if (nodeInfo.versionProvenance) { depTree.versionProvenance = nodeInfo.versionProvenance; } if (nodeInfo.labels) { depTree.labels = Object.assign({}, nodeInfo.labels); } const depInstanceIds = depGraph.getNodeDepsNodeIds(nodeId); if (!depInstanceIds || depInstanceIds.length === 0) { memoizationMap.set(nodeId, { depTree }); return [depTree, undefined]; } const cycle = cycles_1.getCycle(ancestors, nodeId); if (cycle) { // This node starts a cycle and now it's the second visit. addLabel(depTree, 'pruned', 'cyclic'); return [depTree, [cycle]]; } if (maybeDeduplicationSet) { if (maybeDeduplicationSet.has(nodeId)) { if (depInstanceIds.length > 0) { addLabel(depTree, 'pruned', 'true'); } return [depTree, undefined]; } maybeDeduplicationSet.add(nodeId); } const cycles = []; for (const depInstId of depInstanceIds) { // Deduplication of nodes occurs only within a scope of a top-level dependency. // Therefore, every top-level dep gets an independent set to track duplicates. if (isRoot && maybeDeduplicationSet !== false) { maybeDeduplicationSet = new Set(); } const [subtree, subtreeCycles] = await buildSubtree(depGraph, depInstId, maybeDeduplicationSet, ancestors.concat(nodeId), memoizationMap); if (subtreeCycles) { for (const cycle of subtreeCycles) { cycles.push(cycle); } } if (!subtree) { continue; } if (!depTree.dependencies) { depTree.dependencies = {}; } depTree.dependencies[subtree.name] = subtree; } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } const partitionedCycles = cycles_1.partitionCycles(nodeId, cycles); memiozation_1.memoize(nodeId, memoizationMap, depTree, partitionedCycles); return [depTree, partitionedCycles.cyclesWithThisNode]; } function trimAfterLastSep(str, sep) { return str.slice(0, str.lastIndexOf(sep)); } //# sourceMappingURL=index.js.map /***/ }), /***/ 71908: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getMemoizedDepTree = exports.memoize = void 0; function memoize(nodeId, memoizationMap, depTree, partitionedCycles) { const { cyclesStartWithThisNode, cyclesWithThisNode } = partitionedCycles; if (cyclesStartWithThisNode.length > 0) { const cycleNodeIds = new Set(...cyclesStartWithThisNode); memoizationMap.set(nodeId, { depTree, cycleNodeIds }); } else if (cyclesWithThisNode.length === 0) { memoizationMap.set(nodeId, { depTree }); } // Don't memoize nodes in cycles (cyclesWithThisNode.length > 0) } exports.memoize = memoize; function getMemoizedDepTree(nodeId, ancestors, memoizationMap) { if (!memoizationMap.has(nodeId)) return null; const { depTree, cycleNodeIds } = memoizationMap.get(nodeId); if (!cycleNodeIds) return depTree; const ancestorsArePartOfTheCycle = ancestors.some((nodeId) => cycleNodeIds.has(nodeId)); return ancestorsArePartOfTheCycle ? null : depTree; } exports.getMemoizedDepTree = getMemoizedDepTree; //# sourceMappingURL=memiozation.js.map /***/ }), /***/ 48959: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* module decorator */ module = __webpack_require__.nmd(module); const wrapAnsi16 = (fn, offset) => (...args) => { const code = fn(...args); return `\u001B[${code + offset}m`; }; const wrapAnsi256 = (fn, offset) => (...args) => { const code = fn(...args); return `\u001B[${38 + offset};5;${code}m`; }; const wrapAnsi16m = (fn, offset) => (...args) => { const rgb = fn(...args); return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; }; const ansi2ansi = n => n; const rgb2rgb = (r, g, b) => [r, g, b]; const setLazyProperty = (object, property, get) => { Object.defineProperty(object, property, { get: () => { const value = get(); Object.defineProperty(object, property, { value, enumerable: true, configurable: true }); return value; }, enumerable: true, configurable: true }); }; /** @type {typeof import('color-convert')} */ let colorConvert; const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { if (colorConvert === undefined) { colorConvert = __webpack_require__(20698); } const offset = isBackground ? 10 : 0; const styles = {}; for (const [sourceSpace, suite] of Object.entries(colorConvert)) { const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; if (sourceSpace === targetSpace) { styles[name] = wrap(identity, offset); } else if (typeof suite === 'object') { styles[name] = wrap(suite[targetSpace], offset); } } return styles; }; function assembleStyles() { const codes = new Map(); const styles = { modifier: { reset: [0, 0], // 21 isn't widely supported and 22 does the same thing bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29] }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], // Bright color blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // Bright color bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } }; // Alias bright black as gray (and grey) styles.color.gray = styles.color.blackBright; styles.bgColor.bgGray = styles.bgColor.bgBlackBright; styles.color.grey = styles.color.blackBright; styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; for (const [groupName, group] of Object.entries(styles)) { for (const [styleName, style] of Object.entries(group)) { styles[styleName] = { open: `\u001B[${style[0]}m`, close: `\u001B[${style[1]}m` }; group[styleName] = styles[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles, groupName, { value: group, enumerable: false }); } Object.defineProperty(styles, 'codes', { value: codes, enumerable: false }); styles.color.close = '\u001B[39m'; styles.bgColor.close = '\u001B[49m'; setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); return styles; } // Make the export immutable Object.defineProperty(module, 'exports', { enumerable: true, get: assembleStyles }); /***/ }), /***/ 35337: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const ansiStyles = __webpack_require__(48959); const {stdout: stdoutColor, stderr: stderrColor} = __webpack_require__(32946); const { stringReplaceAll, stringEncaseCRLFWithFirstIndex } = __webpack_require__(93774); // `supportsColor.level` → `ansiStyles.color[name]` mapping const levelMapping = [ 'ansi', 'ansi', 'ansi256', 'ansi16m' ]; const styles = Object.create(null); const applyOptions = (object, options = {}) => { if (options.level > 3 || options.level < 0) { throw new Error('The `level` option should be an integer from 0 to 3'); } // Detect level if not set manually const colorLevel = stdoutColor ? stdoutColor.level : 0; object.level = options.level === undefined ? colorLevel : options.level; }; class ChalkClass { constructor(options) { return chalkFactory(options); } } const chalkFactory = options => { const chalk = {}; applyOptions(chalk, options); chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); Object.setPrototypeOf(chalk, Chalk.prototype); Object.setPrototypeOf(chalk.template, chalk); chalk.template.constructor = () => { throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); }; chalk.template.Instance = ChalkClass; return chalk.template; }; function Chalk(options) { return chalkFactory(options); } for (const [styleName, style] of Object.entries(ansiStyles)) { styles[styleName] = { get() { const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); Object.defineProperty(this, styleName, {value: builder}); return builder; } }; } styles.visible = { get() { const builder = createBuilder(this, this._styler, true); Object.defineProperty(this, 'visible', {value: builder}); return builder; } }; const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; for (const model of usedModels) { styles[model] = { get() { const {level} = this; return function (...arguments_) { const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler); return createBuilder(this, styler, this._isEmpty); }; } }; } for (const model of usedModels) { const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); styles[bgModel] = { get() { const {level} = this; return function (...arguments_) { const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler); return createBuilder(this, styler, this._isEmpty); }; } }; } const proto = Object.defineProperties(() => {}, { ...styles, level: { enumerable: true, get() { return this._generator.level; }, set(level) { this._generator.level = level; } } }); const createStyler = (open, close, parent) => { let openAll; let closeAll; if (parent === undefined) { openAll = open; closeAll = close; } else { openAll = parent.openAll + open; closeAll = close + parent.closeAll; } return { open, close, openAll, closeAll, parent }; }; const createBuilder = (self, _styler, _isEmpty) => { const builder = (...arguments_) => { // Single argument is hot path, implicit coercion is faster than anything // eslint-disable-next-line no-implicit-coercion return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); }; // `__proto__` is used because we must return a function, but there is // no way to create a function with a different prototype builder.__proto__ = proto; // eslint-disable-line no-proto builder._generator = self; builder._styler = _styler; builder._isEmpty = _isEmpty; return builder; }; const applyStyle = (self, string) => { if (self.level <= 0 || !string) { return self._isEmpty ? '' : string; } let styler = self._styler; if (styler === undefined) { return string; } const {openAll, closeAll} = styler; if (string.indexOf('\u001B') !== -1) { while (styler !== undefined) { // Replace any instances already present with a re-opening code // otherwise only the part of the string until said closing code // will be colored, and the rest will simply be 'plain'. string = stringReplaceAll(string, styler.close, styler.open); styler = styler.parent; } } // We can move both next actions out of loop, because remaining actions in loop won't have // any/visible effect on parts we add here. Close the styling before a linebreak and reopen // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 const lfIndex = string.indexOf('\n'); if (lfIndex !== -1) { string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); } return openAll + string + closeAll; }; let template; const chalkTag = (chalk, ...strings) => { const [firstString] = strings; if (!Array.isArray(firstString)) { // If chalk() was called by itself or with a string, // return the string itself as a string. return strings.join(' '); } const arguments_ = strings.slice(1); const parts = [firstString.raw[0]]; for (let i = 1; i < firstString.length; i++) { parts.push( String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), String(firstString.raw[i]) ); } if (template === undefined) { template = __webpack_require__(8210); } return template(chalk, parts.join('')); }; Object.defineProperties(Chalk.prototype, styles); const chalk = Chalk(); // eslint-disable-line new-cap chalk.supportsColor = stdoutColor; chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap chalk.stderr.supportsColor = stderrColor; // For TypeScript chalk.Level = { None: 0, Basic: 1, Ansi256: 2, TrueColor: 3, 0: 'None', 1: 'Basic', 2: 'Ansi256', 3: 'TrueColor' }; module.exports = chalk; /***/ }), /***/ 8210: /***/ ((module) => { "use strict"; const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.)|([^\\])/gi; const ESCAPES = new Map([ ['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007'] ]); function unescape(c) { const u = c[0] === 'u'; const bracket = c[1] === '{'; if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) { return String.fromCharCode(parseInt(c.slice(1), 16)); } if (u && bracket) { return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); } return ESCAPES.get(c) || c; } function parseArguments(name, arguments_) { const results = []; const chunks = arguments_.trim().split(/\s*,\s*/g); let matches; for (const chunk of chunks) { const number = Number(chunk); if (!Number.isNaN(number)) { results.push(number); } else if ((matches = chunk.match(STRING_REGEX))) { results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character)); } else { throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); } } return results; } function parseStyle(style) { STYLE_REGEX.lastIndex = 0; const results = []; let matches; while ((matches = STYLE_REGEX.exec(style)) !== null) { const name = matches[1]; if (matches[2]) { const args = parseArguments(name, matches[2]); results.push([name].concat(args)); } else { results.push([name]); } } return results; } function buildStyle(chalk, styles) { const enabled = {}; for (const layer of styles) { for (const style of layer.styles) { enabled[style[0]] = layer.inverse ? null : style.slice(1); } } let current = chalk; for (const [styleName, styles] of Object.entries(enabled)) { if (!Array.isArray(styles)) { continue; } if (!(styleName in current)) { throw new Error(`Unknown Chalk style: ${styleName}`); } current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; } return current; } module.exports = (chalk, temporary) => { const styles = []; const chunks = []; let chunk = []; // eslint-disable-next-line max-params temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => { if (escapeCharacter) { chunk.push(unescape(escapeCharacter)); } else if (style) { const string = chunk.join(''); chunk = []; chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string)); styles.push({inverse, styles: parseStyle(style)}); } else if (close) { if (styles.length === 0) { throw new Error('Found extraneous } in Chalk template literal'); } chunks.push(buildStyle(chalk, styles)(chunk.join(''))); chunk = []; styles.pop(); } else { chunk.push(character); } }); chunks.push(chunk.join('')); if (styles.length > 0) { const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; throw new Error(errMsg); } return chunks.join(''); }; /***/ }), /***/ 93774: /***/ ((module) => { "use strict"; const stringReplaceAll = (string, substring, replacer) => { let index = string.indexOf(substring); if (index === -1) { return string; } const substringLength = substring.length; let endIndex = 0; let returnValue = ''; do { returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; endIndex = index + substringLength; index = string.indexOf(substring, endIndex); } while (index !== -1); returnValue += string.substr(endIndex); return returnValue; }; const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => { let endIndex = 0; let returnValue = ''; do { const gotCR = string[index - 1] === '\r'; returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; endIndex = index + 1; index = string.indexOf('\n', endIndex); } while (index !== -1); returnValue += string.substr(endIndex); return returnValue; }; module.exports = { stringReplaceAll, stringEncaseCRLFWithFirstIndex }; /***/ }), /***/ 99595: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /* MIT license */ /* eslint-disable no-mixed-operators */ const cssKeywords = __webpack_require__(56662); // NOTE: conversions should only return primitive values (i.e. arrays, or // values that give correct `typeof` results). // do not use box values types (i.e. Number(), String(), etc.) const reverseKeywords = {}; for (const key of Object.keys(cssKeywords)) { reverseKeywords[cssKeywords[key]] = key; } const convert = { rgb: {channels: 3, labels: 'rgb'}, hsl: {channels: 3, labels: 'hsl'}, hsv: {channels: 3, labels: 'hsv'}, hwb: {channels: 3, labels: 'hwb'}, cmyk: {channels: 4, labels: 'cmyk'}, xyz: {channels: 3, labels: 'xyz'}, lab: {channels: 3, labels: 'lab'}, lch: {channels: 3, labels: 'lch'}, hex: {channels: 1, labels: ['hex']}, keyword: {channels: 1, labels: ['keyword']}, ansi16: {channels: 1, labels: ['ansi16']}, ansi256: {channels: 1, labels: ['ansi256']}, hcg: {channels: 3, labels: ['h', 'c', 'g']}, apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, gray: {channels: 1, labels: ['gray']} }; module.exports = convert; // Hide .channels and .labels properties for (const model of Object.keys(convert)) { if (!('channels' in convert[model])) { throw new Error('missing channels property: ' + model); } if (!('labels' in convert[model])) { throw new Error('missing channel labels property: ' + model); } if (convert[model].labels.length !== convert[model].channels) { throw new Error('channel and label counts mismatch: ' + model); } const {channels, labels} = convert[model]; delete convert[model].channels; delete convert[model].labels; Object.defineProperty(convert[model], 'channels', {value: channels}); Object.defineProperty(convert[model], 'labels', {value: labels}); } convert.rgb.hsl = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const min = Math.min(r, g, b); const max = Math.max(r, g, b); const delta = max - min; let h; let s; if (max === min) { h = 0; } else if (r === max) { h = (g - b) / delta; } else if (g === max) { h = 2 + (b - r) / delta; } else if (b === max) { h = 4 + (r - g) / delta; } h = Math.min(h * 60, 360); if (h < 0) { h += 360; } const l = (min + max) / 2; if (max === min) { s = 0; } else if (l <= 0.5) { s = delta / (max + min); } else { s = delta / (2 - max - min); } return [h, s * 100, l * 100]; }; convert.rgb.hsv = function (rgb) { let rdif; let gdif; let bdif; let h; let s; const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const v = Math.max(r, g, b); const diff = v - Math.min(r, g, b); const diffc = function (c) { return (v - c) / 6 / diff + 1 / 2; }; if (diff === 0) { h = 0; s = 0; } else { s = diff / v; rdif = diffc(r); gdif = diffc(g); bdif = diffc(b); if (r === v) { h = bdif - gdif; } else if (g === v) { h = (1 / 3) + rdif - bdif; } else if (b === v) { h = (2 / 3) + gdif - rdif; } if (h < 0) { h += 1; } else if (h > 1) { h -= 1; } } return [ h * 360, s * 100, v * 100 ]; }; convert.rgb.hwb = function (rgb) { const r = rgb[0]; const g = rgb[1]; let b = rgb[2]; const h = convert.rgb.hsl(rgb)[0]; const w = 1 / 255 * Math.min(r, Math.min(g, b)); b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); return [h, w * 100, b * 100]; }; convert.rgb.cmyk = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const k = Math.min(1 - r, 1 - g, 1 - b); const c = (1 - r - k) / (1 - k) || 0; const m = (1 - g - k) / (1 - k) || 0; const y = (1 - b - k) / (1 - k) || 0; return [c * 100, m * 100, y * 100, k * 100]; }; function comparativeDistance(x, y) { /* See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance */ return ( ((x[0] - y[0]) ** 2) + ((x[1] - y[1]) ** 2) + ((x[2] - y[2]) ** 2) ); } convert.rgb.keyword = function (rgb) { const reversed = reverseKeywords[rgb]; if (reversed) { return reversed; } let currentClosestDistance = Infinity; let currentClosestKeyword; for (const keyword of Object.keys(cssKeywords)) { const value = cssKeywords[keyword]; // Compute comparative distance const distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest if (distance < currentClosestDistance) { currentClosestDistance = distance; currentClosestKeyword = keyword; } } return currentClosestKeyword; }; convert.keyword.rgb = function (keyword) { return cssKeywords[keyword]; }; convert.rgb.xyz = function (rgb) { let r = rgb[0] / 255; let g = rgb[1] / 255; let b = rgb[2] / 255; // Assume sRGB r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92); g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92); b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92); const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); return [x * 100, y * 100, z * 100]; }; convert.rgb.lab = function (rgb) { const xyz = convert.rgb.xyz(rgb); let x = xyz[0]; let y = xyz[1]; let z = xyz[2]; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); const l = (116 * y) - 16; const a = 500 * (x - y); const b = 200 * (y - z); return [l, a, b]; }; convert.hsl.rgb = function (hsl) { const h = hsl[0] / 360; const s = hsl[1] / 100; const l = hsl[2] / 100; let t2; let t3; let val; if (s === 0) { val = l * 255; return [val, val, val]; } if (l < 0.5) { t2 = l * (1 + s); } else { t2 = l + s - l * s; } const t1 = 2 * l - t2; const rgb = [0, 0, 0]; for (let i = 0; i < 3; i++) { t3 = h + 1 / 3 * -(i - 1); if (t3 < 0) { t3++; } if (t3 > 1) { t3--; } if (6 * t3 < 1) { val = t1 + (t2 - t1) * 6 * t3; } else if (2 * t3 < 1) { val = t2; } else if (3 * t3 < 2) { val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; } else { val = t1; } rgb[i] = val * 255; } return rgb; }; convert.hsl.hsv = function (hsl) { const h = hsl[0]; let s = hsl[1] / 100; let l = hsl[2] / 100; let smin = s; const lmin = Math.max(l, 0.01); l *= 2; s *= (l <= 1) ? l : 2 - l; smin *= lmin <= 1 ? lmin : 2 - lmin; const v = (l + s) / 2; const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); return [h, sv * 100, v * 100]; }; convert.hsv.rgb = function (hsv) { const h = hsv[0] / 60; const s = hsv[1] / 100; let v = hsv[2] / 100; const hi = Math.floor(h) % 6; const f = h - Math.floor(h); const p = 255 * v * (1 - s); const q = 255 * v * (1 - (s * f)); const t = 255 * v * (1 - (s * (1 - f))); v *= 255; switch (hi) { case 0: return [v, t, p]; case 1: return [q, v, p]; case 2: return [p, v, t]; case 3: return [p, q, v]; case 4: return [t, p, v]; case 5: return [v, p, q]; } }; convert.hsv.hsl = function (hsv) { const h = hsv[0]; const s = hsv[1] / 100; const v = hsv[2] / 100; const vmin = Math.max(v, 0.01); let sl; let l; l = (2 - s) * v; const lmin = (2 - s) * vmin; sl = s * vmin; sl /= (lmin <= 1) ? lmin : 2 - lmin; sl = sl || 0; l /= 2; return [h, sl * 100, l * 100]; }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb convert.hwb.rgb = function (hwb) { const h = hwb[0] / 360; let wh = hwb[1] / 100; let bl = hwb[2] / 100; const ratio = wh + bl; let f; // Wh + bl cant be > 1 if (ratio > 1) { wh /= ratio; bl /= ratio; } const i = Math.floor(6 * h); const v = 1 - bl; f = 6 * h - i; if ((i & 0x01) !== 0) { f = 1 - f; } const n = wh + f * (v - wh); // Linear interpolation let r; let g; let b; /* eslint-disable max-statements-per-line,no-multi-spaces */ switch (i) { default: case 6: case 0: r = v; g = n; b = wh; break; case 1: r = n; g = v; b = wh; break; case 2: r = wh; g = v; b = n; break; case 3: r = wh; g = n; b = v; break; case 4: r = n; g = wh; b = v; break; case 5: r = v; g = wh; b = n; break; } /* eslint-enable max-statements-per-line,no-multi-spaces */ return [r * 255, g * 255, b * 255]; }; convert.cmyk.rgb = function (cmyk) { const c = cmyk[0] / 100; const m = cmyk[1] / 100; const y = cmyk[2] / 100; const k = cmyk[3] / 100; const r = 1 - Math.min(1, c * (1 - k) + k); const g = 1 - Math.min(1, m * (1 - k) + k); const b = 1 - Math.min(1, y * (1 - k) + k); return [r * 255, g * 255, b * 255]; }; convert.xyz.rgb = function (xyz) { const x = xyz[0] / 100; const y = xyz[1] / 100; const z = xyz[2] / 100; let r; let g; let b; r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); // Assume sRGB r = r > 0.0031308 ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) : r * 12.92; g = g > 0.0031308 ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) : g * 12.92; b = b > 0.0031308 ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) : b * 12.92; r = Math.min(Math.max(0, r), 1); g = Math.min(Math.max(0, g), 1); b = Math.min(Math.max(0, b), 1); return [r * 255, g * 255, b * 255]; }; convert.xyz.lab = function (xyz) { let x = xyz[0]; let y = xyz[1]; let z = xyz[2]; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); const l = (116 * y) - 16; const a = 500 * (x - y); const b = 200 * (y - z); return [l, a, b]; }; convert.lab.xyz = function (lab) { const l = lab[0]; const a = lab[1]; const b = lab[2]; let x; let y; let z; y = (l + 16) / 116; x = a / 500 + y; z = y - b / 200; const y2 = y ** 3; const x2 = x ** 3; const z2 = z ** 3; y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; x *= 95.047; y *= 100; z *= 108.883; return [x, y, z]; }; convert.lab.lch = function (lab) { const l = lab[0]; const a = lab[1]; const b = lab[2]; let h; const hr = Math.atan2(b, a); h = hr * 360 / 2 / Math.PI; if (h < 0) { h += 360; } const c = Math.sqrt(a * a + b * b); return [l, c, h]; }; convert.lch.lab = function (lch) { const l = lch[0]; const c = lch[1]; const h = lch[2]; const hr = h / 360 * 2 * Math.PI; const a = c * Math.cos(hr); const b = c * Math.sin(hr); return [l, a, b]; }; convert.rgb.ansi16 = function (args, saturation = null) { const [r, g, b] = args; let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization value = Math.round(value / 50); if (value === 0) { return 30; } let ansi = 30 + ((Math.round(b / 255) << 2) | (Math.round(g / 255) << 1) | Math.round(r / 255)); if (value === 2) { ansi += 60; } return ansi; }; convert.hsv.ansi16 = function (args) { // Optimization here; we already know the value and don't need to get // it converted for us. return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); }; convert.rgb.ansi256 = function (args) { const r = args[0]; const g = args[1]; const b = args[2]; // We use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (r === g && g === b) { if (r < 8) { return 16; } if (r > 248) { return 231; } return Math.round(((r - 8) / 247) * 24) + 232; } const ansi = 16 + (36 * Math.round(r / 255 * 5)) + (6 * Math.round(g / 255 * 5)) + Math.round(b / 255 * 5); return ansi; }; convert.ansi16.rgb = function (args) { let color = args % 10; // Handle greyscale if (color === 0 || color === 7) { if (args > 50) { color += 3.5; } color = color / 10.5 * 255; return [color, color, color]; } const mult = (~~(args > 50) + 1) * 0.5; const r = ((color & 1) * mult) * 255; const g = (((color >> 1) & 1) * mult) * 255; const b = (((color >> 2) & 1) * mult) * 255; return [r, g, b]; }; convert.ansi256.rgb = function (args) { // Handle greyscale if (args >= 232) { const c = (args - 232) * 10 + 8; return [c, c, c]; } args -= 16; let rem; const r = Math.floor(args / 36) / 5 * 255; const g = Math.floor((rem = args % 36) / 6) / 5 * 255; const b = (rem % 6) / 5 * 255; return [r, g, b]; }; convert.rgb.hex = function (args) { const integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); const string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.hex.rgb = function (args) { const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); if (!match) { return [0, 0, 0]; } let colorString = match[0]; if (match[0].length === 3) { colorString = colorString.split('').map(char => { return char + char; }).join(''); } const integer = parseInt(colorString, 16); const r = (integer >> 16) & 0xFF; const g = (integer >> 8) & 0xFF; const b = integer & 0xFF; return [r, g, b]; }; convert.rgb.hcg = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const max = Math.max(Math.max(r, g), b); const min = Math.min(Math.min(r, g), b); const chroma = (max - min); let grayscale; let hue; if (chroma < 1) { grayscale = min / (1 - chroma); } else { grayscale = 0; } if (chroma <= 0) { hue = 0; } else if (max === r) { hue = ((g - b) / chroma) % 6; } else if (max === g) { hue = 2 + (b - r) / chroma; } else { hue = 4 + (r - g) / chroma; } hue /= 6; hue %= 1; return [hue * 360, chroma * 100, grayscale * 100]; }; convert.hsl.hcg = function (hsl) { const s = hsl[1] / 100; const l = hsl[2] / 100; const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); let f = 0; if (c < 1.0) { f = (l - 0.5 * c) / (1.0 - c); } return [hsl[0], c * 100, f * 100]; }; convert.hsv.hcg = function (hsv) { const s = hsv[1] / 100; const v = hsv[2] / 100; const c = s * v; let f = 0; if (c < 1.0) { f = (v - c) / (1 - c); } return [hsv[0], c * 100, f * 100]; }; convert.hcg.rgb = function (hcg) { const h = hcg[0] / 360; const c = hcg[1] / 100; const g = hcg[2] / 100; if (c === 0.0) { return [g * 255, g * 255, g * 255]; } const pure = [0, 0, 0]; const hi = (h % 1) * 6; const v = hi % 1; const w = 1 - v; let mg = 0; /* eslint-disable max-statements-per-line */ switch (Math.floor(hi)) { case 0: pure[0] = 1; pure[1] = v; pure[2] = 0; break; case 1: pure[0] = w; pure[1] = 1; pure[2] = 0; break; case 2: pure[0] = 0; pure[1] = 1; pure[2] = v; break; case 3: pure[0] = 0; pure[1] = w; pure[2] = 1; break; case 4: pure[0] = v; pure[1] = 0; pure[2] = 1; break; default: pure[0] = 1; pure[1] = 0; pure[2] = w; } /* eslint-enable max-statements-per-line */ mg = (1.0 - c) * g; return [ (c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255 ]; }; convert.hcg.hsv = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const v = c + g * (1.0 - c); let f = 0; if (v > 0.0) { f = c / v; } return [hcg[0], f * 100, v * 100]; }; convert.hcg.hsl = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const l = g * (1.0 - c) + 0.5 * c; let s = 0; if (l > 0.0 && l < 0.5) { s = c / (2 * l); } else if (l >= 0.5 && l < 1.0) { s = c / (2 * (1 - l)); } return [hcg[0], s * 100, l * 100]; }; convert.hcg.hwb = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const v = c + g * (1.0 - c); return [hcg[0], (v - c) * 100, (1 - v) * 100]; }; convert.hwb.hcg = function (hwb) { const w = hwb[1] / 100; const b = hwb[2] / 100; const v = 1 - b; const c = v - w; let g = 0; if (c < 1) { g = (v - c) / (1 - c); } return [hwb[0], c * 100, g * 100]; }; convert.apple.rgb = function (apple) { return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; }; convert.rgb.apple = function (rgb) { return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; }; convert.gray.rgb = function (args) { return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; }; convert.gray.hsl = function (args) { return [0, 0, args[0]]; }; convert.gray.hsv = convert.gray.hsl; convert.gray.hwb = function (gray) { return [0, 100, gray[0]]; }; convert.gray.cmyk = function (gray) { return [0, 0, 0, gray[0]]; }; convert.gray.lab = function (gray) { return [gray[0], 0, 0]; }; convert.gray.hex = function (gray) { const val = Math.round(gray[0] / 100 * 255) & 0xFF; const integer = (val << 16) + (val << 8) + val; const string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.rgb.gray = function (rgb) { const val = (rgb[0] + rgb[1] + rgb[2]) / 3; return [val / 255 * 100]; }; /***/ }), /***/ 20698: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const conversions = __webpack_require__(99595); const route = __webpack_require__(69591); const convert = {}; const models = Object.keys(conversions); function wrapRaw(fn) { const wrappedFn = function (...args) { const arg0 = args[0]; if (arg0 === undefined || arg0 === null) { return arg0; } if (arg0.length > 1) { args = arg0; } return fn(args); }; // Preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } function wrapRounded(fn) { const wrappedFn = function (...args) { const arg0 = args[0]; if (arg0 === undefined || arg0 === null) { return arg0; } if (arg0.length > 1) { args = arg0; } const result = fn(args); // We're assuming the result is an array here. // see notice in conversions.js; don't use box types // in conversion functions. if (typeof result === 'object') { for (let len = result.length, i = 0; i < len; i++) { result[i] = Math.round(result[i]); } } return result; }; // Preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } models.forEach(fromModel => { convert[fromModel] = {}; Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); const routes = route(fromModel); const routeModels = Object.keys(routes); routeModels.forEach(toModel => { const fn = routes[toModel]; convert[fromModel][toModel] = wrapRounded(fn); convert[fromModel][toModel].raw = wrapRaw(fn); }); }); module.exports = convert; /***/ }), /***/ 69591: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const conversions = __webpack_require__(99595); /* This function routes a model to all other models. all functions that are routed have a property `.conversion` attached to the returned synthetic function. This property is an array of strings, each with the steps in between the 'from' and 'to' color models (inclusive). conversions that are not possible simply are not included. */ function buildGraph() { const graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3 const models = Object.keys(conversions); for (let len = models.length, i = 0; i < len; i++) { graph[models[i]] = { // http://jsperf.com/1-vs-infinity // micro-opt, but this is simple. distance: -1, parent: null }; } return graph; } // https://en.wikipedia.org/wiki/Breadth-first_search function deriveBFS(fromModel) { const graph = buildGraph(); const queue = [fromModel]; // Unshift -> queue -> pop graph[fromModel].distance = 0; while (queue.length) { const current = queue.pop(); const adjacents = Object.keys(conversions[current]); for (let len = adjacents.length, i = 0; i < len; i++) { const adjacent = adjacents[i]; const node = graph[adjacent]; if (node.distance === -1) { node.distance = graph[current].distance + 1; node.parent = current; queue.unshift(adjacent); } } } return graph; } function link(from, to) { return function (args) { return to(from(args)); }; } function wrapConversion(toModel, graph) { const path = [graph[toModel].parent, toModel]; let fn = conversions[graph[toModel].parent][toModel]; let cur = graph[toModel].parent; while (graph[cur].parent) { path.unshift(graph[cur].parent); fn = link(conversions[graph[cur].parent][cur], fn); cur = graph[cur].parent; } fn.conversion = path; return fn; } module.exports = function (fromModel) { const graph = deriveBFS(fromModel); const conversion = {}; const models = Object.keys(graph); for (let len = models.length, i = 0; i < len; i++) { const toModel = models[i]; const node = graph[toModel]; if (node.parent === null) { // No possible conversion, or this node is the source model. continue; } conversion[toModel] = wrapConversion(toModel, graph); } return conversion; }; /***/ }), /***/ 56662: /***/ ((module) => { "use strict"; module.exports = { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255, 235, 205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategray": [47, 79, 79], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "grey": [128, 128, 128], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "rebeccapurple": [102, 51, 153], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50] }; /***/ }), /***/ 25234: /***/ ((module) => { "use strict"; module.exports = (flag, argv = process.argv) => { const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); const position = argv.indexOf(prefix + flag); const terminatorPosition = argv.indexOf('--'); return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); }; /***/ }), /***/ 25176: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // A linked list to keep track of recently-used-ness const Yallist = __webpack_require__(92191) const MAX = Symbol('max') const LENGTH = Symbol('length') const LENGTH_CALCULATOR = Symbol('lengthCalculator') const ALLOW_STALE = Symbol('allowStale') const MAX_AGE = Symbol('maxAge') const DISPOSE = Symbol('dispose') const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') const LRU_LIST = Symbol('lruList') const CACHE = Symbol('cache') const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') const naiveLength = () => 1 // lruList is a yallist where the head is the youngest // item, and the tail is the oldest. the list contains the Hit // objects as the entries. // Each Hit object has a reference to its Yallist.Node. This // never changes. // // cache is a Map (or PseudoMap) that matches the keys to // the Yallist.Node object. class LRUCache { constructor (options) { if (typeof options === 'number') options = { max: options } if (!options) options = {} if (options.max && (typeof options.max !== 'number' || options.max < 0)) throw new TypeError('max must be a non-negative number') // Kind of weird to have a default max of Infinity, but oh well. const max = this[MAX] = options.max || Infinity const lc = options.length || naiveLength this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc this[ALLOW_STALE] = options.stale || false if (options.maxAge && typeof options.maxAge !== 'number') throw new TypeError('maxAge must be a number') this[MAX_AGE] = options.maxAge || 0 this[DISPOSE] = options.dispose this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false this.reset() } // resize the cache when the max changes. set max (mL) { if (typeof mL !== 'number' || mL < 0) throw new TypeError('max must be a non-negative number') this[MAX] = mL || Infinity trim(this) } get max () { return this[MAX] } set allowStale (allowStale) { this[ALLOW_STALE] = !!allowStale } get allowStale () { return this[ALLOW_STALE] } set maxAge (mA) { if (typeof mA !== 'number') throw new TypeError('maxAge must be a non-negative number') this[MAX_AGE] = mA trim(this) } get maxAge () { return this[MAX_AGE] } // resize the cache when the lengthCalculator changes. set lengthCalculator (lC) { if (typeof lC !== 'function') lC = naiveLength if (lC !== this[LENGTH_CALCULATOR]) { this[LENGTH_CALCULATOR] = lC this[LENGTH] = 0 this[LRU_LIST].forEach(hit => { hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) this[LENGTH] += hit.length }) } trim(this) } get lengthCalculator () { return this[LENGTH_CALCULATOR] } get length () { return this[LENGTH] } get itemCount () { return this[LRU_LIST].length } rforEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].tail; walker !== null;) { const prev = walker.prev forEachStep(this, fn, walker, thisp) walker = prev } } forEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].head; walker !== null;) { const next = walker.next forEachStep(this, fn, walker, thisp) walker = next } } keys () { return this[LRU_LIST].toArray().map(k => k.key) } values () { return this[LRU_LIST].toArray().map(k => k.value) } reset () { if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) { this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) } this[CACHE] = new Map() // hash of items by key this[LRU_LIST] = new Yallist() // list of items in order of use recency this[LENGTH] = 0 // length of items in the list } dump () { return this[LRU_LIST].map(hit => isStale(this, hit) ? false : { k: hit.key, v: hit.value, e: hit.now + (hit.maxAge || 0) }).toArray().filter(h => h) } dumpLru () { return this[LRU_LIST] } set (key, value, maxAge) { maxAge = maxAge || this[MAX_AGE] if (maxAge && typeof maxAge !== 'number') throw new TypeError('maxAge must be a number') const now = maxAge ? Date.now() : 0 const len = this[LENGTH_CALCULATOR](value, key) if (this[CACHE].has(key)) { if (len > this[MAX]) { del(this, this[CACHE].get(key)) return false } const node = this[CACHE].get(key) const item = node.value // dispose of the old one before overwriting // split out into 2 ifs for better coverage tracking if (this[DISPOSE]) { if (!this[NO_DISPOSE_ON_SET]) this[DISPOSE](key, item.value) } item.now = now item.maxAge = maxAge item.value = value this[LENGTH] += len - item.length item.length = len this.get(key) trim(this) return true } const hit = new Entry(key, value, len, now, maxAge) // oversized objects fall out of cache automatically. if (hit.length > this[MAX]) { if (this[DISPOSE]) this[DISPOSE](key, value) return false } this[LENGTH] += hit.length this[LRU_LIST].unshift(hit) this[CACHE].set(key, this[LRU_LIST].head) trim(this) return true } has (key) { if (!this[CACHE].has(key)) return false const hit = this[CACHE].get(key).value return !isStale(this, hit) } get (key) { return get(this, key, true) } peek (key) { return get(this, key, false) } pop () { const node = this[LRU_LIST].tail if (!node) return null del(this, node) return node.value } del (key) { del(this, this[CACHE].get(key)) } load (arr) { // reset the cache this.reset() const now = Date.now() // A previous serialized cache has the most recent items first for (let l = arr.length - 1; l >= 0; l--) { const hit = arr[l] const expiresAt = hit.e || 0 if (expiresAt === 0) // the item was created without expiration in a non aged cache this.set(hit.k, hit.v) else { const maxAge = expiresAt - now // dont add already expired items if (maxAge > 0) { this.set(hit.k, hit.v, maxAge) } } } } prune () { this[CACHE].forEach((value, key) => get(this, key, false)) } } const get = (self, key, doUse) => { const node = self[CACHE].get(key) if (node) { const hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) return undefined } else { if (doUse) { if (self[UPDATE_AGE_ON_GET]) node.value.now = Date.now() self[LRU_LIST].unshiftNode(node) } } return hit.value } } const isStale = (self, hit) => { if (!hit || (!hit.maxAge && !self[MAX_AGE])) return false const diff = Date.now() - hit.now return hit.maxAge ? diff > hit.maxAge : self[MAX_AGE] && (diff > self[MAX_AGE]) } const trim = self => { if (self[LENGTH] > self[MAX]) { for (let walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) { // We know that we're about to delete this one, and also // what the next least recently used key will be, so just // go ahead and set it now. const prev = walker.prev del(self, walker) walker = prev } } } const del = (self, node) => { if (node) { const hit = node.value if (self[DISPOSE]) self[DISPOSE](hit.key, hit.value) self[LENGTH] -= hit.length self[CACHE].delete(hit.key) self[LRU_LIST].removeNode(node) } } class Entry { constructor (key, value, length, now, maxAge) { this.key = key this.value = value this.length = length this.now = now this.maxAge = maxAge || 0 } } const forEachStep = (self, fn, node, thisp) => { let hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) hit = undefined } if (hit) fn.call(thisp, hit.value, hit.key, self) } module.exports = LRUCache /***/ }), /***/ 62874: /***/ ((module, exports, __webpack_require__) => { "use strict"; var crypto = __webpack_require__(6113); /** * Exported function * * Options: * * - `algorithm` hash algo to be used by this instance: *'sha1', 'md5' * - `excludeValues` {true|*false} hash object keys, values ignored * - `encoding` hash encoding, supports 'buffer', '*hex', 'binary', 'base64' * - `ignoreUnknown` {true|*false} ignore unknown object types * - `replacer` optional function that replaces values before hashing * - `respectFunctionProperties` {*true|false} consider function properties when hashing * - `respectFunctionNames` {*true|false} consider 'name' property of functions for hashing * - `respectType` {*true|false} Respect special properties (prototype, constructor) * when hashing to distinguish between types * - `unorderedArrays` {true|*false} Sort all arrays before hashing * - `unorderedSets` {*true|false} Sort `Set` and `Map` instances before hashing * * = default * * @param {object} object value to hash * @param {object} options hashing options * @return {string} hash value * @api public */ exports = module.exports = objectHash; function objectHash(object, options){ options = applyDefaults(object, options); return hash(object, options); } /** * Exported sugar methods * * @param {object} object value to hash * @return {string} hash value * @api public */ exports.sha1 = function(object){ return objectHash(object); }; exports.keys = function(object){ return objectHash(object, {excludeValues: true, algorithm: 'sha1', encoding: 'hex'}); }; exports.MD5 = function(object){ return objectHash(object, {algorithm: 'md5', encoding: 'hex'}); }; exports.keysMD5 = function(object){ return objectHash(object, {algorithm: 'md5', encoding: 'hex', excludeValues: true}); }; // Internals var hashes = crypto.getHashes ? crypto.getHashes().slice() : ['sha1', 'md5']; hashes.push('passthrough'); var encodings = ['buffer', 'hex', 'binary', 'base64']; function applyDefaults(object, sourceOptions){ sourceOptions = sourceOptions || {}; // create a copy rather than mutating var options = {}; options.algorithm = sourceOptions.algorithm || 'sha1'; options.encoding = sourceOptions.encoding || 'hex'; options.excludeValues = sourceOptions.excludeValues ? true : false; options.algorithm = options.algorithm.toLowerCase(); options.encoding = options.encoding.toLowerCase(); options.ignoreUnknown = sourceOptions.ignoreUnknown !== true ? false : true; // default to false options.respectType = sourceOptions.respectType === false ? false : true; // default to true options.respectFunctionNames = sourceOptions.respectFunctionNames === false ? false : true; options.respectFunctionProperties = sourceOptions.respectFunctionProperties === false ? false : true; options.unorderedArrays = sourceOptions.unorderedArrays !== true ? false : true; // default to false options.unorderedSets = sourceOptions.unorderedSets === false ? false : true; // default to false options.unorderedObjects = sourceOptions.unorderedObjects === false ? false : true; // default to true options.replacer = sourceOptions.replacer || undefined; options.excludeKeys = sourceOptions.excludeKeys || undefined; if(typeof object === 'undefined') { throw new Error('Object argument required.'); } // if there is a case-insensitive match in the hashes list, accept it // (i.e. SHA256 for sha256) for (var i = 0; i < hashes.length; ++i) { if (hashes[i].toLowerCase() === options.algorithm.toLowerCase()) { options.algorithm = hashes[i]; } } if(hashes.indexOf(options.algorithm) === -1){ throw new Error('Algorithm "' + options.algorithm + '" not supported. ' + 'supported values: ' + hashes.join(', ')); } if(encodings.indexOf(options.encoding) === -1 && options.algorithm !== 'passthrough'){ throw new Error('Encoding "' + options.encoding + '" not supported. ' + 'supported values: ' + encodings.join(', ')); } return options; } /** Check if the given function is a native function */ function isNativeFunction(f) { if ((typeof f) !== 'function') { return false; } var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i; return exp.exec(Function.prototype.toString.call(f)) != null; } function hash(object, options) { var hashingStream; if (options.algorithm !== 'passthrough') { hashingStream = crypto.createHash(options.algorithm); } else { hashingStream = new PassThrough(); } if (typeof hashingStream.write === 'undefined') { hashingStream.write = hashingStream.update; hashingStream.end = hashingStream.update; } var hasher = typeHasher(options, hashingStream); hasher.dispatch(object); if (!hashingStream.update) { hashingStream.end(''); } if (hashingStream.digest) { return hashingStream.digest(options.encoding === 'buffer' ? undefined : options.encoding); } var buf = hashingStream.read(); if (options.encoding === 'buffer') { return buf; } return buf.toString(options.encoding); } /** * Expose streaming API * * @param {object} object Value to serialize * @param {object} options Options, as for hash() * @param {object} stream A stream to write the serializiation to * @api public */ exports.writeToStream = function(object, options, stream) { if (typeof stream === 'undefined') { stream = options; options = {}; } options = applyDefaults(object, options); return typeHasher(options, stream).dispatch(object); }; function typeHasher(options, writeTo, context){ context = context || []; var write = function(str) { if (writeTo.update) { return writeTo.update(str, 'utf8'); } else { return writeTo.write(str, 'utf8'); } }; return { dispatch: function(value){ if (options.replacer) { value = options.replacer(value); } var type = typeof value; if (value === null) { type = 'null'; } //console.log("[DEBUG] Dispatch: ", value, "->", type, " -> ", "_" + type); return this['_' + type](value); }, _object: function(object) { var pattern = (/\[object (.*)\]/i); var objString = Object.prototype.toString.call(object); var objType = pattern.exec(objString); if (!objType) { // object type did not match [object ...] objType = 'unknown:[' + objString + ']'; } else { objType = objType[1]; // take only the class name } objType = objType.toLowerCase(); var objectNumber = null; if ((objectNumber = context.indexOf(object)) >= 0) { return this.dispatch('[CIRCULAR:' + objectNumber + ']'); } else { context.push(object); } if (typeof Buffer !== 'undefined' && Buffer.isBuffer && Buffer.isBuffer(object)) { write('buffer:'); return write(object); } if(objType !== 'object' && objType !== 'function' && objType !== 'asyncfunction') { if(this['_' + objType]) { this['_' + objType](object); } else if (options.ignoreUnknown) { return write('[' + objType + ']'); } else { throw new Error('Unknown object type "' + objType + '"'); } }else{ var keys = Object.keys(object); if (options.unorderedObjects) { keys = keys.sort(); } // Make sure to incorporate special properties, so // Types with different prototypes will produce // a different hash and objects derived from // different functions (`new Foo`, `new Bar`) will // produce different hashes. // We never do this for native functions since some // seem to break because of that. if (options.respectType !== false && !isNativeFunction(object)) { keys.splice(0, 0, 'prototype', '__proto__', 'constructor'); } if (options.excludeKeys) { keys = keys.filter(function(key) { return !options.excludeKeys(key); }); } write('object:' + keys.length + ':'); var self = this; return keys.forEach(function(key){ self.dispatch(key); write(':'); if(!options.excludeValues) { self.dispatch(object[key]); } write(','); }); } }, _array: function(arr, unordered){ unordered = typeof unordered !== 'undefined' ? unordered : options.unorderedArrays !== false; // default to options.unorderedArrays var self = this; write('array:' + arr.length + ':'); if (!unordered || arr.length <= 1) { return arr.forEach(function(entry) { return self.dispatch(entry); }); } // the unordered case is a little more complicated: // since there is no canonical ordering on objects, // i.e. {a:1} < {a:2} and {a:1} > {a:2} are both false, // we first serialize each entry using a PassThrough stream // before sorting. // also: we can’t use the same context array for all entries // since the order of hashing should *not* matter. instead, // we keep track of the additions to a copy of the context array // and add all of them to the global context array when we’re done var contextAdditions = []; var entries = arr.map(function(entry) { var strm = new PassThrough(); var localContext = context.slice(); // make copy var hasher = typeHasher(options, strm, localContext); hasher.dispatch(entry); // take only what was added to localContext and append it to contextAdditions contextAdditions = contextAdditions.concat(localContext.slice(context.length)); return strm.read().toString(); }); context = context.concat(contextAdditions); entries.sort(); return this._array(entries, false); }, _date: function(date){ return write('date:' + date.toJSON()); }, _symbol: function(sym){ return write('symbol:' + sym.toString()); }, _error: function(err){ return write('error:' + err.toString()); }, _boolean: function(bool){ return write('bool:' + bool.toString()); }, _string: function(string){ write('string:' + string.length + ':'); write(string.toString()); }, _function: function(fn){ write('fn:'); if (isNativeFunction(fn)) { this.dispatch('[native]'); } else { this.dispatch(fn.toString()); } if (options.respectFunctionNames !== false) { // Make sure we can still distinguish native functions // by their name, otherwise String and Function will // have the same hash this.dispatch("function-name:" + String(fn.name)); } if (options.respectFunctionProperties) { this._object(fn); } }, _number: function(number){ return write('number:' + number.toString()); }, _xml: function(xml){ return write('xml:' + xml.toString()); }, _null: function() { return write('Null'); }, _undefined: function() { return write('Undefined'); }, _regexp: function(regex){ return write('regex:' + regex.toString()); }, _uint8array: function(arr){ write('uint8array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _uint8clampedarray: function(arr){ write('uint8clampedarray:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _int8array: function(arr){ write('uint8array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _uint16array: function(arr){ write('uint16array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _int16array: function(arr){ write('uint16array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _uint32array: function(arr){ write('uint32array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _int32array: function(arr){ write('uint32array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _float32array: function(arr){ write('float32array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _float64array: function(arr){ write('float64array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _arraybuffer: function(arr){ write('arraybuffer:'); return this.dispatch(new Uint8Array(arr)); }, _url: function(url) { return write('url:' + url.toString(), 'utf8'); }, _map: function(map) { write('map:'); var arr = Array.from(map); return this._array(arr, options.unorderedSets !== false); }, _set: function(set) { write('set:'); var arr = Array.from(set); return this._array(arr, options.unorderedSets !== false); }, _file: function(file) { write('file:'); return this.dispatch([file.name, file.size, file.type, file.lastModfied]); }, _blob: function() { if (options.ignoreUnknown) { return write('[blob]'); } throw Error('Hashing Blob objects is currently not supported\n' + '(see https://github.com/puleos/object-hash/issues/26)\n' + 'Use "options.replacer" or "options.ignoreUnknown"\n'); }, _domwindow: function() { return write('domwindow'); }, _bigint: function(number){ return write('bigint:' + number.toString()); }, /* Node.js standard native objects */ _process: function() { return write('process'); }, _timer: function() { return write('timer'); }, _pipe: function() { return write('pipe'); }, _tcp: function() { return write('tcp'); }, _udp: function() { return write('udp'); }, _tty: function() { return write('tty'); }, _statwatcher: function() { return write('statwatcher'); }, _securecontext: function() { return write('securecontext'); }, _connection: function() { return write('connection'); }, _zlib: function() { return write('zlib'); }, _context: function() { return write('context'); }, _nodescript: function() { return write('nodescript'); }, _httpparser: function() { return write('httpparser'); }, _dataview: function() { return write('dataview'); }, _signal: function() { return write('signal'); }, _fsevent: function() { return write('fsevent'); }, _tlswrap: function() { return write('tlswrap'); }, }; } // Mini-implementation of stream.PassThrough // We are far from having need for the full implementation, and we can // make assumptions like "many writes, then only one final read" // and we can ignore encoding specifics function PassThrough() { return { buf: '', write: function(b) { this.buf += b; }, end: function(b) { this.buf += b; }, read: function() { return this.buf; } }; } /***/ }), /***/ 53200: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const assert = __webpack_require__(39491) const path = __webpack_require__(71017) const fs = __webpack_require__(57147) let glob = undefined try { glob = __webpack_require__(12884) } catch (_err) { // treat glob as optional. } const defaultGlobOpts = { nosort: true, silent: true } // for EMFILE handling let timeout = 0 const isWindows = (process.platform === "win32") const defaults = options => { const methods = [ 'unlink', 'chmod', 'stat', 'lstat', 'rmdir', 'readdir' ] methods.forEach(m => { options[m] = options[m] || fs[m] m = m + 'Sync' options[m] = options[m] || fs[m] }) options.maxBusyTries = options.maxBusyTries || 3 options.emfileWait = options.emfileWait || 1000 if (options.glob === false) { options.disableGlob = true } if (options.disableGlob !== true && glob === undefined) { throw Error('glob dependency not found, set `options.disableGlob = true` if intentional') } options.disableGlob = options.disableGlob || false options.glob = options.glob || defaultGlobOpts } const rimraf = (p, options, cb) => { if (typeof options === 'function') { cb = options options = {} } assert(p, 'rimraf: missing path') assert.equal(typeof p, 'string', 'rimraf: path should be a string') assert.equal(typeof cb, 'function', 'rimraf: callback function required') assert(options, 'rimraf: invalid options argument provided') assert.equal(typeof options, 'object', 'rimraf: options should be object') defaults(options) let busyTries = 0 let errState = null let n = 0 const next = (er) => { errState = errState || er if (--n === 0) cb(errState) } const afterGlob = (er, results) => { if (er) return cb(er) n = results.length if (n === 0) return cb() results.forEach(p => { const CB = (er) => { if (er) { if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && busyTries < options.maxBusyTries) { busyTries ++ // try again, with the same exact callback as this one. return setTimeout(() => rimraf_(p, options, CB), busyTries * 100) } // this one won't happen if graceful-fs is used. if (er.code === "EMFILE" && timeout < options.emfileWait) { return setTimeout(() => rimraf_(p, options, CB), timeout ++) } // already gone if (er.code === "ENOENT") er = null } timeout = 0 next(er) } rimraf_(p, options, CB) }) } if (options.disableGlob || !glob.hasMagic(p)) return afterGlob(null, [p]) options.lstat(p, (er, stat) => { if (!er) return afterGlob(null, [p]) glob(p, options.glob, afterGlob) }) } // Two possible strategies. // 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR // 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR // // Both result in an extra syscall when you guess wrong. However, there // are likely far more normal files in the world than directories. This // is based on the assumption that a the average number of files per // directory is >= 1. // // If anyone ever complains about this, then I guess the strategy could // be made configurable somehow. But until then, YAGNI. const rimraf_ = (p, options, cb) => { assert(p) assert(options) assert(typeof cb === 'function') // sunos lets the root user unlink directories, which is... weird. // so we have to lstat here and make sure it's not a dir. options.lstat(p, (er, st) => { if (er && er.code === "ENOENT") return cb(null) // Windows can EPERM on stat. Life is suffering. if (er && er.code === "EPERM" && isWindows) fixWinEPERM(p, options, er, cb) if (st && st.isDirectory()) return rmdir(p, options, er, cb) options.unlink(p, er => { if (er) { if (er.code === "ENOENT") return cb(null) if (er.code === "EPERM") return (isWindows) ? fixWinEPERM(p, options, er, cb) : rmdir(p, options, er, cb) if (er.code === "EISDIR") return rmdir(p, options, er, cb) } return cb(er) }) }) } const fixWinEPERM = (p, options, er, cb) => { assert(p) assert(options) assert(typeof cb === 'function') options.chmod(p, 0o666, er2 => { if (er2) cb(er2.code === "ENOENT" ? null : er) else options.stat(p, (er3, stats) => { if (er3) cb(er3.code === "ENOENT" ? null : er) else if (stats.isDirectory()) rmdir(p, options, er, cb) else options.unlink(p, cb) }) }) } const fixWinEPERMSync = (p, options, er) => { assert(p) assert(options) try { options.chmodSync(p, 0o666) } catch (er2) { if (er2.code === "ENOENT") return else throw er } let stats try { stats = options.statSync(p) } catch (er3) { if (er3.code === "ENOENT") return else throw er } if (stats.isDirectory()) rmdirSync(p, options, er) else options.unlinkSync(p) } const rmdir = (p, options, originalEr, cb) => { assert(p) assert(options) assert(typeof cb === 'function') // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) // if we guessed wrong, and it's not a directory, then // raise the original error. options.rmdir(p, er => { if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) rmkids(p, options, cb) else if (er && er.code === "ENOTDIR") cb(originalEr) else cb(er) }) } const rmkids = (p, options, cb) => { assert(p) assert(options) assert(typeof cb === 'function') options.readdir(p, (er, files) => { if (er) return cb(er) let n = files.length if (n === 0) return options.rmdir(p, cb) let errState files.forEach(f => { rimraf(path.join(p, f), options, er => { if (errState) return if (er) return cb(errState = er) if (--n === 0) options.rmdir(p, cb) }) }) }) } // this looks simpler, and is strictly *faster*, but will // tie up the JavaScript thread and fail on excessively // deep directory trees. const rimrafSync = (p, options) => { options = options || {} defaults(options) assert(p, 'rimraf: missing path') assert.equal(typeof p, 'string', 'rimraf: path should be a string') assert(options, 'rimraf: missing options') assert.equal(typeof options, 'object', 'rimraf: options should be object') let results if (options.disableGlob || !glob.hasMagic(p)) { results = [p] } else { try { options.lstatSync(p) results = [p] } catch (er) { results = glob.sync(p, options.glob) } } if (!results.length) return for (let i = 0; i < results.length; i++) { const p = results[i] let st try { st = options.lstatSync(p) } catch (er) { if (er.code === "ENOENT") return // Windows can EPERM on stat. Life is suffering. if (er.code === "EPERM" && isWindows) fixWinEPERMSync(p, options, er) } try { // sunos lets the root user unlink directories, which is... weird. if (st && st.isDirectory()) rmdirSync(p, options, null) else options.unlinkSync(p) } catch (er) { if (er.code === "ENOENT") return if (er.code === "EPERM") return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) if (er.code !== "EISDIR") throw er rmdirSync(p, options, er) } } } const rmdirSync = (p, options, originalEr) => { assert(p) assert(options) try { options.rmdirSync(p) } catch (er) { if (er.code === "ENOENT") return if (er.code === "ENOTDIR") throw originalEr if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") rmkidsSync(p, options) } } const rmkidsSync = (p, options) => { assert(p) assert(options) options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)) // We only end up here once we got ENOTEMPTY at least once, and // at this point, we are guaranteed to have removed all the kids. // So, we know that it won't be ENOENT or ENOTDIR or anything else. // try really hard to delete stuff on windows, because it has a // PROFOUNDLY annoying habit of not closing handles promptly when // files are deleted, resulting in spurious ENOTEMPTY errors. const retries = isWindows ? 100 : 1 let i = 0 do { let threw = true try { const ret = options.rmdirSync(p, options) threw = false return ret } finally { if (++i < retries && threw) continue } } while (true) } module.exports = rimraf rimraf.sync = rimrafSync /***/ }), /***/ 99767: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const ANY = Symbol('SemVer ANY') // hoisted class for cyclic dependency class Comparator { static get ANY () { return ANY } constructor (comp, options) { options = parseOptions(options) if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } comp = comp.trim().split(/\s+/).join(' ') debug('comparator', comp, options) this.options = options this.loose = !!options.loose this.parse(comp) if (this.semver === ANY) { this.value = '' } else { this.value = this.operator + this.semver.version } debug('comp', this) } parse (comp) { const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] const m = comp.match(r) if (!m) { throw new TypeError(`Invalid comparator: ${comp}`) } this.operator = m[1] !== undefined ? m[1] : '' if (this.operator === '=') { this.operator = '' } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY } else { this.semver = new SemVer(m[2], this.options.loose) } } toString () { return this.value } test (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY || version === ANY) { return true } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } return cmp(version, this.operator, this.semver, this.options) } intersects (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (this.operator === '') { if (this.value === '') { return true } return new Range(comp.value, options).test(this.value) } else if (comp.operator === '') { if (comp.value === '') { return true } return new Range(this.value, options).test(comp.semver) } options = parseOptions(options) // Special cases where nothing can possibly be lower if (options.includePrerelease && (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { return false } if (!options.includePrerelease && (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { return false } // Same direction increasing (> or >=) if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { return true } // Same direction decreasing (< or <=) if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { return true } // same SemVer and both sides are inclusive (<= or >=) if ( (this.semver.version === comp.semver.version) && this.operator.includes('=') && comp.operator.includes('=')) { return true } // opposite directions less than if (cmp(this.semver, '<', comp.semver, options) && this.operator.startsWith('>') && comp.operator.startsWith('<')) { return true } // opposite directions greater than if (cmp(this.semver, '>', comp.semver, options) && this.operator.startsWith('<') && comp.operator.startsWith('>')) { return true } return false } } module.exports = Comparator const parseOptions = __webpack_require__(60920) const { safeRe: re, t } = __webpack_require__(42262) const cmp = __webpack_require__(32986) const debug = __webpack_require__(93948) const SemVer = __webpack_require__(68039) const Range = __webpack_require__(45859) /***/ }), /***/ 45859: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // hoisted class for cyclic dependency class Range { constructor (range, options) { options = parseOptions(options) if (range instanceof Range) { if ( range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease ) { return range } else { return new Range(range.raw, options) } } if (range instanceof Comparator) { // just put it in the set and return this.raw = range.value this.set = [[range]] this.format() return this } this.options = options this.loose = !!options.loose this.includePrerelease = !!options.includePrerelease // First reduce all whitespace as much as possible so we do not have to rely // on potentially slow regexes like \s*. This is then stored and used for // future error messages as well. this.raw = range .trim() .split(/\s+/) .join(' ') // First, split on || this.set = this.raw .split('||') // map the range to a 2d array of comparators .map(r => this.parseRange(r.trim())) // throw out any comparator lists that are empty // this generally means that it was not a valid range, which is allowed // in loose mode, but will still throw if the WHOLE range is invalid. .filter(c => c.length) if (!this.set.length) { throw new TypeError(`Invalid SemVer Range: ${this.raw}`) } // if we have any that are not the null set, throw out null sets. if (this.set.length > 1) { // keep the first one, in case they're all null sets const first = this.set[0] this.set = this.set.filter(c => !isNullSet(c[0])) if (this.set.length === 0) { this.set = [first] } else if (this.set.length > 1) { // if we have any that are *, then the range is just * for (const c of this.set) { if (c.length === 1 && isAny(c[0])) { this.set = [c] break } } } } this.format() } format () { this.range = this.set .map((comps) => comps.join(' ').trim()) .join('||') .trim() return this.range } toString () { return this.range } parseRange (range) { // memoize range parsing for performance. // this is a very hot path, and fully deterministic. const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE) const memoKey = memoOpts + ':' + range const cached = cache.get(memoKey) if (cached) { return cached } const loose = this.options.loose // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range) // `~ 1.2.3` => `~1.2.3` range = range.replace(re[t.TILDETRIM], tildeTrimReplace) debug('tilde trim', range) // `^ 1.2.3` => `^1.2.3` range = range.replace(re[t.CARETTRIM], caretTrimReplace) debug('caret trim', range) // At this point, the range is completely trimmed and // ready to be split into comparators. let rangeList = range .split(' ') .map(comp => parseComparator(comp, this.options)) .join(' ') .split(/\s+/) // >=0.0.0 is equivalent to * .map(comp => replaceGTE0(comp, this.options)) if (loose) { // in loose mode, throw out any that are not valid comparators rangeList = rangeList.filter(comp => { debug('loose invalid filter', comp, this.options) return !!comp.match(re[t.COMPARATORLOOSE]) }) } debug('range list', rangeList) // if any comparators are the null set, then replace with JUST null set // if more than one comparator, remove any * comparators // also, don't include the same comparator more than once const rangeMap = new Map() const comparators = rangeList.map(comp => new Comparator(comp, this.options)) for (const comp of comparators) { if (isNullSet(comp)) { return [comp] } rangeMap.set(comp.value, comp) } if (rangeMap.size > 1 && rangeMap.has('')) { rangeMap.delete('') } const result = [...rangeMap.values()] cache.set(memoKey, result) return result } intersects (range, options) { if (!(range instanceof Range)) { throw new TypeError('a Range is required') } return this.set.some((thisComparators) => { return ( isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => { return ( isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { return rangeComparators.every((rangeComparator) => { return thisComparator.intersects(rangeComparator, options) }) }) ) }) ) }) } // if ANY of the sets match ALL of its comparators, then pass test (version) { if (!version) { return false } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } for (let i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true } } return false } } module.exports = Range const LRU = __webpack_require__(25176) const cache = new LRU({ max: 1000 }) const parseOptions = __webpack_require__(60920) const Comparator = __webpack_require__(99767) const debug = __webpack_require__(93948) const SemVer = __webpack_require__(68039) const { safeRe: re, t, comparatorTrimReplace, tildeTrimReplace, caretTrimReplace, } = __webpack_require__(42262) const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __webpack_require__(10172) const isNullSet = c => c.value === '<0.0.0-0' const isAny = c => c.value === '' // take a set of comparators and determine whether there // exists a version which can satisfy it const isSatisfiable = (comparators, options) => { let result = true const remainingComparators = comparators.slice() let testComparator = remainingComparators.pop() while (result && remainingComparators.length) { result = remainingComparators.every((otherComparator) => { return testComparator.intersects(otherComparator, options) }) testComparator = remainingComparators.pop() } return result } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. const parseComparator = (comp, options) => { debug('comp', comp, options) comp = replaceCarets(comp, options) debug('caret', comp) comp = replaceTildes(comp, options) debug('tildes', comp) comp = replaceXRanges(comp, options) debug('xrange', comp) comp = replaceStars(comp, options) debug('stars', comp) return comp } const isX = id => !id || id.toLowerCase() === 'x' || id === '*' // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 // ~0.0.1 --> >=0.0.1 <0.1.0-0 const replaceTildes = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceTilde(c, options)) .join(' ') } const replaceTilde = (comp, options) => { const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] return comp.replace(r, (_, M, m, p, pr) => { debug('tilde', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0 <${+M + 1}.0.0-0` } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0-0 ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` } else if (pr) { debug('replaceTilde pr', pr) ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } else { // ~1.2.3 == >=1.2.3 <1.3.0-0 ret = `>=${M}.${m}.${p } <${M}.${+m + 1}.0-0` } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 // ^1.2.3 --> >=1.2.3 <2.0.0-0 // ^1.2.0 --> >=1.2.0 <2.0.0-0 // ^0.0.1 --> >=0.0.1 <0.0.2-0 // ^0.1.0 --> >=0.1.0 <0.2.0-0 const replaceCarets = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceCaret(c, options)) .join(' ') } const replaceCaret = (comp, options) => { debug('caret', comp, options) const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] const z = options.includePrerelease ? '-0' : '' return comp.replace(r, (_, M, m, p, pr) => { debug('caret', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` } else if (isX(p)) { if (M === '0') { ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` } else { ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p}-${pr } <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p}-${pr } <${+M + 1}.0.0-0` } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p }${z} <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p }${z} <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p } <${+M + 1}.0.0-0` } } debug('caret return', ret) return ret }) } const replaceXRanges = (comp, options) => { debug('replaceXRanges', comp, options) return comp .split(/\s+/) .map((c) => replaceXRange(c, options)) .join(' ') } const replaceXRange = (comp, options) => { comp = comp.trim() const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] return comp.replace(r, (ret, gtlt, M, m, p, pr) => { debug('xRange', comp, ret, gtlt, M, m, p, pr) const xM = isX(M) const xm = xM || isX(m) const xp = xm || isX(p) const anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } // if we're including prereleases in the match, then we need // to fix this to -0, the lowest possible prerelease value pr = options.includePrerelease ? '-0' : '' if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0-0' } else { // nothing is forbidden ret = '*' } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0 } p = 0 if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 gtlt = '>=' if (xm) { M = +M + 1 m = 0 p = 0 } else { m = +m + 1 p = 0 } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<' if (xm) { M = +M + 1 } else { m = +m + 1 } } if (gtlt === '<') { pr = '-0' } ret = `${gtlt + M}.${m}.${p}${pr}` } else if (xm) { ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` } else if (xp) { ret = `>=${M}.${m}.0${pr } <${M}.${+m + 1}.0-0` } debug('xRange return', ret) return ret }) } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. const replaceStars = (comp, options) => { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp .trim() .replace(re[t.STAR], '') } const replaceGTE0 = (comp, options) => { debug('replaceGTE0', comp, options) return comp .trim() .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') } // This function is passed to string.replace(re[t.HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 const hyphenReplace = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) => { if (isX(fM)) { from = '' } else if (isX(fm)) { from = `>=${fM}.0.0${incPr ? '-0' : ''}` } else if (isX(fp)) { from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` } else if (fpr) { from = `>=${from}` } else { from = `>=${from}${incPr ? '-0' : ''}` } if (isX(tM)) { to = '' } else if (isX(tm)) { to = `<${+tM + 1}.0.0-0` } else if (isX(tp)) { to = `<${tM}.${+tm + 1}.0-0` } else if (tpr) { to = `<=${tM}.${tm}.${tp}-${tpr}` } else if (incPr) { to = `<${tM}.${tm}.${+tp + 1}-0` } else { to = `<=${to}` } return `${from} ${to}`.trim() } const testSet = (set, version, options) => { for (let i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (let i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === Comparator.ANY) { continue } if (set[i].semver.prerelease.length > 0) { const allowed = set[i].semver if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } /***/ }), /***/ 68039: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const debug = __webpack_require__(93948) const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(10172) const { safeRe: re, t } = __webpack_require__(42262) const parseOptions = __webpack_require__(60920) const { compareIdentifiers } = __webpack_require__(41248) class SemVer { constructor (version, options) { options = parseOptions(options) if (version instanceof SemVer) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) } if (version.length > MAX_LENGTH) { throw new TypeError( `version is longer than ${MAX_LENGTH} characters` ) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose // this isn't actually relevant for versions, but keep it so that we // don't run into trouble passing this.options around. this.includePrerelease = !!options.includePrerelease const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) if (!m) { throw new TypeError(`Invalid Version: ${version}`) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map((id) => { if (/^[0-9]+$/.test(id)) { const num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } format () { this.version = `${this.major}.${this.minor}.${this.patch}` if (this.prerelease.length) { this.version += `-${this.prerelease.join('.')}` } return this.version } toString () { return this.version } compare (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { if (typeof other === 'string' && other === this.version) { return 0 } other = new SemVer(other, this.options) } if (other.version === this.version) { return 0 } return this.compareMain(other) || this.comparePre(other) } compareMain (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return ( compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) ) } comparePre (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } let i = 0 do { const a = this.prerelease[i] const b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } compareBuild (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } let i = 0 do { const a = this.build[i] const b = other.build[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc (release, identifier, identifierBase) { switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier, identifierBase) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier, identifierBase) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier, identifierBase) this.inc('pre', identifier, identifierBase) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier, identifierBase) } this.inc('pre', identifier, identifierBase) break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if ( this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0 ) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. case 'pre': { const base = Number(identifierBase) ? 1 : 0 if (!identifier && identifierBase === false) { throw new Error('invalid increment argument: identifier is empty') } if (this.prerelease.length === 0) { this.prerelease = [base] } else { let i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything if (identifier === this.prerelease.join('.') && identifierBase === false) { throw new Error('invalid increment argument: identifier already exists') } this.prerelease.push(base) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 let prerelease = [identifier, base] if (identifierBase === false) { prerelease = [identifier] } if (compareIdentifiers(this.prerelease[0], identifier) === 0) { if (isNaN(this.prerelease[1])) { this.prerelease = prerelease } } else { this.prerelease = prerelease } } break } default: throw new Error(`invalid increment argument: ${release}`) } this.raw = this.format() if (this.build.length) { this.raw += `+${this.build.join('.')}` } return this } } module.exports = SemVer /***/ }), /***/ 72493: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(52651) const clean = (version, options) => { const s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } module.exports = clean /***/ }), /***/ 32986: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const eq = __webpack_require__(32396) const neq = __webpack_require__(17165) const gt = __webpack_require__(79072) const gte = __webpack_require__(30840) const lt = __webpack_require__(81098) const lte = __webpack_require__(68276) const cmp = (a, op, b, loose) => { switch (op) { case '===': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a === b case '!==': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError(`Invalid operator: ${op}`) } } module.exports = cmp /***/ }), /***/ 18736: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(68039) const parse = __webpack_require__(52651) const { safeRe: re, t } = __webpack_require__(42262) const coerce = (version, options) => { if (version instanceof SemVer) { return version } if (typeof version === 'number') { version = String(version) } if (typeof version !== 'string') { return null } options = options || {} let match = null if (!options.rtl) { match = version.match(re[t.COERCE]) } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' // // Walk through the string checking with a /g regexp // Manually set the index so as to pick up overlapping matches. // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. let next while ((next = re[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next } re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length } // leave it in a clean state re[t.COERCERTL].lastIndex = -1 } if (match === null) { return null } return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) } module.exports = coerce /***/ }), /***/ 24352: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(68039) const compareBuild = (a, b, loose) => { const versionA = new SemVer(a, loose) const versionB = new SemVer(b, loose) return versionA.compare(versionB) || versionA.compareBuild(versionB) } module.exports = compareBuild /***/ }), /***/ 49055: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(63370) const compareLoose = (a, b) => compare(a, b, true) module.exports = compareLoose /***/ }), /***/ 63370: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(68039) const compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)) module.exports = compare /***/ }), /***/ 49078: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(52651) const diff = (version1, version2) => { const v1 = parse(version1, null, true) const v2 = parse(version2, null, true) const comparison = v1.compare(v2) if (comparison === 0) { return null } const v1Higher = comparison > 0 const highVersion = v1Higher ? v1 : v2 const lowVersion = v1Higher ? v2 : v1 const highHasPre = !!highVersion.prerelease.length const lowHasPre = !!lowVersion.prerelease.length if (lowHasPre && !highHasPre) { // Going from prerelease -> no prerelease requires some special casing // If the low version has only a major, then it will always be a major // Some examples: // 1.0.0-1 -> 1.0.0 // 1.0.0-1 -> 1.1.1 // 1.0.0-1 -> 2.0.0 if (!lowVersion.patch && !lowVersion.minor) { return 'major' } // Otherwise it can be determined by checking the high version if (highVersion.patch) { // anything higher than a patch bump would result in the wrong version return 'patch' } if (highVersion.minor) { // anything higher than a minor bump would result in the wrong version return 'minor' } // bumping major/minor/patch all have same result return 'major' } // add the `pre` prefix if we are going to a prerelease version const prefix = highHasPre ? 'pre' : '' if (v1.major !== v2.major) { return prefix + 'major' } if (v1.minor !== v2.minor) { return prefix + 'minor' } if (v1.patch !== v2.patch) { return prefix + 'patch' } // high and low are preleases return 'prerelease' } module.exports = diff /***/ }), /***/ 32396: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(63370) const eq = (a, b, loose) => compare(a, b, loose) === 0 module.exports = eq /***/ }), /***/ 79072: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(63370) const gt = (a, b, loose) => compare(a, b, loose) > 0 module.exports = gt /***/ }), /***/ 30840: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(63370) const gte = (a, b, loose) => compare(a, b, loose) >= 0 module.exports = gte /***/ }), /***/ 95714: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(68039) const inc = (version, release, options, identifier, identifierBase) => { if (typeof (options) === 'string') { identifierBase = identifier identifier = options options = undefined } try { return new SemVer( version instanceof SemVer ? version.version : version, options ).inc(release, identifier, identifierBase).version } catch (er) { return null } } module.exports = inc /***/ }), /***/ 81098: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(63370) const lt = (a, b, loose) => compare(a, b, loose) < 0 module.exports = lt /***/ }), /***/ 68276: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(63370) const lte = (a, b, loose) => compare(a, b, loose) <= 0 module.exports = lte /***/ }), /***/ 14678: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(68039) const major = (a, loose) => new SemVer(a, loose).major module.exports = major /***/ }), /***/ 63255: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(68039) const minor = (a, loose) => new SemVer(a, loose).minor module.exports = minor /***/ }), /***/ 17165: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(63370) const neq = (a, b, loose) => compare(a, b, loose) !== 0 module.exports = neq /***/ }), /***/ 52651: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(68039) const parse = (version, options, throwErrors = false) => { if (version instanceof SemVer) { return version } try { return new SemVer(version, options) } catch (er) { if (!throwErrors) { return null } throw er } } module.exports = parse /***/ }), /***/ 47940: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(68039) const patch = (a, loose) => new SemVer(a, loose).patch module.exports = patch /***/ }), /***/ 51257: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(52651) const prerelease = (version, options) => { const parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } module.exports = prerelease /***/ }), /***/ 17920: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(63370) const rcompare = (a, b, loose) => compare(b, a, loose) module.exports = rcompare /***/ }), /***/ 1861: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(24352) const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) module.exports = rsort /***/ }), /***/ 25343: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(45859) const satisfies = (version, range, options) => { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } module.exports = satisfies /***/ }), /***/ 83410: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(24352) const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) module.exports = sort /***/ }), /***/ 57427: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(52651) const valid = (version, options) => { const v = parse(version, options) return v ? v.version : null } module.exports = valid /***/ }), /***/ 18938: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // just pre-load all the stuff that index.js lazily exports const internalRe = __webpack_require__(42262) const constants = __webpack_require__(10172) const SemVer = __webpack_require__(68039) const identifiers = __webpack_require__(41248) const parse = __webpack_require__(52651) const valid = __webpack_require__(57427) const clean = __webpack_require__(72493) const inc = __webpack_require__(95714) const diff = __webpack_require__(49078) const major = __webpack_require__(14678) const minor = __webpack_require__(63255) const patch = __webpack_require__(47940) const prerelease = __webpack_require__(51257) const compare = __webpack_require__(63370) const rcompare = __webpack_require__(17920) const compareLoose = __webpack_require__(49055) const compareBuild = __webpack_require__(24352) const sort = __webpack_require__(83410) const rsort = __webpack_require__(1861) const gt = __webpack_require__(79072) const lt = __webpack_require__(81098) const eq = __webpack_require__(32396) const neq = __webpack_require__(17165) const gte = __webpack_require__(30840) const lte = __webpack_require__(68276) const cmp = __webpack_require__(32986) const coerce = __webpack_require__(18736) const Comparator = __webpack_require__(99767) const Range = __webpack_require__(45859) const satisfies = __webpack_require__(25343) const toComparators = __webpack_require__(29138) const maxSatisfying = __webpack_require__(7799) const minSatisfying = __webpack_require__(58927) const minVersion = __webpack_require__(43682) const validRange = __webpack_require__(15312) const outside = __webpack_require__(95238) const gtr = __webpack_require__(48033) const ltr = __webpack_require__(38653) const intersects = __webpack_require__(93452) const simplifyRange = __webpack_require__(12571) const subset = __webpack_require__(76293) module.exports = { parse, valid, clean, inc, diff, major, minor, patch, prerelease, compare, rcompare, compareLoose, compareBuild, sort, rsort, gt, lt, eq, neq, gte, lte, cmp, coerce, Comparator, Range, satisfies, toComparators, maxSatisfying, minSatisfying, minVersion, validRange, outside, gtr, ltr, intersects, simplifyRange, subset, SemVer, re: internalRe.re, src: internalRe.src, tokens: internalRe.t, SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, RELEASE_TYPES: constants.RELEASE_TYPES, compareIdentifiers: identifiers.compareIdentifiers, rcompareIdentifiers: identifiers.rcompareIdentifiers, } /***/ }), /***/ 10172: /***/ ((module) => { // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. const SEMVER_SPEC_VERSION = '2.0.0' const MAX_LENGTH = 256 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. const MAX_SAFE_COMPONENT_LENGTH = 16 // Max safe length for a build identifier. The max length minus 6 characters for // the shortest version with a build 0.0.0+BUILD. const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 const RELEASE_TYPES = [ 'major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease', ] module.exports = { MAX_LENGTH, MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_SAFE_INTEGER, RELEASE_TYPES, SEMVER_SPEC_VERSION, FLAG_INCLUDE_PRERELEASE: 0b001, FLAG_LOOSE: 0b010, } /***/ }), /***/ 93948: /***/ ((module) => { const debug = ( typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ) ? (...args) => console.error('SEMVER', ...args) : () => {} module.exports = debug /***/ }), /***/ 41248: /***/ ((module) => { const numeric = /^[0-9]+$/ const compareIdentifiers = (a, b) => { const anum = numeric.test(a) const bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) module.exports = { compareIdentifiers, rcompareIdentifiers, } /***/ }), /***/ 60920: /***/ ((module) => { // parse out just the options we care about const looseOption = Object.freeze({ loose: true }) const emptyOpts = Object.freeze({ }) const parseOptions = options => { if (!options) { return emptyOpts } if (typeof options !== 'object') { return looseOption } return options } module.exports = parseOptions /***/ }), /***/ 42262: /***/ ((module, exports, __webpack_require__) => { const { MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_LENGTH, } = __webpack_require__(10172) const debug = __webpack_require__(93948) exports = module.exports = {} // The actual regexps go on exports.re const re = exports.re = [] const safeRe = exports.safeRe = [] const src = exports.src = [] const t = exports.t = {} let R = 0 const LETTERDASHNUMBER = '[a-zA-Z0-9-]' // Replace some greedy regex tokens to prevent regex dos issues. These regex are // used internally via the safeRe object since all inputs in this library get // normalized first to trim and collapse all extra whitespace. The original // regexes are exported for userland consumption and lower level usage. A // future breaking change could export the safer regex only with a note that // all input should have extra whitespace removed. const safeRegexReplacements = [ ['\\s', 1], ['\\d', MAX_LENGTH], [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], ] const makeSafeRegex = (value) => { for (const [token, max] of safeRegexReplacements) { value = value .split(`${token}*`).join(`${token}{0,${max}}`) .split(`${token}+`).join(`${token}{1,${max}}`) } return value } const createToken = (name, value, isGlobal) => { const safe = makeSafeRegex(value) const index = R++ debug(name, index, value) t[name] = index src[index] = value re[index] = new RegExp(value, isGlobal ? 'g' : undefined) safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) } // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') createToken('NUMERICIDENTIFIERLOOSE', '\\d+') // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) // ## Main Version // Three dot-separated numeric identifiers. createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`) createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] }|${src[t.NONNUMERICIDENTIFIER]})`) createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] }|${src[t.NONNUMERICIDENTIFIER]})`) // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] }(?:\\.${src[t.BUILDIDENTIFIER]})*))`) // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. createToken('FULLPLAIN', `v?${src[t.MAINVERSION] }${src[t.PRERELEASE]}?${ src[t.BUILD]}?`) createToken('FULL', `^${src[t.FULLPLAIN]}$`) // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] }${src[t.PRERELEASELOOSE]}?${ src[t.BUILD]}?`) createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) createToken('GTLT', '((?:<|>)?=?)') // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) // Coercion. // Extract anything that could conceivably be a part of a valid semver createToken('COERCE', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:$|[^\\d])`) createToken('COERCERTL', src[t.COERCE], true) // Tilde ranges. // Meaning is "reasonably at or greater than" createToken('LONETILDE', '(?:~>?)') createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) exports.tildeTrimReplace = '$1~' createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) // Caret ranges. // Meaning is "at least and backwards compatible with" createToken('LONECARET', '(?:\\^)') createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) exports.caretTrimReplace = '$1^' createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) // A simple gt/lt/eq thing, or just "" to indicate "any version" createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) exports.comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`) createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`) // Star ranges basically just allow anything at all. createToken('STAR', '(<|>)?=?\\s*\\*') // >=0.0.0 is like a star createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') /***/ }), /***/ 48033: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Determine if version is greater than all the versions possible in the range. const outside = __webpack_require__(95238) const gtr = (version, range, options) => outside(version, range, '>', options) module.exports = gtr /***/ }), /***/ 93452: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(45859) const intersects = (r1, r2, options) => { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2, options) } module.exports = intersects /***/ }), /***/ 38653: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const outside = __webpack_require__(95238) // Determine if version is less than all the versions possible in the range const ltr = (version, range, options) => outside(version, range, '<', options) module.exports = ltr /***/ }), /***/ 7799: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(68039) const Range = __webpack_require__(45859) const maxSatisfying = (versions, range, options) => { let max = null let maxSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } module.exports = maxSatisfying /***/ }), /***/ 58927: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(68039) const Range = __webpack_require__(45859) const minSatisfying = (versions, range, options) => { let min = null let minSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } module.exports = minSatisfying /***/ }), /***/ 43682: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(68039) const Range = __webpack_require__(45859) const gt = __webpack_require__(79072) const minVersion = (range, loose) => { range = new Range(range, loose) let minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let setMin = null comparators.forEach((comparator) => { // Clone to avoid manipulating the comparator's semver object. const compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!setMin || gt(compver, setMin)) { setMin = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error(`Unexpected operation: ${comparator.operator}`) } }) if (setMin && (!minver || gt(minver, setMin))) { minver = setMin } } if (minver && range.test(minver)) { return minver } return null } module.exports = minVersion /***/ }), /***/ 95238: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(68039) const Comparator = __webpack_require__(99767) const { ANY } = Comparator const Range = __webpack_require__(45859) const satisfies = __webpack_require__(25343) const gt = __webpack_require__(79072) const lt = __webpack_require__(81098) const lte = __webpack_require__(68276) const gte = __webpack_require__(30840) const outside = (version, range, hilo, options) => { version = new SemVer(version, options) range = new Range(range, options) let gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisfies the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let high = null let low = null comparators.forEach((comparator) => { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } module.exports = outside /***/ }), /***/ 12571: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // given a set of versions and a range, create a "simplified" range // that includes the same versions that the original range does // If the original range is shorter than the simplified one, return that. const satisfies = __webpack_require__(25343) const compare = __webpack_require__(63370) module.exports = (versions, range, options) => { const set = [] let first = null let prev = null const v = versions.sort((a, b) => compare(a, b, options)) for (const version of v) { const included = satisfies(version, range, options) if (included) { prev = version if (!first) { first = version } } else { if (prev) { set.push([first, prev]) } prev = null first = null } } if (first) { set.push([first, null]) } const ranges = [] for (const [min, max] of set) { if (min === max) { ranges.push(min) } else if (!max && min === v[0]) { ranges.push('*') } else if (!max) { ranges.push(`>=${min}`) } else if (min === v[0]) { ranges.push(`<=${max}`) } else { ranges.push(`${min} - ${max}`) } } const simplified = ranges.join(' || ') const original = typeof range.raw === 'string' ? range.raw : String(range) return simplified.length < original.length ? simplified : range } /***/ }), /***/ 76293: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(45859) const Comparator = __webpack_require__(99767) const { ANY } = Comparator const satisfies = __webpack_require__(25343) const compare = __webpack_require__(63370) // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: // - Every simple range `r1, r2, ...` is a null set, OR // - Every simple range `r1, r2, ...` which is not a null set is a subset of // some `R1, R2, ...` // // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: // - If c is only the ANY comparator // - If C is only the ANY comparator, return true // - Else if in prerelease mode, return false // - else replace c with `[>=0.0.0]` // - If C is only the ANY comparator // - if in prerelease mode, return true // - else replace C with `[>=0.0.0]` // - Let EQ be the set of = comparators in c // - If EQ is more than one, return true (null set) // - Let GT be the highest > or >= comparator in c // - Let LT be the lowest < or <= comparator in c // - If GT and LT, and GT.semver > LT.semver, return true (null set) // - If any C is a = range, and GT or LT are set, return false // - If EQ // - If GT, and EQ does not satisfy GT, return true (null set) // - If LT, and EQ does not satisfy LT, return true (null set) // - If EQ satisfies every C, return true // - Else return false // - If GT // - If GT.semver is lower than any > or >= comp in C, return false // - If GT is >=, and GT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the GT.semver tuple, return false // - If LT // - If LT.semver is greater than any < or <= comp in C, return false // - If LT is <=, and LT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the LT.semver tuple, return false // - Else return true const subset = (sub, dom, options = {}) => { if (sub === dom) { return true } sub = new Range(sub, options) dom = new Range(dom, options) let sawNonNull = false OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { const isSub = simpleSubset(simpleSub, simpleDom, options) sawNonNull = sawNonNull || isSub !== null if (isSub) { continue OUTER } } // the null set is a subset of everything, but null simple ranges in // a complex range should be ignored. so if we saw a non-null range, // then we know this isn't a subset, but if EVERY simple range was null, // then it is a subset. if (sawNonNull) { return false } } return true } const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] const minimumVersion = [new Comparator('>=0.0.0')] const simpleSubset = (sub, dom, options) => { if (sub === dom) { return true } if (sub.length === 1 && sub[0].semver === ANY) { if (dom.length === 1 && dom[0].semver === ANY) { return true } else if (options.includePrerelease) { sub = minimumVersionWithPreRelease } else { sub = minimumVersion } } if (dom.length === 1 && dom[0].semver === ANY) { if (options.includePrerelease) { return true } else { dom = minimumVersion } } const eqSet = new Set() let gt, lt for (const c of sub) { if (c.operator === '>' || c.operator === '>=') { gt = higherGT(gt, c, options) } else if (c.operator === '<' || c.operator === '<=') { lt = lowerLT(lt, c, options) } else { eqSet.add(c.semver) } } if (eqSet.size > 1) { return null } let gtltComp if (gt && lt) { gtltComp = compare(gt.semver, lt.semver, options) if (gtltComp > 0) { return null } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { return null } } // will iterate one or zero times for (const eq of eqSet) { if (gt && !satisfies(eq, String(gt), options)) { return null } if (lt && !satisfies(eq, String(lt), options)) { return null } for (const c of dom) { if (!satisfies(eq, String(c), options)) { return false } } return true } let higher, lower let hasDomLT, hasDomGT // if the subset has a prerelease, we need a comparator in the superset // with the same tuple and a prerelease, or it's not a subset let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false // exception: <1.2.3-0 is the same as <1.2.3 if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { needDomLTPre = false } for (const c of dom) { hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' if (gt) { if (needDomGTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { needDomGTPre = false } } if (c.operator === '>' || c.operator === '>=') { higher = higherGT(gt, c, options) if (higher === c && higher !== gt) { return false } } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { return false } } if (lt) { if (needDomLTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { needDomLTPre = false } } if (c.operator === '<' || c.operator === '<=') { lower = lowerLT(lt, c, options) if (lower === c && lower !== lt) { return false } } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { return false } } if (!c.operator && (lt || gt) && gtltComp !== 0) { return false } } // if there was a < or >, and nothing in the dom, then must be false // UNLESS it was limited by another range in the other direction. // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 if (gt && hasDomLT && !lt && gtltComp !== 0) { return false } if (lt && hasDomGT && !gt && gtltComp !== 0) { return false } // we needed a prerelease range in a specific tuple, but didn't get one // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, // because it includes prereleases in the 1.2.3 tuple if (needDomGTPre || needDomLTPre) { return false } return true } // >=1.2.3 is lower than >1.2.3 const higherGT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp > 0 ? a : comp < 0 ? b : b.operator === '>' && a.operator === '>=' ? b : a } // <=1.2.3 is higher than <1.2.3 const lowerLT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp < 0 ? a : comp > 0 ? b : b.operator === '<' && a.operator === '<=' ? b : a } module.exports = subset /***/ }), /***/ 29138: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(45859) // Mostly just for testing and legacy API reasons const toComparators = (range, options) => new Range(range, options).set .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) module.exports = toComparators /***/ }), /***/ 15312: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(45859) const validRange = (range, options) => { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } module.exports = validRange /***/ }), /***/ 32946: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const os = __webpack_require__(22037); const tty = __webpack_require__(76224); const hasFlag = __webpack_require__(25234); const {env} = process; let forceColor; if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false') || hasFlag('color=never')) { forceColor = 0; } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { forceColor = 1; } if ('FORCE_COLOR' in env) { if (env.FORCE_COLOR === 'true') { forceColor = 1; } else if (env.FORCE_COLOR === 'false') { forceColor = 0; } else { forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); } } function translateLevel(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function supportsColor(haveStream, streamIsTTY) { if (forceColor === 0) { return 0; } if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { return 3; } if (hasFlag('color=256')) { return 2; } if (haveStream && !streamIsTTY && forceColor === undefined) { return 0; } const min = forceColor || 0; if (env.TERM === 'dumb') { return min; } if (process.platform === 'win32') { // Windows 10 build 10586 is the first Windows release that supports 256 colors. // Windows 10 build 14931 is the first release that supports 16m/TrueColor. const osRelease = os.release().split('.'); if ( Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586 ) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ('CI' in env) { if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { return 1; } return min; } if ('TEAMCITY_VERSION' in env) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; } if (env.COLORTERM === 'truecolor') { return 3; } if ('TERM_PROGRAM' in env) { const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); switch (env.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': return 2; // No default } } if (/-256(color)?$/i.test(env.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { return 1; } if ('COLORTERM' in env) { return 1; } return min; } function getSupportLevel(stream) { const level = supportsColor(stream, stream && stream.isTTY); return translateLevel(level); } module.exports = { supportsColor: getSupportLevel, stdout: translateLevel(supportsColor(true, tty.isatty(1))), stderr: translateLevel(supportsColor(true, tty.isatty(2))) }; /***/ }), /***/ 84688: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /*! * Tmp * * Copyright (c) 2011-2017 KARASZI Istvan * * MIT Licensed */ /* * Module dependencies. */ const fs = __webpack_require__(57147); const os = __webpack_require__(22037); const path = __webpack_require__(71017); const crypto = __webpack_require__(6113); const _c = { fs: fs.constants, os: os.constants }; const rimraf = __webpack_require__(53200); /* * The working inner variables. */ const // the random characters to choose from RANDOM_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', TEMPLATE_PATTERN = /XXXXXX/, DEFAULT_TRIES = 3, CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR), // constants are off on the windows platform and will not match the actual errno codes IS_WIN32 = os.platform() === 'win32', EBADF = _c.EBADF || _c.os.errno.EBADF, ENOENT = _c.ENOENT || _c.os.errno.ENOENT, DIR_MODE = 0o700 /* 448 */, FILE_MODE = 0o600 /* 384 */, EXIT = 'exit', // this will hold the objects need to be removed on exit _removeObjects = [], // API change in fs.rmdirSync leads to error when passing in a second parameter, e.g. the callback FN_RMDIR_SYNC = fs.rmdirSync.bind(fs), FN_RIMRAF_SYNC = rimraf.sync; let _gracefulCleanup = false; /** * Gets a temporary file name. * * @param {(Options|tmpNameCallback)} options options or callback * @param {?tmpNameCallback} callback the callback function */ function tmpName(options, callback) { const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; try { _assertAndSanitizeOptions(opts); } catch (err) { return cb(err); } let tries = opts.tries; (function _getUniqueName() { try { const name = _generateTmpName(opts); // check whether the path exists then retry if needed fs.stat(name, function (err) { /* istanbul ignore else */ if (!err) { /* istanbul ignore else */ if (tries-- > 0) return _getUniqueName(); return cb(new Error('Could not get a unique tmp filename, max tries reached ' + name)); } cb(null, name); }); } catch (err) { cb(err); } }()); } /** * Synchronous version of tmpName. * * @param {Object} options * @returns {string} the generated random name * @throws {Error} if the options are invalid or could not generate a filename */ function tmpNameSync(options) { const args = _parseArguments(options), opts = args[0]; _assertAndSanitizeOptions(opts); let tries = opts.tries; do { const name = _generateTmpName(opts); try { fs.statSync(name); } catch (e) { return name; } } while (tries-- > 0); throw new Error('Could not get a unique tmp filename, max tries reached'); } /** * Creates and opens a temporary file. * * @param {(Options|null|undefined|fileCallback)} options the config options or the callback function or null or undefined * @param {?fileCallback} callback */ function file(options, callback) { const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; // gets a temporary filename tmpName(opts, function _tmpNameCreated(err, name) { /* istanbul ignore else */ if (err) return cb(err); // create and open the file fs.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err, fd) { /* istanbu ignore else */ if (err) return cb(err); if (opts.discardDescriptor) { return fs.close(fd, function _discardCallback(possibleErr) { // the chance of getting an error on close here is rather low and might occur in the most edgiest cases only return cb(possibleErr, name, undefined, _prepareTmpFileRemoveCallback(name, -1, opts, false)); }); } else { // detachDescriptor passes the descriptor whereas discardDescriptor closes it, either way, we no longer care // about the descriptor const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; cb(null, name, fd, _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, false)); } }); }); } /** * Synchronous version of file. * * @param {Options} options * @returns {FileSyncObject} object consists of name, fd and removeCallback * @throws {Error} if cannot create a file */ function fileSync(options) { const args = _parseArguments(options), opts = args[0]; const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; const name = tmpNameSync(opts); var fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); /* istanbul ignore else */ if (opts.discardDescriptor) { fs.closeSync(fd); fd = undefined; } return { name: name, fd: fd, removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, true) }; } /** * Creates a temporary directory. * * @param {(Options|dirCallback)} options the options or the callback function * @param {?dirCallback} callback */ function dir(options, callback) { const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; // gets a temporary filename tmpName(opts, function _tmpNameCreated(err, name) { /* istanbul ignore else */ if (err) return cb(err); // create the directory fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err) { /* istanbul ignore else */ if (err) return cb(err); cb(null, name, _prepareTmpDirRemoveCallback(name, opts, false)); }); }); } /** * Synchronous version of dir. * * @param {Options} options * @returns {DirSyncObject} object consists of name and removeCallback * @throws {Error} if it cannot create a directory */ function dirSync(options) { const args = _parseArguments(options), opts = args[0]; const name = tmpNameSync(opts); fs.mkdirSync(name, opts.mode || DIR_MODE); return { name: name, removeCallback: _prepareTmpDirRemoveCallback(name, opts, true) }; } /** * Removes files asynchronously. * * @param {Object} fdPath * @param {Function} next * @private */ function _removeFileAsync(fdPath, next) { const _handler = function (err) { if (err && !_isENOENT(err)) { // reraise any unanticipated error return next(err); } next(); }; if (0 <= fdPath[0]) fs.close(fdPath[0], function () { fs.unlink(fdPath[1], _handler); }); else fs.unlink(fdPath[1], _handler); } /** * Removes files synchronously. * * @param {Object} fdPath * @private */ function _removeFileSync(fdPath) { let rethrownException = null; try { if (0 <= fdPath[0]) fs.closeSync(fdPath[0]); } catch (e) { // reraise any unanticipated error if (!_isEBADF(e) && !_isENOENT(e)) throw e; } finally { try { fs.unlinkSync(fdPath[1]); } catch (e) { // reraise any unanticipated error if (!_isENOENT(e)) rethrownException = e; } } if (rethrownException !== null) { throw rethrownException; } } /** * Prepares the callback for removal of the temporary file. * * Returns either a sync callback or a async callback depending on whether * fileSync or file was called, which is expressed by the sync parameter. * * @param {string} name the path of the file * @param {number} fd file descriptor * @param {Object} opts * @param {boolean} sync * @returns {fileCallback | fileCallbackSync} * @private */ function _prepareTmpFileRemoveCallback(name, fd, opts, sync) { const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name], sync); const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], sync, removeCallbackSync); if (!opts.keep) _removeObjects.unshift(removeCallbackSync); return sync ? removeCallbackSync : removeCallback; } /** * Prepares the callback for removal of the temporary directory. * * Returns either a sync callback or a async callback depending on whether * tmpFileSync or tmpFile was called, which is expressed by the sync parameter. * * @param {string} name * @param {Object} opts * @param {boolean} sync * @returns {Function} the callback * @private */ function _prepareTmpDirRemoveCallback(name, opts, sync) { const removeFunction = opts.unsafeCleanup ? rimraf : fs.rmdir.bind(fs); const removeFunctionSync = opts.unsafeCleanup ? FN_RIMRAF_SYNC : FN_RMDIR_SYNC; const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name, sync); const removeCallback = _prepareRemoveCallback(removeFunction, name, sync, removeCallbackSync); if (!opts.keep) _removeObjects.unshift(removeCallbackSync); return sync ? removeCallbackSync : removeCallback; } /** * Creates a guarded function wrapping the removeFunction call. * * The cleanup callback is save to be called multiple times. * Subsequent invocations will be ignored. * * @param {Function} removeFunction * @param {string} fileOrDirName * @param {boolean} sync * @param {cleanupCallbackSync?} cleanupCallbackSync * @returns {cleanupCallback | cleanupCallbackSync} * @private */ function _prepareRemoveCallback(removeFunction, fileOrDirName, sync, cleanupCallbackSync) { let called = false; // if sync is true, the next parameter will be ignored return function _cleanupCallback(next) { /* istanbul ignore else */ if (!called) { // remove cleanupCallback from cache const toRemove = cleanupCallbackSync || _cleanupCallback; const index = _removeObjects.indexOf(toRemove); /* istanbul ignore else */ if (index >= 0) _removeObjects.splice(index, 1); called = true; if (sync || removeFunction === FN_RMDIR_SYNC || removeFunction === FN_RIMRAF_SYNC) { return removeFunction(fileOrDirName); } else { return removeFunction(fileOrDirName, next || function() {}); } } }; } /** * The garbage collector. * * @private */ function _garbageCollector() { /* istanbul ignore else */ if (!_gracefulCleanup) return; // the function being called removes itself from _removeObjects, // loop until _removeObjects is empty while (_removeObjects.length) { try { _removeObjects[0](); } catch (e) { // already removed? } } } /** * Random name generator based on crypto. * Adapted from http://blog.tompawlak.org/how-to-generate-random-values-nodejs-javascript * * @param {number} howMany * @returns {string} the generated random name * @private */ function _randomChars(howMany) { let value = [], rnd = null; // make sure that we do not fail because we ran out of entropy try { rnd = crypto.randomBytes(howMany); } catch (e) { rnd = crypto.pseudoRandomBytes(howMany); } for (var i = 0; i < howMany; i++) { value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]); } return value.join(''); } /** * Helper which determines whether a string s is blank, that is undefined, or empty or null. * * @private * @param {string} s * @returns {Boolean} true whether the string s is blank, false otherwise */ function _isBlank(s) { return s === null || _isUndefined(s) || !s.trim(); } /** * Checks whether the `obj` parameter is defined or not. * * @param {Object} obj * @returns {boolean} true if the object is undefined * @private */ function _isUndefined(obj) { return typeof obj === 'undefined'; } /** * Parses the function arguments. * * This function helps to have optional arguments. * * @param {(Options|null|undefined|Function)} options * @param {?Function} callback * @returns {Array} parsed arguments * @private */ function _parseArguments(options, callback) { /* istanbul ignore else */ if (typeof options === 'function') { return [{}, options]; } /* istanbul ignore else */ if (_isUndefined(options)) { return [{}, callback]; } // copy options so we do not leak the changes we make internally const actualOptions = {}; for (const key of Object.getOwnPropertyNames(options)) { actualOptions[key] = options[key]; } return [actualOptions, callback]; } /** * Generates a new temporary name. * * @param {Object} opts * @returns {string} the new random name according to opts * @private */ function _generateTmpName(opts) { const tmpDir = opts.tmpdir; /* istanbul ignore else */ if (!_isUndefined(opts.name)) return path.join(tmpDir, opts.dir, opts.name); /* istanbul ignore else */ if (!_isUndefined(opts.template)) return path.join(tmpDir, opts.dir, opts.template).replace(TEMPLATE_PATTERN, _randomChars(6)); // prefix and postfix const name = [ opts.prefix ? opts.prefix : 'tmp', '-', process.pid, '-', _randomChars(12), opts.postfix ? '-' + opts.postfix : '' ].join(''); return path.join(tmpDir, opts.dir, name); } /** * Asserts whether the specified options are valid, also sanitizes options and provides sane defaults for missing * options. * * @param {Options} options * @private */ function _assertAndSanitizeOptions(options) { options.tmpdir = _getTmpDir(options); const tmpDir = options.tmpdir; /* istanbul ignore else */ if (!_isUndefined(options.name)) _assertIsRelative(options.name, 'name', tmpDir); /* istanbul ignore else */ if (!_isUndefined(options.dir)) _assertIsRelative(options.dir, 'dir', tmpDir); /* istanbul ignore else */ if (!_isUndefined(options.template)) { _assertIsRelative(options.template, 'template', tmpDir); if (!options.template.match(TEMPLATE_PATTERN)) throw new Error(`Invalid template, found "${options.template}".`); } /* istanbul ignore else */ if (!_isUndefined(options.tries) && isNaN(options.tries) || options.tries < 0) throw new Error(`Invalid tries, found "${options.tries}".`); // if a name was specified we will try once options.tries = _isUndefined(options.name) ? options.tries || DEFAULT_TRIES : 1; options.keep = !!options.keep; options.detachDescriptor = !!options.detachDescriptor; options.discardDescriptor = !!options.discardDescriptor; options.unsafeCleanup = !!options.unsafeCleanup; // sanitize dir, also keep (multiple) blanks if the user, purportedly sane, requests us to options.dir = _isUndefined(options.dir) ? '' : path.relative(tmpDir, _resolvePath(options.dir, tmpDir)); options.template = _isUndefined(options.template) ? undefined : path.relative(tmpDir, _resolvePath(options.template, tmpDir)); // sanitize further if template is relative to options.dir options.template = _isBlank(options.template) ? undefined : path.relative(options.dir, options.template); // for completeness' sake only, also keep (multiple) blanks if the user, purportedly sane, requests us to options.name = _isUndefined(options.name) ? undefined : _sanitizeName(options.name); options.prefix = _isUndefined(options.prefix) ? '' : options.prefix; options.postfix = _isUndefined(options.postfix) ? '' : options.postfix; } /** * Resolve the specified path name in respect to tmpDir. * * The specified name might include relative path components, e.g. ../ * so we need to resolve in order to be sure that is is located inside tmpDir * * @param name * @param tmpDir * @returns {string} * @private */ function _resolvePath(name, tmpDir) { const sanitizedName = _sanitizeName(name); if (sanitizedName.startsWith(tmpDir)) { return path.resolve(sanitizedName); } else { return path.resolve(path.join(tmpDir, sanitizedName)); } } /** * Sanitize the specified path name by removing all quote characters. * * @param name * @returns {string} * @private */ function _sanitizeName(name) { if (_isBlank(name)) { return name; } return name.replace(/["']/g, ''); } /** * Asserts whether specified name is relative to the specified tmpDir. * * @param {string} name * @param {string} option * @param {string} tmpDir * @throws {Error} * @private */ function _assertIsRelative(name, option, tmpDir) { if (option === 'name') { // assert that name is not absolute and does not contain a path if (path.isAbsolute(name)) throw new Error(`${option} option must not contain an absolute path, found "${name}".`); // must not fail on valid . or .. or similar such constructs let basename = path.basename(name); if (basename === '..' || basename === '.' || basename !== name) throw new Error(`${option} option must not contain a path, found "${name}".`); } else { // if (option === 'dir' || option === 'template') { // assert that dir or template are relative to tmpDir if (path.isAbsolute(name) && !name.startsWith(tmpDir)) { throw new Error(`${option} option must be relative to "${tmpDir}", found "${name}".`); } let resolvedPath = _resolvePath(name, tmpDir); if (!resolvedPath.startsWith(tmpDir)) throw new Error(`${option} option must be relative to "${tmpDir}", found "${resolvedPath}".`); } } /** * Helper for testing against EBADF to compensate changes made to Node 7.x under Windows. * * @private */ function _isEBADF(error) { return _isExpectedError(error, -EBADF, 'EBADF'); } /** * Helper for testing against ENOENT to compensate changes made to Node 7.x under Windows. * * @private */ function _isENOENT(error) { return _isExpectedError(error, -ENOENT, 'ENOENT'); } /** * Helper to determine whether the expected error code matches the actual code and errno, * which will differ between the supported node versions. * * - Node >= 7.0: * error.code {string} * error.errno {number} any numerical value will be negated * * CAVEAT * * On windows, the errno for EBADF is -4083 but os.constants.errno.EBADF is different and we must assume that ENOENT * is no different here. * * @param {SystemError} error * @param {number} errno * @param {string} code * @private */ function _isExpectedError(error, errno, code) { return IS_WIN32 ? error.code === code : error.code === code && error.errno === errno; } /** * Sets the graceful cleanup. * * If graceful cleanup is set, tmp will remove all controlled temporary objects on process exit, otherwise the * temporary objects will remain in place, waiting to be cleaned up on system restart or otherwise scheduled temporary * object removals. */ function setGracefulCleanup() { _gracefulCleanup = true; } /** * Returns the currently configured tmp dir from os.tmpdir(). * * @private * @param {?Options} options * @returns {string} the currently configured tmp dir */ function _getTmpDir(options) { return path.resolve(_sanitizeName(options && options.tmpdir || os.tmpdir())); } // Install process exit listener process.addListener(EXIT, _garbageCollector); /** * Configuration options. * * @typedef {Object} Options * @property {?boolean} keep the temporary object (file or dir) will not be garbage collected * @property {?number} tries the number of tries before give up the name generation * @property (?int) mode the access mode, defaults are 0o700 for directories and 0o600 for files * @property {?string} template the "mkstemp" like filename template * @property {?string} name fixed name relative to tmpdir or the specified dir option * @property {?string} dir tmp directory relative to the root tmp directory in use * @property {?string} prefix prefix for the generated name * @property {?string} postfix postfix for the generated name * @property {?string} tmpdir the root tmp directory which overrides the os tmpdir * @property {?boolean} unsafeCleanup recursively removes the created temporary directory, even when it's not empty * @property {?boolean} detachDescriptor detaches the file descriptor, caller is responsible for closing the file, tmp will no longer try closing the file during garbage collection * @property {?boolean} discardDescriptor discards the file descriptor (closes file, fd is -1), tmp will no longer try closing the file during garbage collection */ /** * @typedef {Object} FileSyncObject * @property {string} name the name of the file * @property {string} fd the file descriptor or -1 if the fd has been discarded * @property {fileCallback} removeCallback the callback function to remove the file */ /** * @typedef {Object} DirSyncObject * @property {string} name the name of the directory * @property {fileCallback} removeCallback the callback function to remove the directory */ /** * @callback tmpNameCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name */ /** * @callback fileCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {number} fd the file descriptor or -1 if the fd had been discarded * @param {cleanupCallback} fn the cleanup callback function */ /** * @callback fileCallbackSync * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {number} fd the file descriptor or -1 if the fd had been discarded * @param {cleanupCallbackSync} fn the cleanup callback function */ /** * @callback dirCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {cleanupCallback} fn the cleanup callback function */ /** * @callback dirCallbackSync * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {cleanupCallbackSync} fn the cleanup callback function */ /** * Removes the temporary created file or directory. * * @callback cleanupCallback * @param {simpleCallback} [next] function to call whenever the tmp object needs to be removed */ /** * Removes the temporary created file or directory. * * @callback cleanupCallbackSync */ /** * Callback function for function composition. * @see {@link https://github.com/raszi/node-tmp/issues/57|raszi/node-tmp#57} * * @callback simpleCallback */ // exporting all the needed methods // evaluate _getTmpDir() lazily, mainly for simplifying testing but it also will // allow users to reconfigure the temporary directory Object.defineProperty(module.exports, "tmpdir", ({ enumerable: true, configurable: false, get: function () { return _getTmpDir(); } })); module.exports.dir = dir; module.exports.dirSync = dirSync; module.exports.file = file; module.exports.fileSync = fileSync; module.exports.tmpName = tmpName; module.exports.tmpNameSync = tmpNameSync; module.exports.setGracefulCleanup = setGracefulCleanup; /***/ }), /***/ 80242: /***/ ((module) => { "use strict"; module.exports = function (Yallist) { Yallist.prototype[Symbol.iterator] = function* () { for (let walker = this.head; walker; walker = walker.next) { yield walker.value } } } /***/ }), /***/ 92191: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = Yallist Yallist.Node = Node Yallist.create = Yallist function Yallist (list) { var self = this if (!(self instanceof Yallist)) { self = new Yallist() } self.tail = null self.head = null self.length = 0 if (list && typeof list.forEach === 'function') { list.forEach(function (item) { self.push(item) }) } else if (arguments.length > 0) { for (var i = 0, l = arguments.length; i < l; i++) { self.push(arguments[i]) } } return self } Yallist.prototype.removeNode = function (node) { if (node.list !== this) { throw new Error('removing node which does not belong to this list') } var next = node.next var prev = node.prev if (next) { next.prev = prev } if (prev) { prev.next = next } if (node === this.head) { this.head = next } if (node === this.tail) { this.tail = prev } node.list.length-- node.next = null node.prev = null node.list = null return next } Yallist.prototype.unshiftNode = function (node) { if (node === this.head) { return } if (node.list) { node.list.removeNode(node) } var head = this.head node.list = this node.next = head if (head) { head.prev = node } this.head = node if (!this.tail) { this.tail = node } this.length++ } Yallist.prototype.pushNode = function (node) { if (node === this.tail) { return } if (node.list) { node.list.removeNode(node) } var tail = this.tail node.list = this node.prev = tail if (tail) { tail.next = node } this.tail = node if (!this.head) { this.head = node } this.length++ } Yallist.prototype.push = function () { for (var i = 0, l = arguments.length; i < l; i++) { push(this, arguments[i]) } return this.length } Yallist.prototype.unshift = function () { for (var i = 0, l = arguments.length; i < l; i++) { unshift(this, arguments[i]) } return this.length } Yallist.prototype.pop = function () { if (!this.tail) { return undefined } var res = this.tail.value this.tail = this.tail.prev if (this.tail) { this.tail.next = null } else { this.head = null } this.length-- return res } Yallist.prototype.shift = function () { if (!this.head) { return undefined } var res = this.head.value this.head = this.head.next if (this.head) { this.head.prev = null } else { this.tail = null } this.length-- return res } Yallist.prototype.forEach = function (fn, thisp) { thisp = thisp || this for (var walker = this.head, i = 0; walker !== null; i++) { fn.call(thisp, walker.value, i, this) walker = walker.next } } Yallist.prototype.forEachReverse = function (fn, thisp) { thisp = thisp || this for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { fn.call(thisp, walker.value, i, this) walker = walker.prev } } Yallist.prototype.get = function (n) { for (var i = 0, walker = this.head; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.next } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.getReverse = function (n) { for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.prev } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.map = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.head; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.next } return res } Yallist.prototype.mapReverse = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.tail; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.prev } return res } Yallist.prototype.reduce = function (fn, initial) { var acc var walker = this.head if (arguments.length > 1) { acc = initial } else if (this.head) { walker = this.head.next acc = this.head.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = 0; walker !== null; i++) { acc = fn(acc, walker.value, i) walker = walker.next } return acc } Yallist.prototype.reduceReverse = function (fn, initial) { var acc var walker = this.tail if (arguments.length > 1) { acc = initial } else if (this.tail) { walker = this.tail.prev acc = this.tail.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = this.length - 1; walker !== null; i--) { acc = fn(acc, walker.value, i) walker = walker.prev } return acc } Yallist.prototype.toArray = function () { var arr = new Array(this.length) for (var i = 0, walker = this.head; walker !== null; i++) { arr[i] = walker.value walker = walker.next } return arr } Yallist.prototype.toArrayReverse = function () { var arr = new Array(this.length) for (var i = 0, walker = this.tail; walker !== null; i++) { arr[i] = walker.value walker = walker.prev } return arr } Yallist.prototype.slice = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = 0, walker = this.head; walker !== null && i < from; i++) { walker = walker.next } for (; walker !== null && i < to; i++, walker = walker.next) { ret.push(walker.value) } return ret } Yallist.prototype.sliceReverse = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { walker = walker.prev } for (; walker !== null && i > from; i--, walker = walker.prev) { ret.push(walker.value) } return ret } Yallist.prototype.splice = function (start, deleteCount, ...nodes) { if (start > this.length) { start = this.length - 1 } if (start < 0) { start = this.length + start; } for (var i = 0, walker = this.head; walker !== null && i < start; i++) { walker = walker.next } var ret = [] for (var i = 0; walker && i < deleteCount; i++) { ret.push(walker.value) walker = this.removeNode(walker) } if (walker === null) { walker = this.tail } if (walker !== this.head && walker !== this.tail) { walker = walker.prev } for (var i = 0; i < nodes.length; i++) { walker = insert(this, walker, nodes[i]) } return ret; } Yallist.prototype.reverse = function () { var head = this.head var tail = this.tail for (var walker = head; walker !== null; walker = walker.prev) { var p = walker.prev walker.prev = walker.next walker.next = p } this.head = tail this.tail = head return this } function insert (self, node, value) { var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self) if (inserted.next === null) { self.tail = inserted } if (inserted.prev === null) { self.head = inserted } self.length++ return inserted } function push (self, item) { self.tail = new Node(item, self.tail, null, self) if (!self.head) { self.head = self.tail } self.length++ } function unshift (self, item) { self.head = new Node(item, null, self.head, self) if (!self.tail) { self.tail = self.head } self.length++ } function Node (value, prev, next, list) { if (!(this instanceof Node)) { return new Node(value, prev, next, list) } this.list = list this.value = value if (prev) { prev.next = this this.prev = prev } else { this.prev = null } if (next) { next.prev = this this.next = next } else { this.next = null } } try { // add if support for Symbol.iterator is present __webpack_require__(80242)(Yallist) } catch (er) {} /***/ }), /***/ 60390: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.encode = exports.parsePackageString = void 0; const debug = __webpack_require__(15158)('snyk:module'); const gitHost = __webpack_require__(19672); exports["default"] = parsePackageString; /** * Parses a string package id (name + optional version) to an object. * * This method used to be named `moduleToObject`. */ function parsePackageString(nameAndMaybeVersion, versionOrOptions, options) { if (!nameAndMaybeVersion) { throw new Error('requires string to parse into module'); } let version; if (versionOrOptions && !options && typeof versionOrOptions === 'object') { options = versionOrOptions; } else { version = versionOrOptions; } let str = nameAndMaybeVersion; // first, try the common case; there's no version, and it's a normal package name if (!version) { // foo, foo-bar, @foo/bar, com.example:test // none of these can be URLs, or versions const fastPath = /^(?:(?:[a-z-]+)|(?:@[a-z-]+\/[a-z-]+)|(?:[a-z-]+\.[.a-z-]+:[a-z-]+))$/; if (fastPath.test(str)) { return supported(str, { name: str, version: '*' }, options); } } if (version && str.lastIndexOf('@') < 1) { debug('appending version onto string'); str += '@' + version; } // first try with regular git urls const gitObject = looksLikeUrl(str); if (gitObject) { // then the string looks like a url, let's try to parse it return supported(str, fromGitObject(gitObject), options); } let parts = str.split('@'); if (str.indexOf('@') === 0) { // put the scoped package name back together parts = parts.slice(1); parts[0] = '@' + parts[0]; } // then as a backup, try pkg@giturl const maybeGitObject = parts[1] && looksLikeUrl(parts[1]); if (maybeGitObject) { // then the string looks like a url, let's try to parse it return supported(str, fromGitObject(maybeGitObject), options); } if (parts.length === 1) { // no version parts.push('*'); } const module = { name: parts[0], version: parts.slice(1).join('@'), }; return supported(str, module, options); } exports.parsePackageString = parsePackageString; // git host from URL function looksLikeUrl(str) { if (str.slice(-1) === '/') { // strip the trailing slash since we can't parse it properly anyway str = str.slice(0, -1); } if (str.toLowerCase().indexOf('://github.com/') !== -1 && str.indexOf('http') === 0) { // attempt to get better compat with our parser by stripping the github // and url parts // examples: // - https://github.com/Snyk/snyk/releases/tag/v1.14.2 // - https://github.com/Snyk/vulndb/tree/snapshots // - https://github.com/Snyk/snyk/commit/75477b18 const parts = str.replace(/https?:\/\/github.com\//, '').split('/'); str = parts.shift() + '/' + parts.shift(); if (parts.length) { str += '#' + parts.pop(); } } const obj = gitHost.fromUrl(str); return obj; } function fromGitObject(obj) { // debug('parsed from hosted-git-info'); /* istanbul ignore if */ if (!obj.project || !obj.user) { // this should never actually occur const error = new Error('not supported: failed to fully parse'); error.code = 501; throw error; } const module = { name: obj.project, version: obj.user + '/' + obj.project, }; if (obj.committish) { module.version += '#' + obj.committish; } return module; } function encode(name) { return name[0] + encodeURIComponent(name.slice(1)); } exports.encode = encode; function supported(str, module, options) { if (!options) { options = {}; } if (options.packageManager === 'maven') { if (str.indexOf(':') === -1) { throw new Error('invalid Maven package name: ' + str); } return module; } const protocolMatch = module.version.match(/^(https?:)|(git[:+])/i); if (protocolMatch || module.name.indexOf('://') !== -1) { // we don't support non-npm modules atm debug('not supported %s@%s (ext)', module.name, module.version); if (options.loose) { delete module.version; } else { debug('external module: ' + toString(module)); } } if (module.version === 'latest' || !module.version) { module.version = '*'; } debug('%s => { name: "%s", version: "%s" }', str, module.name, module.version); return module; } function toString(module) { return module.name + '@' + module.version; } //# sourceMappingURL=index.js.map /***/ }), /***/ 84479: /***/ ((module) => { "use strict"; var gitHosts = module.exports = { github: { // First two are insecure and generally shouldn't be used any more, but // they are still supported. 'protocols': [ 'git', 'http', 'git+ssh', 'git+https', 'ssh', 'https' ], 'domain': 'github.com', 'treepath': 'tree', 'filetemplate': 'https://{auth@}raw.githubusercontent.com/{user}/{project}/{committish}/{path}', 'bugstemplate': 'https://{domain}/{user}/{project}/issues', 'gittemplate': 'git://{auth@}{domain}/{user}/{project}.git{#committish}', 'tarballtemplate': 'https://codeload.{domain}/{user}/{project}/tar.gz/{committish}' }, bitbucket: { 'protocols': [ 'git+ssh', 'git+https', 'ssh', 'https' ], 'domain': 'bitbucket.org', 'treepath': 'src', 'tarballtemplate': 'https://{domain}/{user}/{project}/get/{committish}.tar.gz' }, gitlab: { 'protocols': [ 'git+ssh', 'git+https', 'ssh', 'https' ], 'domain': 'gitlab.com', 'treepath': 'tree', 'bugstemplate': 'https://{domain}/{user}/{project}/issues', 'httpstemplate': 'git+https://{auth@}{domain}/{user}/{projectPath}.git{#committish}', 'tarballtemplate': 'https://{domain}/{user}/{project}/repository/archive.tar.gz?ref={committish}', 'pathmatch': /^\/([^/]+)\/((?!.*(\/-\/|\/repository(\/[^/]+)?\/archive\.tar\.gz)).*?)(?:\.git|\/)?$/ }, gist: { 'protocols': [ 'git', 'git+ssh', 'git+https', 'ssh', 'https' ], 'domain': 'gist.github.com', 'pathmatch': /^[/](?:([^/]+)[/])?([a-z0-9]{7,})(?:[.]git)?$/, 'filetemplate': 'https://gist.githubusercontent.com/{user}/{project}/raw{/committish}/{path}', 'bugstemplate': 'https://{domain}/{project}', 'gittemplate': 'git://{domain}/{project}.git{#committish}', 'sshtemplate': 'git@{domain}:/{project}.git{#committish}', 'sshurltemplate': 'git+ssh://git@{domain}/{project}.git{#committish}', 'browsetemplate': 'https://{domain}/{project}{/committish}', 'browsefiletemplate': 'https://{domain}/{project}{/committish}{#path}', 'docstemplate': 'https://{domain}/{project}{/committish}', 'httpstemplate': 'git+https://{domain}/{project}.git{#committish}', 'shortcuttemplate': '{type}:{project}{#committish}', 'pathtemplate': '{project}{#committish}', 'tarballtemplate': 'https://codeload.github.com/gist/{project}/tar.gz/{committish}', 'hashformat': function (fragment) { return 'file-' + formatHashFragment(fragment) } } } var gitHostDefaults = { 'sshtemplate': 'git@{domain}:{user}/{project}.git{#committish}', 'sshurltemplate': 'git+ssh://git@{domain}/{user}/{project}.git{#committish}', 'browsetemplate': 'https://{domain}/{user}/{project}{/tree/committish}', 'browsefiletemplate': 'https://{domain}/{user}/{project}/{treepath}/{committish}/{path}{#fragment}', 'docstemplate': 'https://{domain}/{user}/{project}{/tree/committish}#readme', 'httpstemplate': 'git+https://{auth@}{domain}/{user}/{project}.git{#committish}', 'filetemplate': 'https://{domain}/{user}/{project}/raw/{committish}/{path}', 'shortcuttemplate': '{type}:{user}/{project}{#committish}', 'pathtemplate': '{user}/{project}{#committish}', 'pathmatch': /^[/]([^/]+)[/]([^/]+?)(?:[.]git|[/])?$/, 'hashformat': formatHashFragment } Object.keys(gitHosts).forEach(function (name) { Object.keys(gitHostDefaults).forEach(function (key) { if (gitHosts[name][key]) return gitHosts[name][key] = gitHostDefaults[key] }) gitHosts[name].protocols_re = RegExp('^(' + gitHosts[name].protocols.map(function (protocol) { return protocol.replace(/([\\+*{}()[\]$^|])/g, '\\$1') }).join('|') + '):$') }) function formatHashFragment (fragment) { return fragment.toLowerCase().replace(/^\W+|\/|\W+$/g, '').replace(/\W+/g, '-') } /***/ }), /***/ 11234: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var gitHosts = __webpack_require__(84479) /* eslint-disable node/no-deprecated-api */ // copy-pasta util._extend from node's source, to avoid pulling // the whole util module into peoples' webpack bundles. /* istanbul ignore next */ var extend = Object.assign || function _extend (target, source) { // Don't do anything if source isn't an object if (source === null || typeof source !== 'object') return target const keys = Object.keys(source) let i = keys.length while (i--) { target[keys[i]] = source[keys[i]] } return target } module.exports = GitHost function GitHost (type, user, auth, project, committish, defaultRepresentation, opts) { var gitHostInfo = this gitHostInfo.type = type Object.keys(gitHosts[type]).forEach(function (key) { gitHostInfo[key] = gitHosts[type][key] }) gitHostInfo.user = user gitHostInfo.auth = auth gitHostInfo.project = project gitHostInfo.committish = committish gitHostInfo.default = defaultRepresentation gitHostInfo.opts = opts || {} } GitHost.prototype.hash = function () { return this.committish ? '#' + this.committish : '' } GitHost.prototype._fill = function (template, opts) { if (!template) return var vars = extend({}, opts) vars.path = vars.path ? vars.path.replace(/^[/]+/g, '') : '' opts = extend(extend({}, this.opts), opts) var self = this Object.keys(this).forEach(function (key) { if (self[key] != null && vars[key] == null) vars[key] = self[key] }) var rawAuth = vars.auth var rawcommittish = vars.committish var rawFragment = vars.fragment var rawPath = vars.path var rawProject = vars.project Object.keys(vars).forEach(function (key) { var value = vars[key] if ((key === 'path' || key === 'project') && typeof value === 'string') { vars[key] = value.split('/').map(function (pathComponent) { return encodeURIComponent(pathComponent) }).join('/') } else if (key !== 'domain') { vars[key] = encodeURIComponent(value) } }) vars['auth@'] = rawAuth ? rawAuth + '@' : '' vars['#fragment'] = rawFragment ? '#' + this.hashformat(rawFragment) : '' vars.fragment = vars.fragment ? vars.fragment : '' vars['#path'] = rawPath ? '#' + this.hashformat(rawPath) : '' vars['/path'] = vars.path ? '/' + vars.path : '' vars.projectPath = rawProject.split('/').map(encodeURIComponent).join('/') if (opts.noCommittish) { vars['#committish'] = '' vars['/tree/committish'] = '' vars['/committish'] = '' vars.committish = '' } else { vars['#committish'] = rawcommittish ? '#' + rawcommittish : '' vars['/tree/committish'] = vars.committish ? '/' + vars.treepath + '/' + vars.committish : '' vars['/committish'] = vars.committish ? '/' + vars.committish : '' vars.committish = vars.committish || 'master' } var res = template Object.keys(vars).forEach(function (key) { res = res.replace(new RegExp('[{]' + key + '[}]', 'g'), vars[key]) }) if (opts.noGitPlus) { return res.replace(/^git[+]/, '') } else { return res } } GitHost.prototype.ssh = function (opts) { return this._fill(this.sshtemplate, opts) } GitHost.prototype.sshurl = function (opts) { return this._fill(this.sshurltemplate, opts) } GitHost.prototype.browse = function (P, F, opts) { if (typeof P === 'string') { if (typeof F !== 'string') { opts = F F = null } return this._fill(this.browsefiletemplate, extend({ fragment: F, path: P }, opts)) } else { return this._fill(this.browsetemplate, P) } } GitHost.prototype.docs = function (opts) { return this._fill(this.docstemplate, opts) } GitHost.prototype.bugs = function (opts) { return this._fill(this.bugstemplate, opts) } GitHost.prototype.https = function (opts) { return this._fill(this.httpstemplate, opts) } GitHost.prototype.git = function (opts) { return this._fill(this.gittemplate, opts) } GitHost.prototype.shortcut = function (opts) { return this._fill(this.shortcuttemplate, opts) } GitHost.prototype.path = function (opts) { return this._fill(this.pathtemplate, opts) } GitHost.prototype.tarball = function (opts_) { var opts = extend({}, opts_, { noCommittish: false }) return this._fill(this.tarballtemplate, opts) } GitHost.prototype.file = function (P, opts) { return this._fill(this.filetemplate, extend({ path: P }, opts)) } GitHost.prototype.getDefaultRepresentation = function () { return this.default } GitHost.prototype.toString = function (opts) { if (this.default && typeof this[this.default] === 'function') return this[this.default](opts) return this.sshurl(opts) } /***/ }), /***/ 19672: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var url = __webpack_require__(57310) var gitHosts = __webpack_require__(84479) var GitHost = module.exports = __webpack_require__(11234) var LRU = __webpack_require__(64422) var cache = new LRU({max: 1000}) var protocolToRepresentationMap = { 'git+ssh:': 'sshurl', 'git+https:': 'https', 'ssh:': 'sshurl', 'git:': 'git' } function protocolToRepresentation (protocol) { return protocolToRepresentationMap[protocol] || protocol.slice(0, -1) } var authProtocols = { 'git:': true, 'https:': true, 'git+https:': true, 'http:': true, 'git+http:': true } module.exports.fromUrl = function (giturl, opts) { if (typeof giturl !== 'string') return var key = giturl + JSON.stringify(opts || {}) if (!cache.has(key)) { cache.set(key, fromUrl(giturl, opts)) } return cache.get(key) } function fromUrl (giturl, opts) { if (giturl == null || giturl === '') return var url = fixupUnqualifiedGist( isGitHubShorthand(giturl) ? 'github:' + giturl : giturl ) var parsed = parseGitUrl(url) var shortcutMatch = url.match(/^([^:]+):(?:[^@]+@)?(?:([^/]*)\/)?([^#]+)/) var matches = Object.keys(gitHosts).map(function (gitHostName) { try { var gitHostInfo = gitHosts[gitHostName] var auth = null if (parsed.auth && authProtocols[parsed.protocol]) { auth = parsed.auth } var committish = parsed.hash ? decodeURIComponent(parsed.hash.substr(1)) : null var user = null var project = null var defaultRepresentation = null if (shortcutMatch && shortcutMatch[1] === gitHostName) { user = shortcutMatch[2] && decodeURIComponent(shortcutMatch[2]) project = decodeURIComponent(shortcutMatch[3].replace(/\.git$/, '')) defaultRepresentation = 'shortcut' } else { if (parsed.host && parsed.host !== gitHostInfo.domain && parsed.host.replace(/^www[.]/, '') !== gitHostInfo.domain) return if (!gitHostInfo.protocols_re.test(parsed.protocol)) return if (!parsed.path) return var pathmatch = gitHostInfo.pathmatch var matched = parsed.path.match(pathmatch) if (!matched) return /* istanbul ignore else */ if (matched[1] !== null && matched[1] !== undefined) { user = decodeURIComponent(matched[1].replace(/^:/, '')) } project = decodeURIComponent(matched[2]) defaultRepresentation = protocolToRepresentation(parsed.protocol) } return new GitHost(gitHostName, user, auth, project, committish, defaultRepresentation, opts) } catch (ex) { /* istanbul ignore else */ if (ex instanceof URIError) { } else throw ex } }).filter(function (gitHostInfo) { return gitHostInfo }) if (matches.length !== 1) return return matches[0] } function isGitHubShorthand (arg) { // Note: This does not fully test the git ref format. // See https://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html // // The only way to do this properly would be to shell out to // git-check-ref-format, and as this is a fast sync function, // we don't want to do that. Just let git fail if it turns // out that the commit-ish is invalid. // GH usernames cannot start with . or - return /^[^:@%/\s.-][^:@%/\s]*[/][^:@\s/%]+(?:#.*)?$/.test(arg) } function fixupUnqualifiedGist (giturl) { // necessary for round-tripping gists var parsed = url.parse(giturl) if (parsed.protocol === 'gist:' && parsed.host && !parsed.path) { return parsed.protocol + '/' + parsed.host } else { return giturl } } function parseGitUrl (giturl) { var matched = giturl.match(/^([^@]+)@([^:/]+):[/]?((?:[^/]+[/])?[^/]+?)(?:[.]git)?(#.*)?$/) if (!matched) { var legacy = url.parse(giturl) if (legacy.auth) { // git urls can be in the form of scp-style/ssh-connect strings, like // git+ssh://user@host.com:some/path, which the legacy url parser // supports, but WhatWG url.URL class does not. However, the legacy // parser de-urlencodes the username and password, so something like // https://user%3An%40me:p%40ss%3Aword@x.com/ becomes // https://user:n@me:p@ss:word@x.com/ which is all kinds of wrong. // Pull off just the auth and host, so we dont' get the confusing // scp-style URL, then pass that to the WhatWG parser to get the // auth properly escaped. const authmatch = giturl.match(/[^@]+@[^:/]+/) /* istanbul ignore else - this should be impossible */ if (authmatch) { var whatwg = new url.URL(authmatch[0]) legacy.auth = whatwg.username || '' if (whatwg.password) legacy.auth += ':' + whatwg.password } } return legacy } return { protocol: 'git+ssh:', slashes: true, auth: matched[1], host: matched[2], port: null, hostname: matched[2], hash: matched[4], search: null, query: null, pathname: '/' + matched[3], path: '/' + matched[3], href: 'git+ssh://' + matched[1] + '@' + matched[2] + '/' + matched[3] + (matched[4] || '') } } /***/ }), /***/ 64422: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // A linked list to keep track of recently-used-ness const Yallist = __webpack_require__(20891) const MAX = Symbol('max') const LENGTH = Symbol('length') const LENGTH_CALCULATOR = Symbol('lengthCalculator') const ALLOW_STALE = Symbol('allowStale') const MAX_AGE = Symbol('maxAge') const DISPOSE = Symbol('dispose') const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') const LRU_LIST = Symbol('lruList') const CACHE = Symbol('cache') const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') const naiveLength = () => 1 // lruList is a yallist where the head is the youngest // item, and the tail is the oldest. the list contains the Hit // objects as the entries. // Each Hit object has a reference to its Yallist.Node. This // never changes. // // cache is a Map (or PseudoMap) that matches the keys to // the Yallist.Node object. class LRUCache { constructor (options) { if (typeof options === 'number') options = { max: options } if (!options) options = {} if (options.max && (typeof options.max !== 'number' || options.max < 0)) throw new TypeError('max must be a non-negative number') // Kind of weird to have a default max of Infinity, but oh well. const max = this[MAX] = options.max || Infinity const lc = options.length || naiveLength this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc this[ALLOW_STALE] = options.stale || false if (options.maxAge && typeof options.maxAge !== 'number') throw new TypeError('maxAge must be a number') this[MAX_AGE] = options.maxAge || 0 this[DISPOSE] = options.dispose this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false this.reset() } // resize the cache when the max changes. set max (mL) { if (typeof mL !== 'number' || mL < 0) throw new TypeError('max must be a non-negative number') this[MAX] = mL || Infinity trim(this) } get max () { return this[MAX] } set allowStale (allowStale) { this[ALLOW_STALE] = !!allowStale } get allowStale () { return this[ALLOW_STALE] } set maxAge (mA) { if (typeof mA !== 'number') throw new TypeError('maxAge must be a non-negative number') this[MAX_AGE] = mA trim(this) } get maxAge () { return this[MAX_AGE] } // resize the cache when the lengthCalculator changes. set lengthCalculator (lC) { if (typeof lC !== 'function') lC = naiveLength if (lC !== this[LENGTH_CALCULATOR]) { this[LENGTH_CALCULATOR] = lC this[LENGTH] = 0 this[LRU_LIST].forEach(hit => { hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) this[LENGTH] += hit.length }) } trim(this) } get lengthCalculator () { return this[LENGTH_CALCULATOR] } get length () { return this[LENGTH] } get itemCount () { return this[LRU_LIST].length } rforEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].tail; walker !== null;) { const prev = walker.prev forEachStep(this, fn, walker, thisp) walker = prev } } forEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].head; walker !== null;) { const next = walker.next forEachStep(this, fn, walker, thisp) walker = next } } keys () { return this[LRU_LIST].toArray().map(k => k.key) } values () { return this[LRU_LIST].toArray().map(k => k.value) } reset () { if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) { this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) } this[CACHE] = new Map() // hash of items by key this[LRU_LIST] = new Yallist() // list of items in order of use recency this[LENGTH] = 0 // length of items in the list } dump () { return this[LRU_LIST].map(hit => isStale(this, hit) ? false : { k: hit.key, v: hit.value, e: hit.now + (hit.maxAge || 0) }).toArray().filter(h => h) } dumpLru () { return this[LRU_LIST] } set (key, value, maxAge) { maxAge = maxAge || this[MAX_AGE] if (maxAge && typeof maxAge !== 'number') throw new TypeError('maxAge must be a number') const now = maxAge ? Date.now() : 0 const len = this[LENGTH_CALCULATOR](value, key) if (this[CACHE].has(key)) { if (len > this[MAX]) { del(this, this[CACHE].get(key)) return false } const node = this[CACHE].get(key) const item = node.value // dispose of the old one before overwriting // split out into 2 ifs for better coverage tracking if (this[DISPOSE]) { if (!this[NO_DISPOSE_ON_SET]) this[DISPOSE](key, item.value) } item.now = now item.maxAge = maxAge item.value = value this[LENGTH] += len - item.length item.length = len this.get(key) trim(this) return true } const hit = new Entry(key, value, len, now, maxAge) // oversized objects fall out of cache automatically. if (hit.length > this[MAX]) { if (this[DISPOSE]) this[DISPOSE](key, value) return false } this[LENGTH] += hit.length this[LRU_LIST].unshift(hit) this[CACHE].set(key, this[LRU_LIST].head) trim(this) return true } has (key) { if (!this[CACHE].has(key)) return false const hit = this[CACHE].get(key).value return !isStale(this, hit) } get (key) { return get(this, key, true) } peek (key) { return get(this, key, false) } pop () { const node = this[LRU_LIST].tail if (!node) return null del(this, node) return node.value } del (key) { del(this, this[CACHE].get(key)) } load (arr) { // reset the cache this.reset() const now = Date.now() // A previous serialized cache has the most recent items first for (let l = arr.length - 1; l >= 0; l--) { const hit = arr[l] const expiresAt = hit.e || 0 if (expiresAt === 0) // the item was created without expiration in a non aged cache this.set(hit.k, hit.v) else { const maxAge = expiresAt - now // dont add already expired items if (maxAge > 0) { this.set(hit.k, hit.v, maxAge) } } } } prune () { this[CACHE].forEach((value, key) => get(this, key, false)) } } const get = (self, key, doUse) => { const node = self[CACHE].get(key) if (node) { const hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) return undefined } else { if (doUse) { if (self[UPDATE_AGE_ON_GET]) node.value.now = Date.now() self[LRU_LIST].unshiftNode(node) } } return hit.value } } const isStale = (self, hit) => { if (!hit || (!hit.maxAge && !self[MAX_AGE])) return false const diff = Date.now() - hit.now return hit.maxAge ? diff > hit.maxAge : self[MAX_AGE] && (diff > self[MAX_AGE]) } const trim = self => { if (self[LENGTH] > self[MAX]) { for (let walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) { // We know that we're about to delete this one, and also // what the next least recently used key will be, so just // go ahead and set it now. const prev = walker.prev del(self, walker) walker = prev } } } const del = (self, node) => { if (node) { const hit = node.value if (self[DISPOSE]) self[DISPOSE](hit.key, hit.value) self[LENGTH] -= hit.length self[CACHE].delete(hit.key) self[LRU_LIST].removeNode(node) } } class Entry { constructor (key, value, length, now, maxAge) { this.key = key this.value = value this.length = length this.now = now this.maxAge = maxAge || 0 } } const forEachStep = (self, fn, node, thisp) => { let hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) hit = undefined } if (hit) fn.call(thisp, hit.value, hit.key, self) } module.exports = LRUCache /***/ }), /***/ 65693: /***/ ((module) => { "use strict"; module.exports = function (Yallist) { Yallist.prototype[Symbol.iterator] = function* () { for (let walker = this.head; walker; walker = walker.next) { yield walker.value } } } /***/ }), /***/ 20891: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = Yallist Yallist.Node = Node Yallist.create = Yallist function Yallist (list) { var self = this if (!(self instanceof Yallist)) { self = new Yallist() } self.tail = null self.head = null self.length = 0 if (list && typeof list.forEach === 'function') { list.forEach(function (item) { self.push(item) }) } else if (arguments.length > 0) { for (var i = 0, l = arguments.length; i < l; i++) { self.push(arguments[i]) } } return self } Yallist.prototype.removeNode = function (node) { if (node.list !== this) { throw new Error('removing node which does not belong to this list') } var next = node.next var prev = node.prev if (next) { next.prev = prev } if (prev) { prev.next = next } if (node === this.head) { this.head = next } if (node === this.tail) { this.tail = prev } node.list.length-- node.next = null node.prev = null node.list = null return next } Yallist.prototype.unshiftNode = function (node) { if (node === this.head) { return } if (node.list) { node.list.removeNode(node) } var head = this.head node.list = this node.next = head if (head) { head.prev = node } this.head = node if (!this.tail) { this.tail = node } this.length++ } Yallist.prototype.pushNode = function (node) { if (node === this.tail) { return } if (node.list) { node.list.removeNode(node) } var tail = this.tail node.list = this node.prev = tail if (tail) { tail.next = node } this.tail = node if (!this.head) { this.head = node } this.length++ } Yallist.prototype.push = function () { for (var i = 0, l = arguments.length; i < l; i++) { push(this, arguments[i]) } return this.length } Yallist.prototype.unshift = function () { for (var i = 0, l = arguments.length; i < l; i++) { unshift(this, arguments[i]) } return this.length } Yallist.prototype.pop = function () { if (!this.tail) { return undefined } var res = this.tail.value this.tail = this.tail.prev if (this.tail) { this.tail.next = null } else { this.head = null } this.length-- return res } Yallist.prototype.shift = function () { if (!this.head) { return undefined } var res = this.head.value this.head = this.head.next if (this.head) { this.head.prev = null } else { this.tail = null } this.length-- return res } Yallist.prototype.forEach = function (fn, thisp) { thisp = thisp || this for (var walker = this.head, i = 0; walker !== null; i++) { fn.call(thisp, walker.value, i, this) walker = walker.next } } Yallist.prototype.forEachReverse = function (fn, thisp) { thisp = thisp || this for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { fn.call(thisp, walker.value, i, this) walker = walker.prev } } Yallist.prototype.get = function (n) { for (var i = 0, walker = this.head; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.next } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.getReverse = function (n) { for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.prev } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.map = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.head; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.next } return res } Yallist.prototype.mapReverse = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.tail; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.prev } return res } Yallist.prototype.reduce = function (fn, initial) { var acc var walker = this.head if (arguments.length > 1) { acc = initial } else if (this.head) { walker = this.head.next acc = this.head.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = 0; walker !== null; i++) { acc = fn(acc, walker.value, i) walker = walker.next } return acc } Yallist.prototype.reduceReverse = function (fn, initial) { var acc var walker = this.tail if (arguments.length > 1) { acc = initial } else if (this.tail) { walker = this.tail.prev acc = this.tail.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = this.length - 1; walker !== null; i--) { acc = fn(acc, walker.value, i) walker = walker.prev } return acc } Yallist.prototype.toArray = function () { var arr = new Array(this.length) for (var i = 0, walker = this.head; walker !== null; i++) { arr[i] = walker.value walker = walker.next } return arr } Yallist.prototype.toArrayReverse = function () { var arr = new Array(this.length) for (var i = 0, walker = this.tail; walker !== null; i++) { arr[i] = walker.value walker = walker.prev } return arr } Yallist.prototype.slice = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = 0, walker = this.head; walker !== null && i < from; i++) { walker = walker.next } for (; walker !== null && i < to; i++, walker = walker.next) { ret.push(walker.value) } return ret } Yallist.prototype.sliceReverse = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { walker = walker.prev } for (; walker !== null && i > from; i--, walker = walker.prev) { ret.push(walker.value) } return ret } Yallist.prototype.splice = function (start, deleteCount, ...nodes) { if (start > this.length) { start = this.length - 1 } if (start < 0) { start = this.length + start; } for (var i = 0, walker = this.head; walker !== null && i < start; i++) { walker = walker.next } var ret = [] for (var i = 0; walker && i < deleteCount; i++) { ret.push(walker.value) walker = this.removeNode(walker) } if (walker === null) { walker = this.tail } if (walker !== this.head && walker !== this.tail) { walker = walker.prev } for (var i = 0; i < nodes.length; i++) { walker = insert(this, walker, nodes[i]) } return ret; } Yallist.prototype.reverse = function () { var head = this.head var tail = this.tail for (var walker = head; walker !== null; walker = walker.prev) { var p = walker.prev walker.prev = walker.next walker.next = p } this.head = tail this.tail = head return this } function insert (self, node, value) { var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self) if (inserted.next === null) { self.tail = inserted } if (inserted.prev === null) { self.head = inserted } self.length++ return inserted } function push (self, item) { self.tail = new Node(item, self.tail, null, self) if (!self.head) { self.head = self.tail } self.length++ } function unshift (self, item) { self.head = new Node(item, null, self.head, self) if (!self.tail) { self.tail = self.head } self.length++ } function Node (value, prev, next, list) { if (!(this instanceof Node)) { return new Node(value, prev, next, list) } this.list = list this.value = value if (prev) { prev.next = this this.prev = prev } else { this.prev = null } if (next) { next.prev = this this.next = next } else { this.next = null } } try { // add if support for Symbol.iterator is present __webpack_require__(65693)(Yallist) } catch (er) {} /***/ }), /***/ 59337: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createDepGraphFromArchive = createDepGraphFromArchive; exports.createDepGraphFromArchives = createDepGraphFromArchives; exports.isArchive = isArchive; exports.findArchives = findArchives; const dep_graph_1 = __webpack_require__(38115); const path = __webpack_require__(71017); const crypto = __webpack_require__(6113); const fs = __webpack_require__(57147); const glob = __webpack_require__(12884); const debugLib = __webpack_require__(15158); const search_1 = __webpack_require__(18906); const debug = debugLib('snyk-mvn-plugin'); const ALGORITHM = 'sha1'; const DIGEST = 'hex'; function getSha1(buf) { return crypto.createHash(ALGORITHM).update(buf).digest(DIGEST); } async function getMavenPackages(targetPath, snykHttpClient) { const contents = fs.readFileSync(targetPath); const sha1 = getSha1(contents); return (0, search_1.getMavenPackageInfo)(sha1, targetPath, snykHttpClient); } async function getDependencies(paths, snykHttpClient) { let dependencies = []; for (const p of paths) { try { const mavenPackages = await getMavenPackages(p, snykHttpClient); dependencies = dependencies.concat(mavenPackages); } catch (err) { // log error and continue with other paths if (err instanceof Error) { console.error(`Failed to get maven dependency for '${p}'.`, err.message); } } } return dependencies; } async function createDepGraphFromArchive(root, targetPath, snykHttpClient) { try { return await createDepGraphFromArchives(root, [targetPath], snykHttpClient); } catch (err) { const msg = `There was a problem generating a dep-graph for '${targetPath}'.`; debug(msg, err); if (err instanceof Error) { throw new Error(msg + ' ' + err.message); } throw new Error(msg); } } async function createDepGraphFromArchives(root, archivePaths, snykHttpClient) { if (!snykHttpClient) { throw new Error('No HTTP client provided!'); } try { const dependencies = await getDependencies(archivePaths, snykHttpClient); if (!dependencies.length) { throw new Error(`No Maven artifacts found!`); } debug(`Creating dep-graph from ${JSON.stringify(dependencies)}`); const rootDependency = getRootDependency(root); const rootPkg = { name: `${rootDependency.groupId}:${rootDependency.artifactId}`, version: rootDependency.version, }; const builder = new dep_graph_1.DepGraphBuilder({ name: 'maven' }, rootPkg); for (const dependency of dependencies) { const nodeId = `${dependency.groupId}:${dependency.artifactId}@${dependency.version}`; builder.addPkgNode({ name: `${dependency.groupId}:${dependency.artifactId}`, version: dependency.version, }, nodeId); builder.connectDep(builder.rootNodeId, nodeId); } const depGraph = builder.build(); debug(`Created dep-graph ${JSON.stringify(depGraph.toJSON())}`); return depGraph; } catch (err) { const msg = `Detected supported file(s) in '${root}', but there was a problem generating a dep-graph.`; debug(msg, err); if (err instanceof Error) { throw new Error(msg + ' ' + err.message); } throw new Error(msg); } } function isArchive(file) { return !!file.match(/\.(([jwa]ar)|(zip))$/); } function findArchives(targetPath) { const stats = fs.statSync(targetPath); const dir = stats.isFile() ? path.dirname(targetPath) : targetPath; return glob.sync(`${dir}/**/*.@(jar|war|aar|zip)`); } function getRootDependency(root, targetFile) { let groupId; if (targetFile) { groupId = path.dirname(targetFile); if (groupId === '.') { // we are in directory of the jar groupId = path.basename(path.resolve(root)); } } else { // take root's parent directory base name groupId = path.basename(path.dirname(path.resolve(root))); } // replace path separators with dots groupId = groupId .replace(/\//g, '.') // *inx .replace(/\\/g, '.') // windows .replace(/^\./, ''); // remove any leading '.' return { groupId: groupId || 'root', artifactId: path.basename(targetFile || root) || 'root', version: '1.0.0', }; } //# sourceMappingURL=archive.js.map /***/ }), /***/ 34083: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.formatGenericPluginError = formatGenericPluginError; function formatGenericPluginError(error, mavenCommand, mvnArgs) { const fullCommand = [mavenCommand, ...mvnArgs].join(' '); const mvnwCommandTipMessage = 'Currently, you cannot run `mvnw` outside your current directory, you will have to go inside the directory of your project (see: https://github.com/takari/maven-wrapper/issues/133)\n\n'; return (error.message + '\n\n' + 'Please make sure that Apache Maven Dependency Plugin ' + 'version 2.2 or above is installed, and that `' + fullCommand + '` executes successfully ' + 'on this project.\n\n' + (mavenCommand.indexOf('mvnw') >= 0 ? mvnwCommandTipMessage : '') + 'If the problem persists, collect the output of `' + 'DEBUG=* ' + fullCommand + '` and contact support@snyk.io\n'); } //# sourceMappingURL=error-format.js.map /***/ }), /***/ 29615: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.debug = debug; exports.getCommand = getCommand; exports.inspect = inspect; exports.buildArgs = buildArgs; const os = __webpack_require__(22037); const fs = __webpack_require__(57147); const path = __webpack_require__(71017); const parse_versions_1 = __webpack_require__(55648); const subProcess = __webpack_require__(17872); const archive_1 = __webpack_require__(59337); const error_format_1 = __webpack_require__(34083); const debugModule = __webpack_require__(15158); const parse_1 = __webpack_require__(22891); const WRAPPERS = ['mvnw', 'mvnw.cmd']; // To enable debugging output, use `snyk -d` let logger = null; function debug(...messages) { if (logger === null) { if (process.env.DEBUG) { debugModule.enable(process.env.DEBUG); } logger = debugModule('snyk-mvn-plugin'); } messages.forEach((m) => logger?.(m)); } function getCommand(root, targetFile) { if (!targetFile) { return 'mvn'; } const isWinLocal = /^win/.test(os.platform()); // local check, can be stubbed in tests const wrapperScript = isWinLocal ? 'mvnw.cmd' : './mvnw'; // try to find a sibling wrapper script first let pathToWrapper = path.resolve(root, path.dirname(targetFile), wrapperScript); if (fs.existsSync(pathToWrapper)) { return wrapperScript; } // now try to find a wrapper in the root pathToWrapper = path.resolve(root, wrapperScript); if (fs.existsSync(pathToWrapper)) { return wrapperScript; } return 'mvn'; } function getParentDirectory(p) { return path.dirname(p); } // When we have `mvn`, we can run the subProcess from anywhere. // However due to https://github.com/takari/maven-wrapper/issues/133, `mvnw` can only be run // within the directory where `mvnw` exists function findWrapper(mavenCommand, root, targetPath) { if (mavenCommand === 'mvn') { return root; } // In this branch we need to -find- the mvnw location; // we start from the containing directory and climb up to the scanned-root-folder let foundMVWLocation = false; // Look for mvnw in the current directory. if not - climb one up let currentFolder = targetPath; do { if (getParentDirectory(root) === currentFolder || !currentFolder.length) { // if we climbed up the tree 1 level higher than our root directory throw new Error("Couldn't find mvnw"); } foundMVWLocation = !!WRAPPERS.map((name) => path.join(currentFolder, name)) // paths .map(fs.existsSync) // since we're on the client's machine - check if the file exists .filter(Boolean).length; // hope for truths & bolleanify if (!foundMVWLocation) { // if we couldn't find the file, go to the parent, or empty string for quick escape if needed currentFolder = getParentDirectory(currentFolder); } } while (!foundMVWLocation); return currentFolder; } async function inspect(root, targetFile, options, snykHttpClient) { const targetPath = targetFile ? path.resolve(root, targetFile) : path.resolve(root); if (!fs.existsSync(targetPath)) { throw new Error('Could not find file or directory ' + targetPath); } if (!options) { options = { dev: false, scanAllUnmanaged: false, 'print-graph': false }; } if (targetPath && (0, archive_1.isArchive)(targetPath)) { debug(`Creating dep-graph from ${targetPath}`); const depGraph = await (0, archive_1.createDepGraphFromArchive)(root, targetPath, snykHttpClient); return { plugin: { name: 'bundled:maven', runtime: 'unknown', meta: {}, }, package: {}, // using dep-graph over depTree dependencyGraph: depGraph, }; } if (options.scanAllUnmanaged) { const archives = (0, archive_1.findArchives)(root); if (archives.length > 0) { debug(`Creating dep-graph from archives in ${root}`); const depGraph = await (0, archive_1.createDepGraphFromArchives)(root, archives, snykHttpClient); return { plugin: { name: 'bundled:maven', runtime: 'unknown', meta: {}, }, package: {}, // using dep-graph over depTree dependencyGraph: depGraph, }; } else { throw Error(`Could not find any supported files in '${root}'.`); } } const mavenCommand = getCommand(root, targetFile); const mvnWorkingDirectory = findWrapper(mavenCommand, root, targetPath); const args = options.args || []; const verboseEnabled = args.includes('-Dverbose') || args.includes('-Dverbose=true') || !!options['print-graph']; const mvnArgs = buildArgs(root, mvnWorkingDirectory, targetFile, args, options.mavenAggregateProject, verboseEnabled); let result; try { debug(`Maven command: ${mavenCommand} ${mvnArgs.join(' ')}`); debug(`Maven working directory: ${mvnWorkingDirectory}`); debug(`Verbose enabled: ${verboseEnabled}`); result = await subProcess.execute(mavenCommand, mvnArgs, { cwd: mvnWorkingDirectory, }); const versionResult = await subProcess.execute(`${mavenCommand} --version`, [], { cwd: mvnWorkingDirectory, }); const parseResult = (0, parse_1.parse)(result, options.dev, verboseEnabled); const { javaVersion, mavenVersion } = (0, parse_versions_1.parseVersions)(versionResult); const mavenPluginVersion = (0, parse_1.parsePluginVersionFromStdout)(result); return { plugin: { name: 'bundled:maven', runtime: 'unknown', meta: { versionBuildInfo: { metaBuildVersion: { mavenVersion, javaVersion, mavenPluginVersion, }, }, }, }, ...parseResult, }; } catch (err) { if (result) debug(`>>> Output from mvn: ${result}`); if (err instanceof Error) { const msg = (0, error_format_1.formatGenericPluginError)(err, mavenCommand, mvnArgs); throw new Error(msg); } throw err; } } function buildArgs(rootPath, executionPath, targetFile, mavenArgs, mavenAggregateProject = false, verboseEnabled = false) { let args = []; if (mavenAggregateProject && !verboseEnabled) { // to workaround an issue in maven-dependency-tree plugin // when unpublished artifacts do not exist in either a local or remote repository // see https://stackoverflow.com/questions/1677473/maven-doesnt-recognize-sibling-modules-when-running-mvn-dependencytree // addendum: if verboseEnabled we are already forcing a newer maven-dependency-plugin, so this is not required args = args.concat('test-compile'); } // when using verbose ensure maven-dependency-plugin version 3 is used // lower versions do not work with -DoutputType=dot const mavenDependencyPlugin = verboseEnabled ? 'org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree' : 'dependency:tree'; // Requires Maven >= 2.2 args = args.concat([ mavenDependencyPlugin, // use dependency plugin to display a tree of dependencies '-DoutputType=dot', // use 'dot' output format '--batch-mode', // clean up output, disables output color and download progress ]); if (!mavenAggregateProject) { args = args.concat('--non-recursive'); // do not include modules unless performing aggregate project scan } if (targetFile && !mavenAggregateProject) { // if we are where we can execute - we preserve the original path; // if not - we rely on the executor (mvnw) to be spawned at the closest directory, leaving us w/ the file itself if (rootPath === executionPath) { args.push('--file="' + targetFile + '"'); } else { args.push('--file="' + path.basename(targetFile) + '"'); } } if (verboseEnabled && !mavenArgs.includes('-Dverbose') && !mavenArgs.includes('-Dverbose=true')) { args = args.concat('-Dverbose'); } args = args.concat(mavenArgs); return args; } //# sourceMappingURL=index.js.map /***/ }), /***/ 58553: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseDigraph = parseDigraph; const regex = /digraph([\s\S]*?)\}[\s]*?$/gm; function parseDigraph(text) { const result = text.match(regex); return result || null; } //# sourceMappingURL=parse-digraph.js.map /***/ }), /***/ 55648: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseVersions = parseVersions; function parseVersions(text) { // AppVeyor (at least) doesn't use \n\r, therefore os.EOL doesn't work const data = text.split('\n'); const mavenVersion = data[0]; const javaVersion = data.find((line) => line.startsWith('Java version:')) || ''; return { javaVersion, mavenVersion }; } //# sourceMappingURL=parse-versions.js.map /***/ }), /***/ 8074: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildDepGraph = buildDepGraph; const dep_graph_1 = __webpack_require__(38115); const dependency_1 = __webpack_require__(20448); function buildDepGraph(mavenGraph, includeTestScope = false, verboseEnabled = false) { const { rootId, nodes } = mavenGraph; const parsedRoot = parseId(rootId); const builder = new dep_graph_1.DepGraphBuilder({ name: 'maven' }, parsedRoot.pkgInfo); const visitedMap = {}; const queue = []; queue.push(...getItems(rootId, [], nodes[rootId])); // breadth first search while (queue.length > 0) { const item = queue.shift(); if (!item) continue; const { id, ancestry, parentId } = item; const parsed = parseId(id); const node = nodes[id]; if (!includeTestScope && parsed.scope === 'test' && !node.reachesProdDep) { continue; } const visited = visitedMap[parsed.key]; if (!verboseEnabled && visited) { const prunedId = visited.id + ':pruned'; builder.addPkgNode(visited.pkgInfo, prunedId, { labels: { pruned: 'true' }, }); builder.connectDep(parentId, prunedId); continue; // don't queue any more children } // If verbose is enabled and our ancestry includes ourselves // we are cyclic and should be pruned :) if (verboseEnabled && ancestry.includes(id)) { const prunedId = visited.id + ':pruned-cycle'; builder.addPkgNode(visited.pkgInfo, prunedId, { labels: { pruned: 'cyclic' }, }); builder.connectDep(parentId, prunedId); continue; // don't queue any more children } const parentNodeId = parentId === rootId ? builder.rootNodeId : parentId; if (verboseEnabled && visited) { // use visited node when omited dependencies found (verbose) builder.addPkgNode(visited.pkgInfo, visited.id); builder.connectDep(parentNodeId, visited.id); } else { builder.addPkgNode(parsed.pkgInfo, id); builder.connectDep(parentNodeId, id); visitedMap[parsed.key] = parsed; } // Remember to push updated ancestry here queue.push(...getItems(id, [...ancestry, id], node)); } return builder.build(); } function getItems(parentId, ancestry, node) { const items = []; for (const id of node?.dependsOn || []) { items.push({ id, ancestry, parentId }); } return items; } function parseId(id) { const dep = (0, dependency_1.parseDependency)(id); const maybeClassifier = dep.classifier ? `:${dep.classifier}` : ''; const name = `${dep.groupId}:${dep.artifactId}`; return { id, key: `${name}:${dep.type}${maybeClassifier}`, pkgInfo: { name, version: dep.version, }, scope: dep.scope, }; } //# sourceMappingURL=dep-graph.js.map /***/ }), /***/ 20448: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseDependency = parseDependency; const UNKNOWN = 'unknown'; const unknownDependency = { groupId: UNKNOWN, artifactId: UNKNOWN, type: UNKNOWN, version: UNKNOWN, }; function parseDependency(value) { if (typeof value !== 'string') return unknownDependency; const parts = value.split(':'); switch (parts.length) { // using classifier and scope // "com.example:my-app:jar:jdk8:1.2.3:compile" case 6: { return { groupId: getPart(parts, 0), artifactId: getPart(parts, 1), type: getPart(parts, 2), classifier: getPart(parts, 3), version: getPart(parts, 4), scope: getPart(parts, 5), }; } // using scope // "com.example:my-app:jar:1.2.3:compile" case 5: { return { groupId: getPart(parts, 0), artifactId: getPart(parts, 1), type: getPart(parts, 2), version: getPart(parts, 3), scope: getPart(parts, 4), }; } // everything else // "com.example:my-app:jar:1.2.3" case 4: { return { groupId: getPart(parts, 0), artifactId: getPart(parts, 1), type: getPart(parts, 2), version: getPart(parts, 3), }; } default: { return unknownDependency; } } } function getPart(parts, index) { return parts[index] || UNKNOWN; } //# sourceMappingURL=dependency.js.map /***/ }), /***/ 2175: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseDigraphs = parseDigraphs; const maven_graph_builder_1 = __webpack_require__(68465); const newLine = /[\r\n]+/g; function parseDigraphs(digraphs) { const graphs = []; for (const digraph of digraphs) { const lines = digraph.split(newLine); const rootId = findQuotedContents(lines[0]); if (!rootId) { throw new Error(`Unexpected digraph could not find root node. Could not parse "${lines[0]}".`); } const builder = new maven_graph_builder_1.MavenGraphBuilder(rootId); for (let i = 1; i < lines.length - 1; i++) { const line = parseLine(lines[i]); if (!line) { throw new Error(`Unexpected digraph could not connect nodes. Could not parse "${lines[i]}".`); } builder.connect(line.from, line.to); } graphs.push(builder.graph); } return graphs; } function parseLine(line) { if (!line) return null; const [left, right] = line.split('->'); if (!left || !right) return null; const from = findQuotedContents(left); const to = findQuotedContents(right); if (!from || !to) return null; return { from, to }; } function findQuotedContents(value) { if (!value) return null; const start = value.indexOf('"') + 1; const end = value.lastIndexOf('"'); if (isVerbose(value)) { const [left] = value .substring(start + (value[start] == '(' ? 1 : 0), end) .split(/ [-(]/); return left; } return value.substring(start, end); } function isVerbose(value) { // clear string of leading and trailing non letters // when using -Dverbose ensure omitted reasons are parsed correctly // https://github.com/apache/maven/blob/ab6ec5bd74af20ab429509eb56fc8e3dff4c7fc7/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultNode.java#L113 const dverboseReasons = [ 'version managed from', 'omitted for conflict with', 'omitted for duplicate', ]; for (const dverboseReason of dverboseReasons) { if (value.includes(dverboseReason)) return true; } return false; } //# sourceMappingURL=digraph.js.map /***/ }), /***/ 22891: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parsePluginVersionFromStdout = void 0; exports.parse = parse; const stdout_1 = __webpack_require__(16866); const digraph_1 = __webpack_require__(2175); const dep_graph_1 = __webpack_require__(8074); var stdout_2 = __webpack_require__(16866); Object.defineProperty(exports, "parsePluginVersionFromStdout", ({ enumerable: true, get: function () { return stdout_2.parsePluginVersionFromStdout; } })); function parse(stdout, includeTestScope = false, verboseEnabled = false) { const digraphs = (0, stdout_1.parseDigraphsFromStdout)(stdout); const mavenGraphs = (0, digraph_1.parseDigraphs)(digraphs); const scannedProjects = []; for (const mavenGraph of mavenGraphs) { const depGraph = (0, dep_graph_1.buildDepGraph)(mavenGraph, includeTestScope, verboseEnabled); scannedProjects.push({ depGraph }); } return { scannedProjects, }; } //# sourceMappingURL=index.js.map /***/ }), /***/ 68465: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MavenGraphBuilder = void 0; class MavenGraphBuilder { #graph; constructor(rootId) { this.#graph = { rootId, nodes: { [rootId]: { dependsOn: [], parents: [], reachesProdDep: false }, }, }; } findOrCreateNode(id) { return this.findNode(id) || this.createNode(id); } findNode(id) { return this.#graph.nodes[id]; } createNode(id) { const node = { dependsOn: [], parents: [], reachesProdDep: false }; this.#graph.nodes[id] = node; return node; } markNodeProdReachable(id) { const node = this.findNode(id); if (node && !node.reachesProdDep) { node.reachesProdDep = true; for (const parentId of node.parents) { this.markNodeProdReachable(parentId); } } } connect(parentId, id) { const parentNode = this.findOrCreateNode(parentId); const childNode = this.findOrCreateNode(id); if (!childNode.parents.includes(parentId)) { childNode.parents.push(parentId); } if (!parentNode.dependsOn.includes(id)) { parentNode.dependsOn.push(id); } if (!id.endsWith(':test')) { this.markNodeProdReachable(id); } } get graph() { return this.#graph; } } exports.MavenGraphBuilder = MavenGraphBuilder; //# sourceMappingURL=maven-graph-builder.js.map /***/ }), /***/ 16866: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseDigraphsFromStdout = parseDigraphsFromStdout; exports.parsePluginVersionFromStdout = parsePluginVersionFromStdout; const parse_digraph_1 = __webpack_require__(58553); const logLabel = /^\[\w+\]\s*/gm; const errorLabel = /^\[ERROR\]/gm; const successLabel = /^\[INFO\] BUILD SUCCESS/gm; const mavenDependencyPluginRegex = /maven-dependency-plugin:(\d\.\d)(\.\d)?:tree/gm; function cleanStdout(stdout) { if (errorLabel.test(stdout) && !successLabel.test(stdout)) { throw new Error('Maven output contains errors.'); } return stdout.replace(logLabel, ''); } // Parse the output from 'mvn dependency:tree -DoutputType=dot' function parseDigraphsFromStdout(stdout) { const cleanedStdout = cleanStdout(stdout); const digraphs = (0, parse_digraph_1.parseDigraph)(cleanedStdout); if (!digraphs) { throw new Error('Cannot find any digraphs.'); } return digraphs; } function parsePluginVersionFromStdout(stdout) { const cleanedStdout = cleanStdout(stdout); const versionRes = mavenDependencyPluginRegex.exec(cleanedStdout); return versionRes ? `${versionRes[1]}${versionRes[2] || ''}` : ''; } //# sourceMappingURL=stdout.js.map /***/ }), /***/ 18906: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getMavenPackageInfo = getMavenPackageInfo; const packageurl_js_1 = __webpack_require__(38382); const debugLib = __webpack_require__(15158); const path = __webpack_require__(71017); const debug = debugLib('snyk-mvn-plugin'); const PACKAGE_SEARCH_TYPE = 'maven'; const PACKAGE_SEARCH_ENDPOINT = '/packages'; const PACKAGE_SEARCH_VERSION = '2022-09-21~beta'; async function getMavenPackageInfo(sha1, targetPath, snykHttpClient) { const searchResults = await searchMavenPackageByChecksum(sha1, targetPath, snykHttpClient); if (searchResults.length == 0) { return [fallbackPackageInfo(sha1, targetPath)]; } // try to find a specific package based on file name const matchingSearchResults = []; if (searchResults.length > 1) { const sha1Target = path.parse(targetPath).base; debug(`Got multiple results for ${sha1}, looking for match on ${sha1Target}`); searchResults.forEach((result) => { if (sha1Target.includes(result.groupId)) { matchingSearchResults.push(result); } }); } // if nothing matches found return all search results return matchingSearchResults.length === 0 ? searchResults : matchingSearchResults; } async function searchMavenPackageByChecksum(sha1, targetPath, snykHttpClient) { const { res, body } = await snykHttpClient({ method: 'get', path: PACKAGE_SEARCH_ENDPOINT, qs: { version: PACKAGE_SEARCH_VERSION, package_type: PACKAGE_SEARCH_TYPE, package_sha1: sha1, }, }); if (!res?.statusCode || res?.statusCode >= 400 || !body || body.errors) { debug(`Failed to resolve ${targetPath}.`); if (body && body.errors) { const catalogError = body.errors[0]; debug(catalogError.detail); debug(catalogError.meta.links[0]); } return []; } return mapPackageSearchResult(body, sha1, targetPath); } function mapPackageSearchResult(body, sha1, targetPath) { return body.data .map((purl) => { try { const pkg = packageurl_js_1.PackageURL.fromString(purl.id); const fallback = fallbackPackageInfo(sha1, targetPath); return { groupId: pkg.namespace || fallback.groupId, artifactId: pkg.name || fallback.artifactId, version: pkg.version || fallback.version, }; } catch (_error) { debug(`Failed to parse package url components for ${targetPath} using sha1 '${sha1}.`); return undefined; } }) .filter((mvnPackage) => mvnPackage !== undefined); } function fallbackPackageInfo(sha1, targetPath) { return { groupId: 'unknown', artifactId: `${targetPath}:${sha1}`, version: 'unknown', }; } //# sourceMappingURL=search.js.map /***/ }), /***/ 17872: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.execute = execute; const childProcess = __webpack_require__(32081); const index_1 = __webpack_require__(29615); const shescape_1 = __webpack_require__(79114); function execute(command, args, options) { const spawnOptions = { shell: true, env: { ...process.env } }; if (options && options.cwd) { spawnOptions.cwd = options.cwd; } if (args) { args = (0, shescape_1.quoteAll)(args, spawnOptions); } // Before spawning an external process, we look if we need to restore the system proxy configuration, // which overides the cli internal proxy configuration. if (process.env.SNYK_SYSTEM_HTTP_PROXY !== undefined) { spawnOptions.env.HTTP_PROXY = process.env.SNYK_SYSTEM_HTTP_PROXY; } if (process.env.SNYK_SYSTEM_HTTPS_PROXY !== undefined) { spawnOptions.env.HTTPS_PROXY = process.env.SNYK_SYSTEM_HTTPS_PROXY; } if (process.env.SNYK_SYSTEM_NO_PROXY !== undefined) { spawnOptions.env.NO_PROXY = process.env.SNYK_SYSTEM_NO_PROXY; } return new Promise((resolve, reject) => { let stdout = ''; let stderr = ''; const proc = childProcess.spawn(command, args, spawnOptions); proc.stdout.on('data', (data) => { stdout = stdout + data; }); proc.stderr.on('data', (data) => { stderr = stderr + data; }); proc.on('error', (err) => { (0, index_1.debug)(`Child process errored with: ${err.message}`); }); proc.on('exit', (code) => { (0, index_1.debug)(`Child process exited with code: ${code}`); }); proc.on('close', (code) => { if (code !== 0) { (0, index_1.debug)(`Child process failed with exit code: ${code}`, '----------------', 'STDERR:', stderr, '----------------', 'STDOUT:', stdout, '----------------'); const stdErrMessage = stderr ? `\nSTDERR:\n${stderr}` : ''; const stdOutMessage = stdout ? `\nSTDOUT:\n${stdout}` : ''; const debugSuggestion = process.env.DEBUG ? '' : `\nRun in debug mode (-d) to see STDERR and STDOUT.`; return reject(new Error(`Child process failed with exit code: ${code}.` + debugSuggestion + (stdErrMessage || stdOutMessage))); } resolve(stdout || stderr); }); }); } //# sourceMappingURL=sub-process.js.map /***/ }), /***/ 33409: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DepGraphBuilder = void 0; const graphlib = __webpack_require__(61009); const dep_graph_1 = __webpack_require__(33866); class DepGraphBuilder { constructor(pkgManager, rootPkg) { this._pkgs = {}; this._pkgNodes = {}; const graph = new graphlib.Graph({ directed: true, multigraph: false, compound: false, }); if (!rootPkg) { rootPkg = { name: '_root', version: '0.0.0', }; } this._rootNodeId = 'root-node'; this._rootPkgId = DepGraphBuilder._getPkgId(rootPkg); this._pkgs[this._rootPkgId] = rootPkg; graph.setNode(this._rootNodeId, { pkgId: this._rootPkgId }); this._pkgNodes[this._rootPkgId] = new Set([this._rootNodeId]); this._graph = graph; this._pkgManager = pkgManager; } get rootNodeId() { return this._rootNodeId; } static _getPkgId(pkg) { return `${pkg.name}@${pkg.version || ''}`; } getPkgs() { return Object.values(this._pkgs); } // TODO: this can create disconnected nodes addPkgNode(pkgInfo, nodeId, nodeInfo) { if (nodeId === this._rootNodeId) { throw new Error('DepGraphBuilder.addPkgNode() cant override root node'); } const pkgId = DepGraphBuilder._getPkgId(pkgInfo); this._pkgs[pkgId] = pkgInfo; this._pkgNodes[pkgId] = this._pkgNodes[pkgId] || new Set(); this._pkgNodes[pkgId].add(nodeId); this._graph.setNode(nodeId, { pkgId, info: nodeInfo }); return this; } // TODO: this can create cycles connectDep(parentNodeId, depNodeId) { if (!this._graph.hasNode(parentNodeId)) { throw new Error('parentNodeId does not exist'); } if (!this._graph.hasNode(depNodeId)) { throw new Error('depNodeId does not exist'); } this._graph.setEdge(parentNodeId, depNodeId); return this; } build() { return new dep_graph_1.DepGraphImpl(this._graph, this._rootNodeId, this._pkgs, this._pkgNodes, this._pkgManager); } } exports.DepGraphBuilder = DepGraphBuilder; //# sourceMappingURL=builder.js.map /***/ }), /***/ 88837: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createFromJSON = exports.SUPPORTED_SCHEMA_RANGE = void 0; const semver = __webpack_require__(9195); const graphlib = __webpack_require__(61009); const errors_1 = __webpack_require__(93970); const validate_graph_1 = __webpack_require__(30555); const dep_graph_1 = __webpack_require__(33866); exports.SUPPORTED_SCHEMA_RANGE = '^1.0.0'; /** * Create a DepGraph instance from a JSON representation of a dep graph. This * is typically used after passing the graph over the wire as `DepGraphData`. */ function createFromJSON(depGraphData) { validateDepGraphData(depGraphData); const graph = new graphlib.Graph({ directed: true, multigraph: false, compound: false, }); const pkgs = {}; const pkgNodes = {}; for (const { id, info } of depGraphData.pkgs) { pkgs[id] = info.version ? info : Object.assign(Object.assign({}, info), { version: undefined }); } for (const node of depGraphData.graph.nodes) { const pkgId = node.pkgId; if (!pkgNodes[pkgId]) { pkgNodes[pkgId] = new Set(); } pkgNodes[pkgId].add(node.nodeId); graph.setNode(node.nodeId, { pkgId, info: node.info }); } for (const node of depGraphData.graph.nodes) { for (const depNodeId of node.deps) { graph.setEdge(node.nodeId, depNodeId.nodeId); } } validate_graph_1.validateGraph(graph, depGraphData.graph.rootNodeId, pkgs, pkgNodes); return new dep_graph_1.DepGraphImpl(graph, depGraphData.graph.rootNodeId, pkgs, pkgNodes, depGraphData.pkgManager); } exports.createFromJSON = createFromJSON; function assert(condition, msg) { if (!condition) { throw new errors_1.ValidationError(msg); } } function validateDepGraphData(depGraphData) { assert(!!semver.valid(depGraphData.schemaVersion) && semver.satisfies(depGraphData.schemaVersion, exports.SUPPORTED_SCHEMA_RANGE), `dep-graph schemaVersion not in "${exports.SUPPORTED_SCHEMA_RANGE}"`); assert(depGraphData.pkgManager && !!depGraphData.pkgManager.name, '.pkgManager.name is missing'); const pkgsMap = depGraphData.pkgs.reduce((acc, cur) => { assert(!(cur.id in acc), 'more than one pkg with same id'); assert(!!cur.info, '.pkgs item missing .info'); acc[cur.id] = cur.info; return acc; }, {}); const nodesMap = depGraphData.graph.nodes.reduce((acc, cur) => { assert(!(cur.nodeId in acc), 'more than on node with same id'); acc[cur.nodeId] = cur; return acc; }, {}); const rootNodeId = depGraphData.graph.rootNodeId; const rootNode = nodesMap[rootNodeId]; assert(rootNodeId in nodesMap, `.${rootNodeId} root graph node is missing`); const rootPkgId = rootNode.pkgId; assert(rootPkgId in pkgsMap, `.${rootPkgId} root pkg missing`); assert(nodesMap[rootNodeId].pkgId === rootPkgId, `the root node .pkgId should be "${rootPkgId}"`); const pkgIds = Object.keys(pkgsMap); // NOTE: this name@version check is very strict, // we can relax it later, it just makes things easier now assert(pkgIds.filter((pkgId) => pkgId !== dep_graph_1.DepGraphImpl.getPkgId(pkgsMap[pkgId])) .length === 0, 'pkgs ids should be name@version'); assert(Object.values(nodesMap).filter((node) => !(node.pkgId in pkgsMap)) .length === 0, 'some instance nodes belong to non-existing pkgIds'); assert(Object.values(pkgsMap).filter((pkg) => !pkg.name) .length === 0, 'some .pkgs elements have no .name field'); } //# sourceMappingURL=create-from-json.js.map /***/ }), /***/ 33866: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DepGraphImpl = void 0; const _isEqual = __webpack_require__(72307); const graphlib = __webpack_require__(61009); const create_from_json_1 = __webpack_require__(88837); class DepGraphImpl { constructor(_graph, _rootNodeId, _pkgs, _pkgNodes, _pkgManager) { this._graph = _graph; this._rootNodeId = _rootNodeId; this._pkgs = _pkgs; this._pkgNodes = _pkgNodes; this._pkgManager = _pkgManager; this._countNodePathsToRootCache = new Map(); this._rootPkgId = _graph.node(_rootNodeId).pkgId; this._pkgList = Object.values(_pkgs); this._depPkgsList = this._pkgList.filter((pkg) => pkg !== this.rootPkg); } static getPkgId(pkg) { return `${pkg.name}@${pkg.version || ''}`; } get pkgManager() { return this._pkgManager; } get rootPkg() { return this._pkgs[this._rootPkgId]; } get rootNodeId() { return this._rootNodeId; } /** * Get all unique packages in the graph (including the root package) */ getPkgs() { return this._pkgList; } /** * Get all unique packages in the graph (excluding the root package) */ getDepPkgs() { return this._depPkgsList; } getPkgNodes(pkg) { const pkgId = DepGraphImpl.getPkgId(pkg); const nodes = []; for (const nodeId of Array.from(this._pkgNodes[pkgId])) { const graphNode = this.getGraphNode(nodeId); nodes.push({ info: graphNode.info || {}, }); } return nodes; } getNode(nodeId) { return this.getGraphNode(nodeId).info || {}; } getNodePkg(nodeId) { return this._pkgs[this.getGraphNode(nodeId).pkgId]; } getPkgNodeIds(pkg) { const pkgId = DepGraphImpl.getPkgId(pkg); if (!this._pkgs[pkgId]) { throw new Error(`no such pkg: ${pkgId}`); } return Array.from(this._pkgNodes[pkgId]); } getNodeDepsNodeIds(nodeId) { const deps = this._graph.successors(nodeId); if (!deps) { throw new Error(`no such node: ${nodeId}`); } return deps; } getNodeParentsNodeIds(nodeId) { const parents = this._graph.predecessors(nodeId); if (!parents) { throw new Error(`no such node: ${nodeId}`); } return parents; } hasCycles() { // `isAcyclic` is expensive, so memoize if (this._hasCycles === undefined) { this._hasCycles = !graphlib.alg.isAcyclic(this._graph); } return this._hasCycles; } pkgPathsToRoot(pkg, opts) { const pathsToRoot = []; const limit = opts === null || opts === void 0 ? void 0 : opts.limit; for (const nodeId of this.getPkgNodeIds(pkg)) { const pathsFromNodeToRoot = this.pathsFromNodeToRoot(nodeId, [], { limit, }); for (const path of pathsFromNodeToRoot) { pathsToRoot.push(path); } if (limit && pathsToRoot.length >= limit) { break; } } // note: sorting to get shorter paths first - // it's nicer - and better resembles older behaviour return pathsToRoot.sort((a, b) => a.length - b.length); } countPathsToRoot(pkg) { let count = 0; for (const nodeId of this.getPkgNodeIds(pkg)) { count += this.countNodePathsToRoot(nodeId); } return count; } equals(other, { compareRoot = true } = {}) { let otherDepGraph; if (other instanceof DepGraphImpl) { otherDepGraph = other; } else { // At runtime theoretically we can have multiple versions of // @snyk/dep-graph. If "other" is not an instance of the same class it is // safer to rebuild it from JSON. otherDepGraph = create_from_json_1.createFromJSON(other.toJSON()); } // In theory, for the graphs created by standard means, `_.isEquals(this._data, otherDepGraph._data)` // should suffice, since node IDs will be generated in a predictable way. // However, there might be different versions of graph and inconsistencies // in the ordering of the arrays, so we perform a deep comparison. return this.nodeEquals(this, this.rootNodeId, otherDepGraph, otherDepGraph.rootNodeId, compareRoot); } directDepsLeadingTo(pkg) { const pkgNodes = this.getPkgNodeIds(pkg); const directDeps = this.getNodeDepsNodeIds(this.rootNodeId); const nodes = directDeps.filter((directDep) => { const reachableNodes = graphlib.alg.postorder(this._graph, [directDep]); return reachableNodes.filter((node) => pkgNodes.includes(node)).length; }); return nodes.map((node) => this.getNodePkg(node)); } /** * Create a JSON representation of a dep graph. This is typically used to * send the dep graph over the wire */ toJSON() { const nodeIds = this._graph.nodes(); const nodes = nodeIds.reduce((acc, nodeId) => { const deps = (this._graph.successors(nodeId) || []).map((depNodeId) => ({ nodeId: depNodeId, })); const node = this._graph.node(nodeId); const elem = { nodeId, pkgId: node.pkgId, deps, }; if (node.info && Object.keys(node.info).length > 0) { elem.info = node.info; } acc.push(elem); return acc; }, []); const pkgs = Object.keys(this._pkgs).map((pkgId) => ({ id: pkgId, info: this._pkgs[pkgId], })); return { schemaVersion: DepGraphImpl.SCHEMA_VERSION, pkgManager: this._pkgManager, pkgs, graph: { rootNodeId: this._rootNodeId, nodes, }, }; } nodeEquals(graphA, nodeIdA, graphB, nodeIdB, compareRoot, traversedPairs = new Set()) { // Skip root nodes comparision if needed. if (compareRoot || (nodeIdA !== graphA.rootNodeId && nodeIdB !== graphB.rootNodeId)) { const pkgA = graphA.getNodePkg(nodeIdA); const pkgB = graphB.getNodePkg(nodeIdB); // Compare PkgInfo (name and version). if (!_isEqual(pkgA, pkgB)) { return false; } const infoA = graphA.getNode(nodeIdA); const infoB = graphB.getNode(nodeIdB); // Compare NodeInfo (VersionProvenance and labels). if (!_isEqual(infoA, infoB)) { return false; } } let depsA = graphA.getNodeDepsNodeIds(nodeIdA); let depsB = graphB.getNodeDepsNodeIds(nodeIdB); // Number of dependencies should be the same. if (depsA.length !== depsB.length) { return false; } // Sort dependencies by name@version string. const sortFn = (graph) => (idA, idB) => { const pkgA = graph.getNodePkg(idA); const pkgB = graph.getNodePkg(idB); return DepGraphImpl.getPkgId(pkgA).localeCompare(DepGraphImpl.getPkgId(pkgB)); }; depsA = depsA.sort(sortFn(graphA)); depsB = depsB.sort(sortFn(graphB)); // Compare Each dependency recursively. for (let i = 0; i < depsA.length; i++) { const pairKey = `${depsA[i]}_${depsB[i]}`; // Prevent cycles. if (traversedPairs.has(pairKey)) { continue; } traversedPairs.add(pairKey); if (!this.nodeEquals(graphA, depsA[i], graphB, depsB[i], compareRoot, traversedPairs)) { return false; } } return true; } getGraphNode(nodeId) { const node = this._graph.node(nodeId); if (!node) { throw new Error(`no such node: ${nodeId}`); } return node; } pathsFromNodeToRoot(nodeId, ancestors = [], opts) { const parentNodesIds = this.getNodeParentsNodeIds(nodeId); const pkgInfo = this.getNodePkg(nodeId); if (parentNodesIds.length === 0) { return [[pkgInfo]]; } const allPaths = []; ancestors = ancestors.concat(nodeId); const limit = opts.limit; for (const id of parentNodesIds) { if (ancestors.includes(id)) continue; const pathsFromNodeToRoot = this.pathsFromNodeToRoot(id, ancestors, opts); pathsFromNodeToRoot.forEach((path) => allPaths.push([pkgInfo].concat(path))); if (limit && allPaths.length >= limit) { break; } } return allPaths; } countNodePathsToRoot(nodeId, ancestors = []) { if (ancestors.includes(nodeId)) { return 0; } if (this._countNodePathsToRootCache.has(nodeId)) { return this._countNodePathsToRootCache.get(nodeId) || 0; } const parentNodesIds = this.getNodeParentsNodeIds(nodeId); if (parentNodesIds.length === 0) { this._countNodePathsToRootCache.set(nodeId, 1); return 1; } ancestors = ancestors.concat(nodeId); const count = parentNodesIds.reduce((acc, parentNodeId) => { return acc + this.countNodePathsToRoot(parentNodeId, ancestors); }, 0); this._countNodePathsToRootCache.set(nodeId, count); return count; } } exports.DepGraphImpl = DepGraphImpl; DepGraphImpl.SCHEMA_VERSION = '1.2.0'; //# sourceMappingURL=dep-graph.js.map /***/ }), /***/ 17058: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CustomError = void 0; class CustomError extends Error { constructor(message) { super(message); Object.setPrototypeOf(this, CustomError.prototype); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; } } exports.CustomError = CustomError; //# sourceMappingURL=custom-error.js.map /***/ }), /***/ 93970: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ValidationError = void 0; const validation_error_1 = __webpack_require__(21202); Object.defineProperty(exports, "ValidationError", ({ enumerable: true, get: function () { return validation_error_1.ValidationError; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 21202: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ValidationError = void 0; const custom_error_1 = __webpack_require__(17058); class ValidationError extends custom_error_1.CustomError { constructor(message) { super(message); Object.setPrototypeOf(this, ValidationError.prototype); } } exports.ValidationError = ValidationError; //# sourceMappingURL=validation-error.js.map /***/ }), /***/ 30555: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.validateGraph = void 0; const graphlib = __webpack_require__(61009); const errors_1 = __webpack_require__(93970); function assert(condition, msg) { if (!condition) { throw new errors_1.ValidationError(msg); } } function validateGraph(graph, rootNodeId, pkgs, pkgNodes) { assert((graph.predecessors(rootNodeId) || []).length === 0, `"${rootNodeId}" is not really the root`); const reachableFromRoot = graphlib.alg.postorder(graph, [rootNodeId]); const nodeIds = graph.nodes(); assert(JSON.stringify(nodeIds.sort()) === JSON.stringify(reachableFromRoot.sort()), 'not all graph nodes are reachable from root'); const pkgIds = Object.keys(pkgs); const pkgsWithoutInstances = pkgIds.filter((pkgId) => !pkgNodes[pkgId] || pkgNodes[pkgId].size === 0); assert(pkgsWithoutInstances.length === 0, 'not all pkgs have instance nodes'); } exports.validateGraph = validateGraph; //# sourceMappingURL=validate-graph.js.map /***/ }), /***/ 46434: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.dfs = void 0; const each = __webpack_require__(43590); /* * A helper that preforms a pre- or post-order traversal on the input graph * and returns the nodes in the order they were visited. If the graph is * undirected then this algorithm will navigate using neighbors. If the graph * is directed then this algorithm will navigate using successors. * * Order must be one of "pre" or "post". */ function dfs(g, vs, order) { if (!Array.isArray(vs)) { vs = [vs]; } const navigation = (g.isDirected() ? g.successors : g.neighbors).bind(g); const acc = []; const visited = {}; each(vs, (v) => { if (!g.hasNode(v)) { throw new Error('Graph does not have node: ' + v); } doDfs(g, v, order === 'post', visited, navigation, acc); }); return acc; } exports.dfs = dfs; function doDfs(g, v, postorder, visited, navigation, acc) { if (!(v in visited)) { visited[v] = true; if (!postorder) { acc.push(v); } each(navigation(v), function (w) { doDfs(g, w, postorder, visited, navigation, acc); }); if (postorder) { acc.push(v); } } } //# sourceMappingURL=dfs.js.map /***/ }), /***/ 98540: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isAcyclic = void 0; const topsort_1 = __webpack_require__(51751); function isAcyclic(g) { try { topsort_1.topsort(g); } catch (e) { if (e instanceof topsort_1.CycleException) { return false; } throw e; } return true; } exports.isAcyclic = isAcyclic; //# sourceMappingURL=is-acyclic.js.map /***/ }), /***/ 73077: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.postorder = void 0; const dfs_1 = __webpack_require__(46434); function postorder(g, vs) { return dfs_1.dfs(g, vs, 'post'); } exports.postorder = postorder; //# sourceMappingURL=postorder.js.map /***/ }), /***/ 51751: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CycleException = exports.topsort = void 0; const each = __webpack_require__(43590); const size = __webpack_require__(27946); function topsort(g) { const visited = {}; const stack = {}; const results = []; function visit(node) { if (node in stack) { throw new CycleException(); } if (!(node in visited)) { stack[node] = true; visited[node] = true; each(g.predecessors(node), visit); delete stack[node]; results.push(node); } } each(g.sinks(), visit); if (size(visited) !== g.nodeCount()) { throw new CycleException(); } return results; } exports.topsort = topsort; class CycleException extends Error { } exports.CycleException = CycleException; //# sourceMappingURL=topsort.js.map /***/ }), /***/ 79331: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Graph = void 0; /* eslint-disable prefer-rest-params */ /* eslint-disable @typescript-eslint/no-this-alias */ const constant = __webpack_require__(4254); const each = __webpack_require__(43590); const _filter = __webpack_require__(43590); const isEmpty = __webpack_require__(99245); const isFunction = __webpack_require__(98423); const isUndefined = __webpack_require__(28801); const keys = __webpack_require__(44799); const reduce = __webpack_require__(34766); const union = __webpack_require__(96744); const values = __webpack_require__(17720); const DEFAULT_EDGE_NAME = '\x00'; const GRAPH_NODE = '\x00'; const EDGE_KEY_DELIM = '\x01'; // Implementation notes: // // * Node id query functions should return string ids for the nodes // * Edge id query functions should return an "edgeObj", edge object, that is // composed of enough information to uniquely identify an edge: {v, w, name}. // * Internally we use an "edgeId", a stringified form of the edgeObj, to // reference edges. This is because we need a performant way to look these // edges up and, object properties, which have string keys, are the closest // we're going to get to a performant hashtable in JavaScript. class Graph { constructor(opts) { var _a, _b, _c; /* Number of nodes in the graph. Should only be changed by the implementation. */ this._nodeCount = 0; /* Number of edges in the graph. Should only be changed by the implementation. */ this._edgeCount = 0; this._isDirected = (_a = opts === null || opts === void 0 ? void 0 : opts.directed) !== null && _a !== void 0 ? _a : true; this._isMultigraph = (_b = opts === null || opts === void 0 ? void 0 : opts.multigraph) !== null && _b !== void 0 ? _b : false; this._isCompound = (_c = opts === null || opts === void 0 ? void 0 : opts.compound) !== null && _c !== void 0 ? _c : false; // Label for the graph itself this._label = undefined; // Defaults to be set when creating a new node this._defaultNodeLabelFn = constant(undefined); // Defaults to be set when creating a new edge this._defaultEdgeLabelFn = constant(undefined); // v -> label this._nodes = {}; if (this._isCompound) { // v -> parent this._parent = {}; // v -> children this._children = {}; this._children[GRAPH_NODE] = {}; } // v -> edgeObj this._in = {}; // u -> v -> Number this._preds = {}; // v -> edgeObj this._out = {}; // v -> w -> Number this._sucs = {}; // e -> edgeObj this._edgeObjs = {}; // e -> label this._edgeLabels = {}; } /* === Graph functions ========= */ isDirected() { return this._isDirected; } isMultigraph() { return this._isMultigraph; } isCompound() { return this._isCompound; } setGraph(label) { this._label = label; return this; } graph() { return this._label; } /* === Node functions ========== */ setDefaultNodeLabel(newDefault) { if (!isFunction(newDefault)) { newDefault = constant(newDefault); } this._defaultNodeLabelFn = newDefault; return this; } nodeCount() { return this._nodeCount; } nodes() { return keys(this._nodes); } sources() { const self = this; return _filter(this.nodes(), function (v) { return isEmpty(self._in[v]); }); } sinks() { const self = this; return _filter(this.nodes(), function (v) { return isEmpty(self._out[v]); }); } setNodes(vs, value) { const args = arguments; const self = this; each(vs, function (v) { if (args.length > 1) { self.setNode(v, value); } else { self.setNode(v); } }); return this; } setNode(v, value) { if (v in this._nodes) { if (arguments.length > 1) { this._nodes[v] = value; } return this; } this._nodes[v] = arguments.length > 1 ? value : this._defaultNodeLabelFn(v); if (this._isCompound) { this._parent[v] = GRAPH_NODE; this._children[v] = {}; this._children[GRAPH_NODE][v] = true; } this._in[v] = {}; this._preds[v] = {}; this._out[v] = {}; this._sucs[v] = {}; ++this._nodeCount; return this; } node(v) { return this._nodes[v]; } hasNode(v) { return v in this._nodes; } removeNode(v) { const self = this; if (v in this._nodes) { const removeEdge = function (e) { self.removeEdge(self._edgeObjs[e]); }; delete this._nodes[v]; if (this._isCompound) { this._removeFromParentsChildList(v); delete this._parent[v]; each(this.children(v), function (child) { self.setParent(child); }); delete this._children[v]; } each(keys(this._in[v]), removeEdge); delete this._in[v]; delete this._preds[v]; each(keys(this._out[v]), removeEdge); delete this._out[v]; delete this._sucs[v]; --this._nodeCount; } return this; } setParent(v, parent) { if (!this._isCompound) { throw new Error('Cannot set parent in a non-compound graph'); } if (isUndefined(parent)) { parent = GRAPH_NODE; } else { // Coerce parent to string parent += ''; for (let ancestor = parent; !isUndefined(ancestor); ancestor = this.parent(ancestor)) { if (ancestor === v) { throw new Error('Setting ' + parent + ' as parent of ' + v + ' would create a cycle'); } } this.setNode(parent); } this.setNode(v); this._removeFromParentsChildList(v); this._parent[v] = parent; this._children[parent][v] = true; return this; } _removeFromParentsChildList(v) { delete this._children[this._parent[v]][v]; } parent(v) { if (this._isCompound) { const parent = this._parent[v]; if (parent !== GRAPH_NODE) { return parent; } } } children(v) { if (isUndefined(v)) { v = GRAPH_NODE; } if (this._isCompound) { const children = this._children[v]; if (children) { return keys(children); } } else if (v === GRAPH_NODE) { return this.nodes(); } else if (this.hasNode(v)) { return []; } } predecessors(v) { const predsV = this._preds[v]; if (predsV) { return keys(predsV); } } successors(v) { const sucsV = this._sucs[v]; if (sucsV) { return keys(sucsV); } } neighbors(v) { const preds = this.predecessors(v); if (preds) { return union(preds, this.successors(v)); } } isLeaf(v) { let neighbors; if (this.isDirected()) { neighbors = this.successors(v); } else { neighbors = this.neighbors(v); } return neighbors.length === 0; } filterNodes(filter) { const copy = new Graph({ directed: this._isDirected, multigraph: this._isMultigraph, compound: this._isCompound, }); copy.setGraph(this.graph()); const self = this; each(this._nodes, function (value, v) { if (filter(v)) { copy.setNode(v, value); } }); each(this._edgeObjs, function (e) { if (copy.hasNode(e.v) && copy.hasNode(e.w)) { copy.setEdge(e, self.edge(e)); } }); const parents = {}; function findParent(v) { const parent = self.parent(v); if (parent === undefined || copy.hasNode(parent)) { parents[v] = parent; return parent; } else if (parent in parents) { return parents[parent]; } else { return findParent(parent); } } if (this._isCompound) { each(copy.nodes(), function (v) { copy.setParent(v, findParent(v)); }); } return copy; } /* === Edge functions ========== */ setDefaultEdgeLabel(newDefault) { if (!isFunction(newDefault)) { newDefault = constant(newDefault); } this._defaultEdgeLabelFn = newDefault; return this; } edgeCount() { return this._edgeCount; } edges() { return values(this._edgeObjs); } setPath(vs, value) { const self = this; const args = arguments; reduce(vs, function (v, w) { if (args.length > 1) { self.setEdge(v, w, value); } else { self.setEdge(v, w); } return w; }); return this; } // eslint-disable-next-line @typescript-eslint/no-unused-vars setEdge(...args) { let v, w, name, value; let valueSpecified = false; const arg0 = arguments[0]; if (typeof arg0 === 'object' && arg0 !== null && 'v' in arg0) { v = arg0.v; w = arg0.w; name = arg0.name; if (arguments.length === 2) { value = arguments[1]; valueSpecified = true; } } else { v = arg0; w = arguments[1]; name = arguments[3]; if (arguments.length > 2) { value = arguments[2]; valueSpecified = true; } } v = '' + v; w = '' + w; if (!isUndefined(name)) { name = '' + name; } const e = edgeArgsToId(this._isDirected, v, w, name); if (e in this._edgeLabels) { if (valueSpecified) { this._edgeLabels[e] = value; } return this; } if (!isUndefined(name) && !this._isMultigraph) { throw new Error('Cannot set a named edge when isMultigraph = false'); } // It didn't exist, so we need to create it. // First ensure the nodes exist. this.setNode(v); this.setNode(w); this._edgeLabels[e] = valueSpecified ? value : this._defaultEdgeLabelFn(v, w, name); const edgeObj = edgeArgsToObj(this._isDirected, v, w, name); // Ensure we add undirected edges in a consistent way. v = edgeObj.v; w = edgeObj.w; Object.freeze(edgeObj); this._edgeObjs[e] = edgeObj; incrementOrInitEntry(this._preds[w], v); incrementOrInitEntry(this._sucs[v], w); this._in[w][e] = edgeObj; this._out[v][e] = edgeObj; this._edgeCount++; return this; } edge(v, w, name) { const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); return this._edgeLabels[e]; } hasEdge(v, w, name) { const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); return e in this._edgeLabels; } removeEdge(v, w, name) { const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); const edge = this._edgeObjs[e]; if (edge) { v = edge.v; w = edge.w; delete this._edgeLabels[e]; delete this._edgeObjs[e]; decrementOrRemoveEntry(this._preds[w], v); decrementOrRemoveEntry(this._sucs[v], w); delete this._in[w][e]; delete this._out[v][e]; this._edgeCount--; } return this; } inEdges(v, u) { const inV = this._in[v]; if (inV) { const edges = values(inV); if (!u) { return edges; } return _filter(edges, function (edge) { return edge.v === u; }); } } outEdges(v, w) { const outV = this._out[v]; if (outV) { const edges = values(outV); if (!w) { return edges; } return _filter(edges, function (edge) { return edge.w === w; }); } } nodeEdges(v, w) { const inEdges = this.inEdges(v, w); if (inEdges) { return inEdges.concat(this.outEdges(v, w)); } } } exports.Graph = Graph; function incrementOrInitEntry(map, k) { if (map[k]) { map[k]++; } else { map[k] = 1; } } function decrementOrRemoveEntry(map, k) { if (!--map[k]) { delete map[k]; } } function edgeArgsToId(isDirected, v_, w_, name) { let v = '' + v_; let w = '' + w_; if (!isDirected && v > w) { const tmp = v; v = w; w = tmp; } return (v + EDGE_KEY_DELIM + w + EDGE_KEY_DELIM + (isUndefined(name) ? DEFAULT_EDGE_NAME : name)); } function edgeArgsToObj(isDirected, v_, w_, name) { let v = '' + v_; let w = '' + w_; if (!isDirected && v > w) { const tmp = v; v = w; w = tmp; } const edgeObj = { v: v, w: w }; if (name) { edgeObj.name = name; } return edgeObj; } function edgeObjToId(isDirected, edgeObj) { return edgeArgsToId(isDirected, edgeObj.v, edgeObj.w, edgeObj.name); } //# sourceMappingURL=graph.js.map /***/ }), /***/ 61009: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.alg = exports.Graph = void 0; var graph_1 = __webpack_require__(79331); Object.defineProperty(exports, "Graph", ({ enumerable: true, get: function () { return graph_1.Graph; } })); const is_acyclic_1 = __webpack_require__(98540); const postorder_1 = __webpack_require__(73077); exports.alg = { isAcyclic: is_acyclic_1.isAcyclic, postorder: postorder_1.postorder, }; //# sourceMappingURL=index.js.map /***/ }), /***/ 38115: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.legacy = exports.Errors = exports.DepGraphBuilder = exports.createFromJSON = void 0; var create_from_json_1 = __webpack_require__(88837); Object.defineProperty(exports, "createFromJSON", ({ enumerable: true, get: function () { return create_from_json_1.createFromJSON; } })); var builder_1 = __webpack_require__(33409); Object.defineProperty(exports, "DepGraphBuilder", ({ enumerable: true, get: function () { return builder_1.DepGraphBuilder; } })); const Errors = __webpack_require__(93970); exports.Errors = Errors; const legacy = __webpack_require__(40878); exports.legacy = legacy; //# sourceMappingURL=index.js.map /***/ }), /***/ 37423: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.partitionCycles = exports.getCycle = void 0; function getCycle(ancestors, nodeId) { if (!ancestors.includes(nodeId)) { return null; } // first item is where the cycle starts and ends. return ancestors.slice(ancestors.indexOf(nodeId)); } exports.getCycle = getCycle; function partitionCycles(nodeId, allCyclesTheNodeIsPartOf) { const cyclesStartWithThisNode = []; const cyclesWithThisNode = []; for (const cycle of allCyclesTheNodeIsPartOf) { const nodeStartsCycle = cycle[0] === nodeId; if (nodeStartsCycle) { cyclesStartWithThisNode.push(cycle); } else { cyclesWithThisNode.push(cycle); } } return { cyclesStartWithThisNode, cyclesWithThisNode }; } exports.partitionCycles = partitionCycles; //# sourceMappingURL=cycles.js.map /***/ }), /***/ 40878: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.graphToDepTree = exports.depTreeToGraph = void 0; const crypto = __webpack_require__(6113); const event_loop_spinner_1 = __webpack_require__(77158); const builder_1 = __webpack_require__(33409); const objectHash = __webpack_require__(18323); const cycles_1 = __webpack_require__(37423); const memiozation_1 = __webpack_require__(19488); function addLabel(dep, key, value) { if (!dep.labels) { dep.labels = {}; } dep.labels[key] = value; } /** * @deprecated Don't use dep trees as an intermediate step, because they are * large structures, resulting in high memory usage and high CPU costs from * serializing / deserializing. Instead, create a graph directly with * {@link DepGraphBuilder} */ async function depTreeToGraph(depTree, pkgManagerName) { const rootPkg = { name: depTree.name, version: depTree.version || undefined, }; const pkgManagerInfo = { name: pkgManagerName, }; const targetOS = depTree.targetOS; if (targetOS) { pkgManagerInfo.repositories = [ { alias: `${targetOS.name}:${targetOS.version}`, }, ]; } const builder = new builder_1.DepGraphBuilder(pkgManagerInfo, rootPkg); await buildGraph(builder, depTree, depTree.name, true); const depGraph = await builder.build(); return shortenNodeIds(depGraph); } exports.depTreeToGraph = depTreeToGraph; async function buildGraph(builder, depTree, pkgName, isRoot = false, memoizationMap = new Map()) { if (memoizationMap.has(depTree)) { return memoizationMap.get(depTree); } const getNodeId = (name, version, hashId) => `${name}@${version || ''}|${hashId}`; const depNodesIds = []; const hash = crypto.createHash('sha1'); if (depTree.versionProvenance) { hash.update(objectHash(depTree.versionProvenance)); } if (depTree.labels) { hash.update(objectHash(depTree.labels)); } const deps = depTree.dependencies || {}; // filter-out invalid null deps (shouldn't happen - but did...) const depNames = Object.keys(deps).filter((d) => !!deps[d]); for (const depName of depNames.sort()) { const dep = deps[depName]; const subtreeHash = await buildGraph(builder, dep, depName, false, memoizationMap); const depPkg = { name: depName, version: dep.version, }; const depNodeId = getNodeId(depPkg.name, depPkg.version, subtreeHash); depNodesIds.push(depNodeId); const nodeInfo = {}; if (dep.versionProvenance) { nodeInfo.versionProvenance = dep.versionProvenance; } if (dep.labels) { nodeInfo.labels = dep.labels; } builder.addPkgNode(depPkg, depNodeId, nodeInfo); hash.update(depNodeId); } const treeHash = hash.digest('hex'); let pkgNodeId; if (isRoot) { pkgNodeId = builder.rootNodeId; } else { // we don't assume depTree has a .name to support output of `npm list --json` const pkg = { name: pkgName, version: depTree.version, }; pkgNodeId = getNodeId(pkg.name, pkg.version, treeHash); const nodeInfo = {}; if (depTree.versionProvenance) { nodeInfo.versionProvenance = depTree.versionProvenance; } if (depTree.labels) { nodeInfo.labels = depTree.labels; } builder.addPkgNode(pkg, pkgNodeId, nodeInfo); } for (const depNodeId of depNodesIds) { builder.connectDep(pkgNodeId, depNodeId); } if (depNodesIds.length > 0 && event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } memoizationMap.set(depTree, treeHash); return treeHash; } async function shortenNodeIds(depGraph) { const builder = new builder_1.DepGraphBuilder(depGraph.pkgManager, depGraph.rootPkg); const nodesMap = {}; // create nodes with shorter ids for (const pkg of depGraph.getPkgs()) { const nodeIds = depGraph.getPkgNodeIds(pkg); for (let i = 0; i < nodeIds.length; i++) { const nodeId = nodeIds[i]; if (nodeId === depGraph.rootNodeId) { continue; } const nodeInfo = depGraph.getNode(nodeId); let newNodeId; if (nodeIds.length === 1) { newNodeId = `${trimAfterLastSep(nodeId, '|')}`; } else { newNodeId = `${trimAfterLastSep(nodeId, '|')}|${i + 1}`; } nodesMap[nodeId] = newNodeId; builder.addPkgNode(pkg, newNodeId, nodeInfo); } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } // connect nodes for (const pkg of depGraph.getPkgs()) { for (const nodeId of depGraph.getPkgNodeIds(pkg)) { for (const depNodeId of depGraph.getNodeDepsNodeIds(nodeId)) { const parentNode = nodesMap[nodeId] || nodeId; const childNode = nodesMap[depNodeId] || depNodeId; builder.connectDep(parentNode, childNode); } } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } return builder.build(); } /** * @deprecated Don't use dep trees. You should adapt your code to use graphs, * and enhance the dep-graph library if there is missing functionality from * the graph structure */ async function graphToDepTree(depGraphInterface, pkgType, opts = { deduplicateWithinTopLevelDeps: false }) { const depGraph = depGraphInterface; const [depTree] = await buildSubtree(depGraph, depGraph.rootNodeId, opts.deduplicateWithinTopLevelDeps ? null : false); depTree.type = depGraph.pkgManager.name; depTree.packageFormatVersion = constructPackageFormatVersion(pkgType); const targetOS = constructTargetOS(depGraph); if (targetOS) { depTree.targetOS = targetOS; } return depTree; } exports.graphToDepTree = graphToDepTree; function constructPackageFormatVersion(pkgType) { if (pkgType === 'maven') { pkgType = 'mvn'; } return `${pkgType}:0.0.1`; } function constructTargetOS(depGraph) { if (['apk', 'apt', 'deb', 'rpm', 'linux'].indexOf(depGraph.pkgManager.name) === -1) { // .targetOS is undefined unless its a linux pkgManager return; } if (!depGraph.pkgManager.repositories || !depGraph.pkgManager.repositories.length || !depGraph.pkgManager.repositories[0].alias) { throw new Error('Incomplete .pkgManager, could not create .targetOS'); } const [name, version] = depGraph.pkgManager.repositories[0].alias.split(':'); return { name, version }; } async function buildSubtree(depGraph, nodeId, maybeDeduplicationSet = false, // false = disabled; null = not in deduplication scope yet ancestors = [], memoizationMap = new Map()) { if (!maybeDeduplicationSet) { const memoizedDepTree = memiozation_1.getMemoizedDepTree(nodeId, ancestors, memoizationMap); if (memoizedDepTree) { return [memoizedDepTree, undefined]; } } const isRoot = nodeId === depGraph.rootNodeId; const nodePkg = depGraph.getNodePkg(nodeId); const nodeInfo = depGraph.getNode(nodeId); const depTree = {}; depTree.name = nodePkg.name; depTree.version = nodePkg.version; if (nodeInfo.versionProvenance) { depTree.versionProvenance = nodeInfo.versionProvenance; } if (nodeInfo.labels) { depTree.labels = Object.assign({}, nodeInfo.labels); } const depInstanceIds = depGraph.getNodeDepsNodeIds(nodeId); if (!depInstanceIds || depInstanceIds.length === 0) { memoizationMap.set(nodeId, { depTree }); return [depTree, undefined]; } const cycle = cycles_1.getCycle(ancestors, nodeId); if (cycle) { // This node starts a cycle and now it's the second visit. addLabel(depTree, 'pruned', 'cyclic'); return [depTree, [cycle]]; } if (maybeDeduplicationSet) { if (maybeDeduplicationSet.has(nodeId)) { if (depInstanceIds.length > 0) { addLabel(depTree, 'pruned', 'true'); } return [depTree, undefined]; } maybeDeduplicationSet.add(nodeId); } const cycles = []; for (const depInstId of depInstanceIds) { // Deduplication of nodes occurs only within a scope of a top-level dependency. // Therefore, every top-level dep gets an independent set to track duplicates. if (isRoot && maybeDeduplicationSet !== false) { maybeDeduplicationSet = new Set(); } const [subtree, subtreeCycles] = await buildSubtree(depGraph, depInstId, maybeDeduplicationSet, ancestors.concat(nodeId), memoizationMap); if (subtreeCycles) { for (const cycle of subtreeCycles) { cycles.push(cycle); } } if (!subtree) { continue; } if (!depTree.dependencies) { depTree.dependencies = {}; } depTree.dependencies[subtree.name] = subtree; } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } const partitionedCycles = cycles_1.partitionCycles(nodeId, cycles); memiozation_1.memoize(nodeId, memoizationMap, depTree, partitionedCycles); return [depTree, partitionedCycles.cyclesWithThisNode]; } function trimAfterLastSep(str, sep) { return str.slice(0, str.lastIndexOf(sep)); } //# sourceMappingURL=index.js.map /***/ }), /***/ 19488: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getMemoizedDepTree = exports.memoize = void 0; function memoize(nodeId, memoizationMap, depTree, partitionedCycles) { const { cyclesStartWithThisNode, cyclesWithThisNode } = partitionedCycles; if (cyclesStartWithThisNode.length > 0) { const cycleNodeIds = new Set(...cyclesStartWithThisNode); memoizationMap.set(nodeId, { depTree, cycleNodeIds }); } else if (cyclesWithThisNode.length === 0) { memoizationMap.set(nodeId, { depTree }); } // Don't memoize nodes in cycles (cyclesWithThisNode.length > 0) } exports.memoize = memoize; function getMemoizedDepTree(nodeId, ancestors, memoizationMap) { if (!memoizationMap.has(nodeId)) return null; const { depTree, cycleNodeIds } = memoizationMap.get(nodeId); if (!cycleNodeIds) return depTree; const ancestorsArePartOfTheCycle = ancestors.some((nodeId) => cycleNodeIds.has(nodeId)); return ancestorsArePartOfTheCycle ? null : depTree; } exports.getMemoizedDepTree = getMemoizedDepTree; //# sourceMappingURL=memiozation.js.map /***/ }), /***/ 50737: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // A linked list to keep track of recently-used-ness const Yallist = __webpack_require__(53141) const MAX = Symbol('max') const LENGTH = Symbol('length') const LENGTH_CALCULATOR = Symbol('lengthCalculator') const ALLOW_STALE = Symbol('allowStale') const MAX_AGE = Symbol('maxAge') const DISPOSE = Symbol('dispose') const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') const LRU_LIST = Symbol('lruList') const CACHE = Symbol('cache') const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') const naiveLength = () => 1 // lruList is a yallist where the head is the youngest // item, and the tail is the oldest. the list contains the Hit // objects as the entries. // Each Hit object has a reference to its Yallist.Node. This // never changes. // // cache is a Map (or PseudoMap) that matches the keys to // the Yallist.Node object. class LRUCache { constructor (options) { if (typeof options === 'number') options = { max: options } if (!options) options = {} if (options.max && (typeof options.max !== 'number' || options.max < 0)) throw new TypeError('max must be a non-negative number') // Kind of weird to have a default max of Infinity, but oh well. const max = this[MAX] = options.max || Infinity const lc = options.length || naiveLength this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc this[ALLOW_STALE] = options.stale || false if (options.maxAge && typeof options.maxAge !== 'number') throw new TypeError('maxAge must be a number') this[MAX_AGE] = options.maxAge || 0 this[DISPOSE] = options.dispose this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false this.reset() } // resize the cache when the max changes. set max (mL) { if (typeof mL !== 'number' || mL < 0) throw new TypeError('max must be a non-negative number') this[MAX] = mL || Infinity trim(this) } get max () { return this[MAX] } set allowStale (allowStale) { this[ALLOW_STALE] = !!allowStale } get allowStale () { return this[ALLOW_STALE] } set maxAge (mA) { if (typeof mA !== 'number') throw new TypeError('maxAge must be a non-negative number') this[MAX_AGE] = mA trim(this) } get maxAge () { return this[MAX_AGE] } // resize the cache when the lengthCalculator changes. set lengthCalculator (lC) { if (typeof lC !== 'function') lC = naiveLength if (lC !== this[LENGTH_CALCULATOR]) { this[LENGTH_CALCULATOR] = lC this[LENGTH] = 0 this[LRU_LIST].forEach(hit => { hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) this[LENGTH] += hit.length }) } trim(this) } get lengthCalculator () { return this[LENGTH_CALCULATOR] } get length () { return this[LENGTH] } get itemCount () { return this[LRU_LIST].length } rforEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].tail; walker !== null;) { const prev = walker.prev forEachStep(this, fn, walker, thisp) walker = prev } } forEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].head; walker !== null;) { const next = walker.next forEachStep(this, fn, walker, thisp) walker = next } } keys () { return this[LRU_LIST].toArray().map(k => k.key) } values () { return this[LRU_LIST].toArray().map(k => k.value) } reset () { if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) { this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) } this[CACHE] = new Map() // hash of items by key this[LRU_LIST] = new Yallist() // list of items in order of use recency this[LENGTH] = 0 // length of items in the list } dump () { return this[LRU_LIST].map(hit => isStale(this, hit) ? false : { k: hit.key, v: hit.value, e: hit.now + (hit.maxAge || 0) }).toArray().filter(h => h) } dumpLru () { return this[LRU_LIST] } set (key, value, maxAge) { maxAge = maxAge || this[MAX_AGE] if (maxAge && typeof maxAge !== 'number') throw new TypeError('maxAge must be a number') const now = maxAge ? Date.now() : 0 const len = this[LENGTH_CALCULATOR](value, key) if (this[CACHE].has(key)) { if (len > this[MAX]) { del(this, this[CACHE].get(key)) return false } const node = this[CACHE].get(key) const item = node.value // dispose of the old one before overwriting // split out into 2 ifs for better coverage tracking if (this[DISPOSE]) { if (!this[NO_DISPOSE_ON_SET]) this[DISPOSE](key, item.value) } item.now = now item.maxAge = maxAge item.value = value this[LENGTH] += len - item.length item.length = len this.get(key) trim(this) return true } const hit = new Entry(key, value, len, now, maxAge) // oversized objects fall out of cache automatically. if (hit.length > this[MAX]) { if (this[DISPOSE]) this[DISPOSE](key, value) return false } this[LENGTH] += hit.length this[LRU_LIST].unshift(hit) this[CACHE].set(key, this[LRU_LIST].head) trim(this) return true } has (key) { if (!this[CACHE].has(key)) return false const hit = this[CACHE].get(key).value return !isStale(this, hit) } get (key) { return get(this, key, true) } peek (key) { return get(this, key, false) } pop () { const node = this[LRU_LIST].tail if (!node) return null del(this, node) return node.value } del (key) { del(this, this[CACHE].get(key)) } load (arr) { // reset the cache this.reset() const now = Date.now() // A previous serialized cache has the most recent items first for (let l = arr.length - 1; l >= 0; l--) { const hit = arr[l] const expiresAt = hit.e || 0 if (expiresAt === 0) // the item was created without expiration in a non aged cache this.set(hit.k, hit.v) else { const maxAge = expiresAt - now // dont add already expired items if (maxAge > 0) { this.set(hit.k, hit.v, maxAge) } } } } prune () { this[CACHE].forEach((value, key) => get(this, key, false)) } } const get = (self, key, doUse) => { const node = self[CACHE].get(key) if (node) { const hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) return undefined } else { if (doUse) { if (self[UPDATE_AGE_ON_GET]) node.value.now = Date.now() self[LRU_LIST].unshiftNode(node) } } return hit.value } } const isStale = (self, hit) => { if (!hit || (!hit.maxAge && !self[MAX_AGE])) return false const diff = Date.now() - hit.now return hit.maxAge ? diff > hit.maxAge : self[MAX_AGE] && (diff > self[MAX_AGE]) } const trim = self => { if (self[LENGTH] > self[MAX]) { for (let walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) { // We know that we're about to delete this one, and also // what the next least recently used key will be, so just // go ahead and set it now. const prev = walker.prev del(self, walker) walker = prev } } } const del = (self, node) => { if (node) { const hit = node.value if (self[DISPOSE]) self[DISPOSE](hit.key, hit.value) self[LENGTH] -= hit.length self[CACHE].delete(hit.key) self[LRU_LIST].removeNode(node) } } class Entry { constructor (key, value, length, now, maxAge) { this.key = key this.value = value this.length = length this.now = now this.maxAge = maxAge || 0 } } const forEachStep = (self, fn, node, thisp) => { let hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) hit = undefined } if (hit) fn.call(thisp, hit.value, hit.key, self) } module.exports = LRUCache /***/ }), /***/ 18323: /***/ ((module, exports, __webpack_require__) => { "use strict"; var crypto = __webpack_require__(6113); /** * Exported function * * Options: * * - `algorithm` hash algo to be used by this instance: *'sha1', 'md5' * - `excludeValues` {true|*false} hash object keys, values ignored * - `encoding` hash encoding, supports 'buffer', '*hex', 'binary', 'base64' * - `ignoreUnknown` {true|*false} ignore unknown object types * - `replacer` optional function that replaces values before hashing * - `respectFunctionProperties` {*true|false} consider function properties when hashing * - `respectFunctionNames` {*true|false} consider 'name' property of functions for hashing * - `respectType` {*true|false} Respect special properties (prototype, constructor) * when hashing to distinguish between types * - `unorderedArrays` {true|*false} Sort all arrays before hashing * - `unorderedSets` {*true|false} Sort `Set` and `Map` instances before hashing * * = default * * @param {object} object value to hash * @param {object} options hashing options * @return {string} hash value * @api public */ exports = module.exports = objectHash; function objectHash(object, options){ options = applyDefaults(object, options); return hash(object, options); } /** * Exported sugar methods * * @param {object} object value to hash * @return {string} hash value * @api public */ exports.sha1 = function(object){ return objectHash(object); }; exports.keys = function(object){ return objectHash(object, {excludeValues: true, algorithm: 'sha1', encoding: 'hex'}); }; exports.MD5 = function(object){ return objectHash(object, {algorithm: 'md5', encoding: 'hex'}); }; exports.keysMD5 = function(object){ return objectHash(object, {algorithm: 'md5', encoding: 'hex', excludeValues: true}); }; // Internals var hashes = crypto.getHashes ? crypto.getHashes().slice() : ['sha1', 'md5']; hashes.push('passthrough'); var encodings = ['buffer', 'hex', 'binary', 'base64']; function applyDefaults(object, sourceOptions){ sourceOptions = sourceOptions || {}; // create a copy rather than mutating var options = {}; options.algorithm = sourceOptions.algorithm || 'sha1'; options.encoding = sourceOptions.encoding || 'hex'; options.excludeValues = sourceOptions.excludeValues ? true : false; options.algorithm = options.algorithm.toLowerCase(); options.encoding = options.encoding.toLowerCase(); options.ignoreUnknown = sourceOptions.ignoreUnknown !== true ? false : true; // default to false options.respectType = sourceOptions.respectType === false ? false : true; // default to true options.respectFunctionNames = sourceOptions.respectFunctionNames === false ? false : true; options.respectFunctionProperties = sourceOptions.respectFunctionProperties === false ? false : true; options.unorderedArrays = sourceOptions.unorderedArrays !== true ? false : true; // default to false options.unorderedSets = sourceOptions.unorderedSets === false ? false : true; // default to false options.unorderedObjects = sourceOptions.unorderedObjects === false ? false : true; // default to true options.replacer = sourceOptions.replacer || undefined; options.excludeKeys = sourceOptions.excludeKeys || undefined; if(typeof object === 'undefined') { throw new Error('Object argument required.'); } // if there is a case-insensitive match in the hashes list, accept it // (i.e. SHA256 for sha256) for (var i = 0; i < hashes.length; ++i) { if (hashes[i].toLowerCase() === options.algorithm.toLowerCase()) { options.algorithm = hashes[i]; } } if(hashes.indexOf(options.algorithm) === -1){ throw new Error('Algorithm "' + options.algorithm + '" not supported. ' + 'supported values: ' + hashes.join(', ')); } if(encodings.indexOf(options.encoding) === -1 && options.algorithm !== 'passthrough'){ throw new Error('Encoding "' + options.encoding + '" not supported. ' + 'supported values: ' + encodings.join(', ')); } return options; } /** Check if the given function is a native function */ function isNativeFunction(f) { if ((typeof f) !== 'function') { return false; } var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i; return exp.exec(Function.prototype.toString.call(f)) != null; } function hash(object, options) { var hashingStream; if (options.algorithm !== 'passthrough') { hashingStream = crypto.createHash(options.algorithm); } else { hashingStream = new PassThrough(); } if (typeof hashingStream.write === 'undefined') { hashingStream.write = hashingStream.update; hashingStream.end = hashingStream.update; } var hasher = typeHasher(options, hashingStream); hasher.dispatch(object); if (!hashingStream.update) { hashingStream.end(''); } if (hashingStream.digest) { return hashingStream.digest(options.encoding === 'buffer' ? undefined : options.encoding); } var buf = hashingStream.read(); if (options.encoding === 'buffer') { return buf; } return buf.toString(options.encoding); } /** * Expose streaming API * * @param {object} object Value to serialize * @param {object} options Options, as for hash() * @param {object} stream A stream to write the serializiation to * @api public */ exports.writeToStream = function(object, options, stream) { if (typeof stream === 'undefined') { stream = options; options = {}; } options = applyDefaults(object, options); return typeHasher(options, stream).dispatch(object); }; function typeHasher(options, writeTo, context){ context = context || []; var write = function(str) { if (writeTo.update) { return writeTo.update(str, 'utf8'); } else { return writeTo.write(str, 'utf8'); } }; return { dispatch: function(value){ if (options.replacer) { value = options.replacer(value); } var type = typeof value; if (value === null) { type = 'null'; } //console.log("[DEBUG] Dispatch: ", value, "->", type, " -> ", "_" + type); return this['_' + type](value); }, _object: function(object) { var pattern = (/\[object (.*)\]/i); var objString = Object.prototype.toString.call(object); var objType = pattern.exec(objString); if (!objType) { // object type did not match [object ...] objType = 'unknown:[' + objString + ']'; } else { objType = objType[1]; // take only the class name } objType = objType.toLowerCase(); var objectNumber = null; if ((objectNumber = context.indexOf(object)) >= 0) { return this.dispatch('[CIRCULAR:' + objectNumber + ']'); } else { context.push(object); } if (typeof Buffer !== 'undefined' && Buffer.isBuffer && Buffer.isBuffer(object)) { write('buffer:'); return write(object); } if(objType !== 'object' && objType !== 'function' && objType !== 'asyncfunction') { if(this['_' + objType]) { this['_' + objType](object); } else if (options.ignoreUnknown) { return write('[' + objType + ']'); } else { throw new Error('Unknown object type "' + objType + '"'); } }else{ var keys = Object.keys(object); if (options.unorderedObjects) { keys = keys.sort(); } // Make sure to incorporate special properties, so // Types with different prototypes will produce // a different hash and objects derived from // different functions (`new Foo`, `new Bar`) will // produce different hashes. // We never do this for native functions since some // seem to break because of that. if (options.respectType !== false && !isNativeFunction(object)) { keys.splice(0, 0, 'prototype', '__proto__', 'constructor'); } if (options.excludeKeys) { keys = keys.filter(function(key) { return !options.excludeKeys(key); }); } write('object:' + keys.length + ':'); var self = this; return keys.forEach(function(key){ self.dispatch(key); write(':'); if(!options.excludeValues) { self.dispatch(object[key]); } write(','); }); } }, _array: function(arr, unordered){ unordered = typeof unordered !== 'undefined' ? unordered : options.unorderedArrays !== false; // default to options.unorderedArrays var self = this; write('array:' + arr.length + ':'); if (!unordered || arr.length <= 1) { return arr.forEach(function(entry) { return self.dispatch(entry); }); } // the unordered case is a little more complicated: // since there is no canonical ordering on objects, // i.e. {a:1} < {a:2} and {a:1} > {a:2} are both false, // we first serialize each entry using a PassThrough stream // before sorting. // also: we can’t use the same context array for all entries // since the order of hashing should *not* matter. instead, // we keep track of the additions to a copy of the context array // and add all of them to the global context array when we’re done var contextAdditions = []; var entries = arr.map(function(entry) { var strm = new PassThrough(); var localContext = context.slice(); // make copy var hasher = typeHasher(options, strm, localContext); hasher.dispatch(entry); // take only what was added to localContext and append it to contextAdditions contextAdditions = contextAdditions.concat(localContext.slice(context.length)); return strm.read().toString(); }); context = context.concat(contextAdditions); entries.sort(); return this._array(entries, false); }, _date: function(date){ return write('date:' + date.toJSON()); }, _symbol: function(sym){ return write('symbol:' + sym.toString()); }, _error: function(err){ return write('error:' + err.toString()); }, _boolean: function(bool){ return write('bool:' + bool.toString()); }, _string: function(string){ write('string:' + string.length + ':'); write(string.toString()); }, _function: function(fn){ write('fn:'); if (isNativeFunction(fn)) { this.dispatch('[native]'); } else { this.dispatch(fn.toString()); } if (options.respectFunctionNames !== false) { // Make sure we can still distinguish native functions // by their name, otherwise String and Function will // have the same hash this.dispatch("function-name:" + String(fn.name)); } if (options.respectFunctionProperties) { this._object(fn); } }, _number: function(number){ return write('number:' + number.toString()); }, _xml: function(xml){ return write('xml:' + xml.toString()); }, _null: function() { return write('Null'); }, _undefined: function() { return write('Undefined'); }, _regexp: function(regex){ return write('regex:' + regex.toString()); }, _uint8array: function(arr){ write('uint8array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _uint8clampedarray: function(arr){ write('uint8clampedarray:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _int8array: function(arr){ write('uint8array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _uint16array: function(arr){ write('uint16array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _int16array: function(arr){ write('uint16array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _uint32array: function(arr){ write('uint32array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _int32array: function(arr){ write('uint32array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _float32array: function(arr){ write('float32array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _float64array: function(arr){ write('float64array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _arraybuffer: function(arr){ write('arraybuffer:'); return this.dispatch(new Uint8Array(arr)); }, _url: function(url) { return write('url:' + url.toString(), 'utf8'); }, _map: function(map) { write('map:'); var arr = Array.from(map); return this._array(arr, options.unorderedSets !== false); }, _set: function(set) { write('set:'); var arr = Array.from(set); return this._array(arr, options.unorderedSets !== false); }, _file: function(file) { write('file:'); return this.dispatch([file.name, file.size, file.type, file.lastModfied]); }, _blob: function() { if (options.ignoreUnknown) { return write('[blob]'); } throw Error('Hashing Blob objects is currently not supported\n' + '(see https://github.com/puleos/object-hash/issues/26)\n' + 'Use "options.replacer" or "options.ignoreUnknown"\n'); }, _domwindow: function() { return write('domwindow'); }, _bigint: function(number){ return write('bigint:' + number.toString()); }, /* Node.js standard native objects */ _process: function() { return write('process'); }, _timer: function() { return write('timer'); }, _pipe: function() { return write('pipe'); }, _tcp: function() { return write('tcp'); }, _udp: function() { return write('udp'); }, _tty: function() { return write('tty'); }, _statwatcher: function() { return write('statwatcher'); }, _securecontext: function() { return write('securecontext'); }, _connection: function() { return write('connection'); }, _zlib: function() { return write('zlib'); }, _context: function() { return write('context'); }, _nodescript: function() { return write('nodescript'); }, _httpparser: function() { return write('httpparser'); }, _dataview: function() { return write('dataview'); }, _signal: function() { return write('signal'); }, _fsevent: function() { return write('fsevent'); }, _tlswrap: function() { return write('tlswrap'); }, }; } // Mini-implementation of stream.PassThrough // We are far from having need for the full implementation, and we can // make assumptions like "many writes, then only one final read" // and we can ignore encoding specifics function PassThrough() { return { buf: '', write: function(b) { this.buf += b; }, end: function(b) { this.buf += b; }, read: function() { return this.buf; } }; } /***/ }), /***/ 58775: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const ANY = Symbol('SemVer ANY') // hoisted class for cyclic dependency class Comparator { static get ANY () { return ANY } constructor (comp, options) { options = parseOptions(options) if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } comp = comp.trim().split(/\s+/).join(' ') debug('comparator', comp, options) this.options = options this.loose = !!options.loose this.parse(comp) if (this.semver === ANY) { this.value = '' } else { this.value = this.operator + this.semver.version } debug('comp', this) } parse (comp) { const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] const m = comp.match(r) if (!m) { throw new TypeError(`Invalid comparator: ${comp}`) } this.operator = m[1] !== undefined ? m[1] : '' if (this.operator === '=') { this.operator = '' } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY } else { this.semver = new SemVer(m[2], this.options.loose) } } toString () { return this.value } test (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY || version === ANY) { return true } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } return cmp(version, this.operator, this.semver, this.options) } intersects (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (this.operator === '') { if (this.value === '') { return true } return new Range(comp.value, options).test(this.value) } else if (comp.operator === '') { if (comp.value === '') { return true } return new Range(this.value, options).test(comp.semver) } options = parseOptions(options) // Special cases where nothing can possibly be lower if (options.includePrerelease && (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { return false } if (!options.includePrerelease && (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { return false } // Same direction increasing (> or >=) if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { return true } // Same direction decreasing (< or <=) if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { return true } // same SemVer and both sides are inclusive (<= or >=) if ( (this.semver.version === comp.semver.version) && this.operator.includes('=') && comp.operator.includes('=')) { return true } // opposite directions less than if (cmp(this.semver, '<', comp.semver, options) && this.operator.startsWith('>') && comp.operator.startsWith('<')) { return true } // opposite directions greater than if (cmp(this.semver, '>', comp.semver, options) && this.operator.startsWith('<') && comp.operator.startsWith('>')) { return true } return false } } module.exports = Comparator const parseOptions = __webpack_require__(9609) const { safeRe: re, t } = __webpack_require__(93821) const cmp = __webpack_require__(99336) const debug = __webpack_require__(9895) const SemVer = __webpack_require__(55946) const Range = __webpack_require__(98479) /***/ }), /***/ 98479: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // hoisted class for cyclic dependency class Range { constructor (range, options) { options = parseOptions(options) if (range instanceof Range) { if ( range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease ) { return range } else { return new Range(range.raw, options) } } if (range instanceof Comparator) { // just put it in the set and return this.raw = range.value this.set = [[range]] this.format() return this } this.options = options this.loose = !!options.loose this.includePrerelease = !!options.includePrerelease // First reduce all whitespace as much as possible so we do not have to rely // on potentially slow regexes like \s*. This is then stored and used for // future error messages as well. this.raw = range .trim() .split(/\s+/) .join(' ') // First, split on || this.set = this.raw .split('||') // map the range to a 2d array of comparators .map(r => this.parseRange(r.trim())) // throw out any comparator lists that are empty // this generally means that it was not a valid range, which is allowed // in loose mode, but will still throw if the WHOLE range is invalid. .filter(c => c.length) if (!this.set.length) { throw new TypeError(`Invalid SemVer Range: ${this.raw}`) } // if we have any that are not the null set, throw out null sets. if (this.set.length > 1) { // keep the first one, in case they're all null sets const first = this.set[0] this.set = this.set.filter(c => !isNullSet(c[0])) if (this.set.length === 0) { this.set = [first] } else if (this.set.length > 1) { // if we have any that are *, then the range is just * for (const c of this.set) { if (c.length === 1 && isAny(c[0])) { this.set = [c] break } } } } this.format() } format () { this.range = this.set .map((comps) => comps.join(' ').trim()) .join('||') .trim() return this.range } toString () { return this.range } parseRange (range) { // memoize range parsing for performance. // this is a very hot path, and fully deterministic. const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE) const memoKey = memoOpts + ':' + range const cached = cache.get(memoKey) if (cached) { return cached } const loose = this.options.loose // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range) // `~ 1.2.3` => `~1.2.3` range = range.replace(re[t.TILDETRIM], tildeTrimReplace) debug('tilde trim', range) // `^ 1.2.3` => `^1.2.3` range = range.replace(re[t.CARETTRIM], caretTrimReplace) debug('caret trim', range) // At this point, the range is completely trimmed and // ready to be split into comparators. let rangeList = range .split(' ') .map(comp => parseComparator(comp, this.options)) .join(' ') .split(/\s+/) // >=0.0.0 is equivalent to * .map(comp => replaceGTE0(comp, this.options)) if (loose) { // in loose mode, throw out any that are not valid comparators rangeList = rangeList.filter(comp => { debug('loose invalid filter', comp, this.options) return !!comp.match(re[t.COMPARATORLOOSE]) }) } debug('range list', rangeList) // if any comparators are the null set, then replace with JUST null set // if more than one comparator, remove any * comparators // also, don't include the same comparator more than once const rangeMap = new Map() const comparators = rangeList.map(comp => new Comparator(comp, this.options)) for (const comp of comparators) { if (isNullSet(comp)) { return [comp] } rangeMap.set(comp.value, comp) } if (rangeMap.size > 1 && rangeMap.has('')) { rangeMap.delete('') } const result = [...rangeMap.values()] cache.set(memoKey, result) return result } intersects (range, options) { if (!(range instanceof Range)) { throw new TypeError('a Range is required') } return this.set.some((thisComparators) => { return ( isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => { return ( isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { return rangeComparators.every((rangeComparator) => { return thisComparator.intersects(rangeComparator, options) }) }) ) }) ) }) } // if ANY of the sets match ALL of its comparators, then pass test (version) { if (!version) { return false } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } for (let i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true } } return false } } module.exports = Range const LRU = __webpack_require__(50737) const cache = new LRU({ max: 1000 }) const parseOptions = __webpack_require__(9609) const Comparator = __webpack_require__(58775) const debug = __webpack_require__(9895) const SemVer = __webpack_require__(55946) const { safeRe: re, t, comparatorTrimReplace, tildeTrimReplace, caretTrimReplace, } = __webpack_require__(93821) const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __webpack_require__(89626) const isNullSet = c => c.value === '<0.0.0-0' const isAny = c => c.value === '' // take a set of comparators and determine whether there // exists a version which can satisfy it const isSatisfiable = (comparators, options) => { let result = true const remainingComparators = comparators.slice() let testComparator = remainingComparators.pop() while (result && remainingComparators.length) { result = remainingComparators.every((otherComparator) => { return testComparator.intersects(otherComparator, options) }) testComparator = remainingComparators.pop() } return result } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. const parseComparator = (comp, options) => { debug('comp', comp, options) comp = replaceCarets(comp, options) debug('caret', comp) comp = replaceTildes(comp, options) debug('tildes', comp) comp = replaceXRanges(comp, options) debug('xrange', comp) comp = replaceStars(comp, options) debug('stars', comp) return comp } const isX = id => !id || id.toLowerCase() === 'x' || id === '*' // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 // ~0.0.1 --> >=0.0.1 <0.1.0-0 const replaceTildes = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceTilde(c, options)) .join(' ') } const replaceTilde = (comp, options) => { const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] return comp.replace(r, (_, M, m, p, pr) => { debug('tilde', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0 <${+M + 1}.0.0-0` } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0-0 ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` } else if (pr) { debug('replaceTilde pr', pr) ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } else { // ~1.2.3 == >=1.2.3 <1.3.0-0 ret = `>=${M}.${m}.${p } <${M}.${+m + 1}.0-0` } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 // ^1.2.3 --> >=1.2.3 <2.0.0-0 // ^1.2.0 --> >=1.2.0 <2.0.0-0 // ^0.0.1 --> >=0.0.1 <0.0.2-0 // ^0.1.0 --> >=0.1.0 <0.2.0-0 const replaceCarets = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceCaret(c, options)) .join(' ') } const replaceCaret = (comp, options) => { debug('caret', comp, options) const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] const z = options.includePrerelease ? '-0' : '' return comp.replace(r, (_, M, m, p, pr) => { debug('caret', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` } else if (isX(p)) { if (M === '0') { ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` } else { ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p}-${pr } <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p}-${pr } <${+M + 1}.0.0-0` } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p }${z} <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p }${z} <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p } <${+M + 1}.0.0-0` } } debug('caret return', ret) return ret }) } const replaceXRanges = (comp, options) => { debug('replaceXRanges', comp, options) return comp .split(/\s+/) .map((c) => replaceXRange(c, options)) .join(' ') } const replaceXRange = (comp, options) => { comp = comp.trim() const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] return comp.replace(r, (ret, gtlt, M, m, p, pr) => { debug('xRange', comp, ret, gtlt, M, m, p, pr) const xM = isX(M) const xm = xM || isX(m) const xp = xm || isX(p) const anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } // if we're including prereleases in the match, then we need // to fix this to -0, the lowest possible prerelease value pr = options.includePrerelease ? '-0' : '' if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0-0' } else { // nothing is forbidden ret = '*' } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0 } p = 0 if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 gtlt = '>=' if (xm) { M = +M + 1 m = 0 p = 0 } else { m = +m + 1 p = 0 } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<' if (xm) { M = +M + 1 } else { m = +m + 1 } } if (gtlt === '<') { pr = '-0' } ret = `${gtlt + M}.${m}.${p}${pr}` } else if (xm) { ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` } else if (xp) { ret = `>=${M}.${m}.0${pr } <${M}.${+m + 1}.0-0` } debug('xRange return', ret) return ret }) } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. const replaceStars = (comp, options) => { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp .trim() .replace(re[t.STAR], '') } const replaceGTE0 = (comp, options) => { debug('replaceGTE0', comp, options) return comp .trim() .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') } // This function is passed to string.replace(re[t.HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 const hyphenReplace = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) => { if (isX(fM)) { from = '' } else if (isX(fm)) { from = `>=${fM}.0.0${incPr ? '-0' : ''}` } else if (isX(fp)) { from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` } else if (fpr) { from = `>=${from}` } else { from = `>=${from}${incPr ? '-0' : ''}` } if (isX(tM)) { to = '' } else if (isX(tm)) { to = `<${+tM + 1}.0.0-0` } else if (isX(tp)) { to = `<${tM}.${+tm + 1}.0-0` } else if (tpr) { to = `<=${tM}.${tm}.${tp}-${tpr}` } else if (incPr) { to = `<${tM}.${tm}.${+tp + 1}-0` } else { to = `<=${to}` } return `${from} ${to}`.trim() } const testSet = (set, version, options) => { for (let i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (let i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === Comparator.ANY) { continue } if (set[i].semver.prerelease.length > 0) { const allowed = set[i].semver if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } /***/ }), /***/ 55946: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const debug = __webpack_require__(9895) const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(89626) const { safeRe: re, t } = __webpack_require__(93821) const parseOptions = __webpack_require__(9609) const { compareIdentifiers } = __webpack_require__(6056) class SemVer { constructor (version, options) { options = parseOptions(options) if (version instanceof SemVer) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) } if (version.length > MAX_LENGTH) { throw new TypeError( `version is longer than ${MAX_LENGTH} characters` ) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose // this isn't actually relevant for versions, but keep it so that we // don't run into trouble passing this.options around. this.includePrerelease = !!options.includePrerelease const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) if (!m) { throw new TypeError(`Invalid Version: ${version}`) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map((id) => { if (/^[0-9]+$/.test(id)) { const num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } format () { this.version = `${this.major}.${this.minor}.${this.patch}` if (this.prerelease.length) { this.version += `-${this.prerelease.join('.')}` } return this.version } toString () { return this.version } compare (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { if (typeof other === 'string' && other === this.version) { return 0 } other = new SemVer(other, this.options) } if (other.version === this.version) { return 0 } return this.compareMain(other) || this.comparePre(other) } compareMain (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return ( compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) ) } comparePre (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } let i = 0 do { const a = this.prerelease[i] const b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } compareBuild (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } let i = 0 do { const a = this.build[i] const b = other.build[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc (release, identifier, identifierBase) { switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier, identifierBase) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier, identifierBase) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier, identifierBase) this.inc('pre', identifier, identifierBase) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier, identifierBase) } this.inc('pre', identifier, identifierBase) break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if ( this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0 ) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. case 'pre': { const base = Number(identifierBase) ? 1 : 0 if (!identifier && identifierBase === false) { throw new Error('invalid increment argument: identifier is empty') } if (this.prerelease.length === 0) { this.prerelease = [base] } else { let i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything if (identifier === this.prerelease.join('.') && identifierBase === false) { throw new Error('invalid increment argument: identifier already exists') } this.prerelease.push(base) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 let prerelease = [identifier, base] if (identifierBase === false) { prerelease = [identifier] } if (compareIdentifiers(this.prerelease[0], identifier) === 0) { if (isNaN(this.prerelease[1])) { this.prerelease = prerelease } } else { this.prerelease = prerelease } } break } default: throw new Error(`invalid increment argument: ${release}`) } this.raw = this.format() if (this.build.length) { this.raw += `+${this.build.join('.')}` } return this } } module.exports = SemVer /***/ }), /***/ 59399: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(29576) const clean = (version, options) => { const s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } module.exports = clean /***/ }), /***/ 99336: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const eq = __webpack_require__(67590) const neq = __webpack_require__(87106) const gt = __webpack_require__(34950) const gte = __webpack_require__(38802) const lt = __webpack_require__(47945) const lte = __webpack_require__(82926) const cmp = (a, op, b, loose) => { switch (op) { case '===': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a === b case '!==': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError(`Invalid operator: ${op}`) } } module.exports = cmp /***/ }), /***/ 75571: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(55946) const parse = __webpack_require__(29576) const { safeRe: re, t } = __webpack_require__(93821) const coerce = (version, options) => { if (version instanceof SemVer) { return version } if (typeof version === 'number') { version = String(version) } if (typeof version !== 'string') { return null } options = options || {} let match = null if (!options.rtl) { match = version.match(re[t.COERCE]) } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' // // Walk through the string checking with a /g regexp // Manually set the index so as to pick up overlapping matches. // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. let next while ((next = re[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next } re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length } // leave it in a clean state re[t.COERCERTL].lastIndex = -1 } if (match === null) { return null } return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) } module.exports = coerce /***/ }), /***/ 75209: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(55946) const compareBuild = (a, b, loose) => { const versionA = new SemVer(a, loose) const versionB = new SemVer(b, loose) return versionA.compare(versionB) || versionA.compareBuild(versionB) } module.exports = compareBuild /***/ }), /***/ 61475: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(38719) const compareLoose = (a, b) => compare(a, b, true) module.exports = compareLoose /***/ }), /***/ 38719: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(55946) const compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)) module.exports = compare /***/ }), /***/ 59154: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(29576) const diff = (version1, version2) => { const v1 = parse(version1, null, true) const v2 = parse(version2, null, true) const comparison = v1.compare(v2) if (comparison === 0) { return null } const v1Higher = comparison > 0 const highVersion = v1Higher ? v1 : v2 const lowVersion = v1Higher ? v2 : v1 const highHasPre = !!highVersion.prerelease.length const lowHasPre = !!lowVersion.prerelease.length if (lowHasPre && !highHasPre) { // Going from prerelease -> no prerelease requires some special casing // If the low version has only a major, then it will always be a major // Some examples: // 1.0.0-1 -> 1.0.0 // 1.0.0-1 -> 1.1.1 // 1.0.0-1 -> 2.0.0 if (!lowVersion.patch && !lowVersion.minor) { return 'major' } // Otherwise it can be determined by checking the high version if (highVersion.patch) { // anything higher than a patch bump would result in the wrong version return 'patch' } if (highVersion.minor) { // anything higher than a minor bump would result in the wrong version return 'minor' } // bumping major/minor/patch all have same result return 'major' } // add the `pre` prefix if we are going to a prerelease version const prefix = highHasPre ? 'pre' : '' if (v1.major !== v2.major) { return prefix + 'major' } if (v1.minor !== v2.minor) { return prefix + 'minor' } if (v1.patch !== v2.patch) { return prefix + 'patch' } // high and low are preleases return 'prerelease' } module.exports = diff /***/ }), /***/ 67590: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(38719) const eq = (a, b, loose) => compare(a, b, loose) === 0 module.exports = eq /***/ }), /***/ 34950: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(38719) const gt = (a, b, loose) => compare(a, b, loose) > 0 module.exports = gt /***/ }), /***/ 38802: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(38719) const gte = (a, b, loose) => compare(a, b, loose) >= 0 module.exports = gte /***/ }), /***/ 91235: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(55946) const inc = (version, release, options, identifier, identifierBase) => { if (typeof (options) === 'string') { identifierBase = identifier identifier = options options = undefined } try { return new SemVer( version instanceof SemVer ? version.version : version, options ).inc(release, identifier, identifierBase).version } catch (er) { return null } } module.exports = inc /***/ }), /***/ 47945: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(38719) const lt = (a, b, loose) => compare(a, b, loose) < 0 module.exports = lt /***/ }), /***/ 82926: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(38719) const lte = (a, b, loose) => compare(a, b, loose) <= 0 module.exports = lte /***/ }), /***/ 74624: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(55946) const major = (a, loose) => new SemVer(a, loose).major module.exports = major /***/ }), /***/ 32681: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(55946) const minor = (a, loose) => new SemVer(a, loose).minor module.exports = minor /***/ }), /***/ 87106: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(38719) const neq = (a, b, loose) => compare(a, b, loose) !== 0 module.exports = neq /***/ }), /***/ 29576: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(55946) const parse = (version, options, throwErrors = false) => { if (version instanceof SemVer) { return version } try { return new SemVer(version, options) } catch (er) { if (!throwErrors) { return null } throw er } } module.exports = parse /***/ }), /***/ 4930: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(55946) const patch = (a, loose) => new SemVer(a, loose).patch module.exports = patch /***/ }), /***/ 50975: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(29576) const prerelease = (version, options) => { const parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } module.exports = prerelease /***/ }), /***/ 89925: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(38719) const rcompare = (a, b, loose) => compare(b, a, loose) module.exports = rcompare /***/ }), /***/ 79206: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(75209) const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) module.exports = rsort /***/ }), /***/ 28050: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(98479) const satisfies = (version, range, options) => { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } module.exports = satisfies /***/ }), /***/ 28524: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(75209) const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) module.exports = sort /***/ }), /***/ 50252: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(29576) const valid = (version, options) => { const v = parse(version, options) return v ? v.version : null } module.exports = valid /***/ }), /***/ 9195: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // just pre-load all the stuff that index.js lazily exports const internalRe = __webpack_require__(93821) const constants = __webpack_require__(89626) const SemVer = __webpack_require__(55946) const identifiers = __webpack_require__(6056) const parse = __webpack_require__(29576) const valid = __webpack_require__(50252) const clean = __webpack_require__(59399) const inc = __webpack_require__(91235) const diff = __webpack_require__(59154) const major = __webpack_require__(74624) const minor = __webpack_require__(32681) const patch = __webpack_require__(4930) const prerelease = __webpack_require__(50975) const compare = __webpack_require__(38719) const rcompare = __webpack_require__(89925) const compareLoose = __webpack_require__(61475) const compareBuild = __webpack_require__(75209) const sort = __webpack_require__(28524) const rsort = __webpack_require__(79206) const gt = __webpack_require__(34950) const lt = __webpack_require__(47945) const eq = __webpack_require__(67590) const neq = __webpack_require__(87106) const gte = __webpack_require__(38802) const lte = __webpack_require__(82926) const cmp = __webpack_require__(99336) const coerce = __webpack_require__(75571) const Comparator = __webpack_require__(58775) const Range = __webpack_require__(98479) const satisfies = __webpack_require__(28050) const toComparators = __webpack_require__(61463) const maxSatisfying = __webpack_require__(16630) const minSatisfying = __webpack_require__(79553) const minVersion = __webpack_require__(30688) const validRange = __webpack_require__(87994) const outside = __webpack_require__(57910) const gtr = __webpack_require__(95347) const ltr = __webpack_require__(83246) const intersects = __webpack_require__(56262) const simplifyRange = __webpack_require__(910) const subset = __webpack_require__(32192) module.exports = { parse, valid, clean, inc, diff, major, minor, patch, prerelease, compare, rcompare, compareLoose, compareBuild, sort, rsort, gt, lt, eq, neq, gte, lte, cmp, coerce, Comparator, Range, satisfies, toComparators, maxSatisfying, minSatisfying, minVersion, validRange, outside, gtr, ltr, intersects, simplifyRange, subset, SemVer, re: internalRe.re, src: internalRe.src, tokens: internalRe.t, SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, RELEASE_TYPES: constants.RELEASE_TYPES, compareIdentifiers: identifiers.compareIdentifiers, rcompareIdentifiers: identifiers.rcompareIdentifiers, } /***/ }), /***/ 89626: /***/ ((module) => { // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. const SEMVER_SPEC_VERSION = '2.0.0' const MAX_LENGTH = 256 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. const MAX_SAFE_COMPONENT_LENGTH = 16 // Max safe length for a build identifier. The max length minus 6 characters for // the shortest version with a build 0.0.0+BUILD. const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 const RELEASE_TYPES = [ 'major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease', ] module.exports = { MAX_LENGTH, MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_SAFE_INTEGER, RELEASE_TYPES, SEMVER_SPEC_VERSION, FLAG_INCLUDE_PRERELEASE: 0b001, FLAG_LOOSE: 0b010, } /***/ }), /***/ 9895: /***/ ((module) => { const debug = ( typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ) ? (...args) => console.error('SEMVER', ...args) : () => {} module.exports = debug /***/ }), /***/ 6056: /***/ ((module) => { const numeric = /^[0-9]+$/ const compareIdentifiers = (a, b) => { const anum = numeric.test(a) const bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) module.exports = { compareIdentifiers, rcompareIdentifiers, } /***/ }), /***/ 9609: /***/ ((module) => { // parse out just the options we care about const looseOption = Object.freeze({ loose: true }) const emptyOpts = Object.freeze({ }) const parseOptions = options => { if (!options) { return emptyOpts } if (typeof options !== 'object') { return looseOption } return options } module.exports = parseOptions /***/ }), /***/ 93821: /***/ ((module, exports, __webpack_require__) => { const { MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_LENGTH, } = __webpack_require__(89626) const debug = __webpack_require__(9895) exports = module.exports = {} // The actual regexps go on exports.re const re = exports.re = [] const safeRe = exports.safeRe = [] const src = exports.src = [] const t = exports.t = {} let R = 0 const LETTERDASHNUMBER = '[a-zA-Z0-9-]' // Replace some greedy regex tokens to prevent regex dos issues. These regex are // used internally via the safeRe object since all inputs in this library get // normalized first to trim and collapse all extra whitespace. The original // regexes are exported for userland consumption and lower level usage. A // future breaking change could export the safer regex only with a note that // all input should have extra whitespace removed. const safeRegexReplacements = [ ['\\s', 1], ['\\d', MAX_LENGTH], [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], ] const makeSafeRegex = (value) => { for (const [token, max] of safeRegexReplacements) { value = value .split(`${token}*`).join(`${token}{0,${max}}`) .split(`${token}+`).join(`${token}{1,${max}}`) } return value } const createToken = (name, value, isGlobal) => { const safe = makeSafeRegex(value) const index = R++ debug(name, index, value) t[name] = index src[index] = value re[index] = new RegExp(value, isGlobal ? 'g' : undefined) safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) } // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') createToken('NUMERICIDENTIFIERLOOSE', '\\d+') // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) // ## Main Version // Three dot-separated numeric identifiers. createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`) createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] }|${src[t.NONNUMERICIDENTIFIER]})`) createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] }|${src[t.NONNUMERICIDENTIFIER]})`) // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] }(?:\\.${src[t.BUILDIDENTIFIER]})*))`) // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. createToken('FULLPLAIN', `v?${src[t.MAINVERSION] }${src[t.PRERELEASE]}?${ src[t.BUILD]}?`) createToken('FULL', `^${src[t.FULLPLAIN]}$`) // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] }${src[t.PRERELEASELOOSE]}?${ src[t.BUILD]}?`) createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) createToken('GTLT', '((?:<|>)?=?)') // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) // Coercion. // Extract anything that could conceivably be a part of a valid semver createToken('COERCE', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:$|[^\\d])`) createToken('COERCERTL', src[t.COERCE], true) // Tilde ranges. // Meaning is "reasonably at or greater than" createToken('LONETILDE', '(?:~>?)') createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) exports.tildeTrimReplace = '$1~' createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) // Caret ranges. // Meaning is "at least and backwards compatible with" createToken('LONECARET', '(?:\\^)') createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) exports.caretTrimReplace = '$1^' createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) // A simple gt/lt/eq thing, or just "" to indicate "any version" createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) exports.comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`) createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`) // Star ranges basically just allow anything at all. createToken('STAR', '(<|>)?=?\\s*\\*') // >=0.0.0 is like a star createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') /***/ }), /***/ 95347: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Determine if version is greater than all the versions possible in the range. const outside = __webpack_require__(57910) const gtr = (version, range, options) => outside(version, range, '>', options) module.exports = gtr /***/ }), /***/ 56262: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(98479) const intersects = (r1, r2, options) => { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2, options) } module.exports = intersects /***/ }), /***/ 83246: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const outside = __webpack_require__(57910) // Determine if version is less than all the versions possible in the range const ltr = (version, range, options) => outside(version, range, '<', options) module.exports = ltr /***/ }), /***/ 16630: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(55946) const Range = __webpack_require__(98479) const maxSatisfying = (versions, range, options) => { let max = null let maxSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } module.exports = maxSatisfying /***/ }), /***/ 79553: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(55946) const Range = __webpack_require__(98479) const minSatisfying = (versions, range, options) => { let min = null let minSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } module.exports = minSatisfying /***/ }), /***/ 30688: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(55946) const Range = __webpack_require__(98479) const gt = __webpack_require__(34950) const minVersion = (range, loose) => { range = new Range(range, loose) let minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let setMin = null comparators.forEach((comparator) => { // Clone to avoid manipulating the comparator's semver object. const compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!setMin || gt(compver, setMin)) { setMin = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error(`Unexpected operation: ${comparator.operator}`) } }) if (setMin && (!minver || gt(minver, setMin))) { minver = setMin } } if (minver && range.test(minver)) { return minver } return null } module.exports = minVersion /***/ }), /***/ 57910: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(55946) const Comparator = __webpack_require__(58775) const { ANY } = Comparator const Range = __webpack_require__(98479) const satisfies = __webpack_require__(28050) const gt = __webpack_require__(34950) const lt = __webpack_require__(47945) const lte = __webpack_require__(82926) const gte = __webpack_require__(38802) const outside = (version, range, hilo, options) => { version = new SemVer(version, options) range = new Range(range, options) let gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisfies the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let high = null let low = null comparators.forEach((comparator) => { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } module.exports = outside /***/ }), /***/ 910: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // given a set of versions and a range, create a "simplified" range // that includes the same versions that the original range does // If the original range is shorter than the simplified one, return that. const satisfies = __webpack_require__(28050) const compare = __webpack_require__(38719) module.exports = (versions, range, options) => { const set = [] let first = null let prev = null const v = versions.sort((a, b) => compare(a, b, options)) for (const version of v) { const included = satisfies(version, range, options) if (included) { prev = version if (!first) { first = version } } else { if (prev) { set.push([first, prev]) } prev = null first = null } } if (first) { set.push([first, null]) } const ranges = [] for (const [min, max] of set) { if (min === max) { ranges.push(min) } else if (!max && min === v[0]) { ranges.push('*') } else if (!max) { ranges.push(`>=${min}`) } else if (min === v[0]) { ranges.push(`<=${max}`) } else { ranges.push(`${min} - ${max}`) } } const simplified = ranges.join(' || ') const original = typeof range.raw === 'string' ? range.raw : String(range) return simplified.length < original.length ? simplified : range } /***/ }), /***/ 32192: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(98479) const Comparator = __webpack_require__(58775) const { ANY } = Comparator const satisfies = __webpack_require__(28050) const compare = __webpack_require__(38719) // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: // - Every simple range `r1, r2, ...` is a null set, OR // - Every simple range `r1, r2, ...` which is not a null set is a subset of // some `R1, R2, ...` // // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: // - If c is only the ANY comparator // - If C is only the ANY comparator, return true // - Else if in prerelease mode, return false // - else replace c with `[>=0.0.0]` // - If C is only the ANY comparator // - if in prerelease mode, return true // - else replace C with `[>=0.0.0]` // - Let EQ be the set of = comparators in c // - If EQ is more than one, return true (null set) // - Let GT be the highest > or >= comparator in c // - Let LT be the lowest < or <= comparator in c // - If GT and LT, and GT.semver > LT.semver, return true (null set) // - If any C is a = range, and GT or LT are set, return false // - If EQ // - If GT, and EQ does not satisfy GT, return true (null set) // - If LT, and EQ does not satisfy LT, return true (null set) // - If EQ satisfies every C, return true // - Else return false // - If GT // - If GT.semver is lower than any > or >= comp in C, return false // - If GT is >=, and GT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the GT.semver tuple, return false // - If LT // - If LT.semver is greater than any < or <= comp in C, return false // - If LT is <=, and LT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the LT.semver tuple, return false // - Else return true const subset = (sub, dom, options = {}) => { if (sub === dom) { return true } sub = new Range(sub, options) dom = new Range(dom, options) let sawNonNull = false OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { const isSub = simpleSubset(simpleSub, simpleDom, options) sawNonNull = sawNonNull || isSub !== null if (isSub) { continue OUTER } } // the null set is a subset of everything, but null simple ranges in // a complex range should be ignored. so if we saw a non-null range, // then we know this isn't a subset, but if EVERY simple range was null, // then it is a subset. if (sawNonNull) { return false } } return true } const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] const minimumVersion = [new Comparator('>=0.0.0')] const simpleSubset = (sub, dom, options) => { if (sub === dom) { return true } if (sub.length === 1 && sub[0].semver === ANY) { if (dom.length === 1 && dom[0].semver === ANY) { return true } else if (options.includePrerelease) { sub = minimumVersionWithPreRelease } else { sub = minimumVersion } } if (dom.length === 1 && dom[0].semver === ANY) { if (options.includePrerelease) { return true } else { dom = minimumVersion } } const eqSet = new Set() let gt, lt for (const c of sub) { if (c.operator === '>' || c.operator === '>=') { gt = higherGT(gt, c, options) } else if (c.operator === '<' || c.operator === '<=') { lt = lowerLT(lt, c, options) } else { eqSet.add(c.semver) } } if (eqSet.size > 1) { return null } let gtltComp if (gt && lt) { gtltComp = compare(gt.semver, lt.semver, options) if (gtltComp > 0) { return null } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { return null } } // will iterate one or zero times for (const eq of eqSet) { if (gt && !satisfies(eq, String(gt), options)) { return null } if (lt && !satisfies(eq, String(lt), options)) { return null } for (const c of dom) { if (!satisfies(eq, String(c), options)) { return false } } return true } let higher, lower let hasDomLT, hasDomGT // if the subset has a prerelease, we need a comparator in the superset // with the same tuple and a prerelease, or it's not a subset let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false // exception: <1.2.3-0 is the same as <1.2.3 if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { needDomLTPre = false } for (const c of dom) { hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' if (gt) { if (needDomGTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { needDomGTPre = false } } if (c.operator === '>' || c.operator === '>=') { higher = higherGT(gt, c, options) if (higher === c && higher !== gt) { return false } } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { return false } } if (lt) { if (needDomLTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { needDomLTPre = false } } if (c.operator === '<' || c.operator === '<=') { lower = lowerLT(lt, c, options) if (lower === c && lower !== lt) { return false } } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { return false } } if (!c.operator && (lt || gt) && gtltComp !== 0) { return false } } // if there was a < or >, and nothing in the dom, then must be false // UNLESS it was limited by another range in the other direction. // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 if (gt && hasDomLT && !lt && gtltComp !== 0) { return false } if (lt && hasDomGT && !gt && gtltComp !== 0) { return false } // we needed a prerelease range in a specific tuple, but didn't get one // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, // because it includes prereleases in the 1.2.3 tuple if (needDomGTPre || needDomLTPre) { return false } return true } // >=1.2.3 is lower than >1.2.3 const higherGT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp > 0 ? a : comp < 0 ? b : b.operator === '>' && a.operator === '>=' ? b : a } // <=1.2.3 is higher than <1.2.3 const lowerLT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp < 0 ? a : comp > 0 ? b : b.operator === '<' && a.operator === '<=' ? b : a } module.exports = subset /***/ }), /***/ 61463: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(98479) // Mostly just for testing and legacy API reasons const toComparators = (range, options) => new Range(range, options).set .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) module.exports = toComparators /***/ }), /***/ 87994: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(98479) const validRange = (range, options) => { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } module.exports = validRange /***/ }), /***/ 5721: /***/ ((module) => { "use strict"; module.exports = function (Yallist) { Yallist.prototype[Symbol.iterator] = function* () { for (let walker = this.head; walker; walker = walker.next) { yield walker.value } } } /***/ }), /***/ 53141: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = Yallist Yallist.Node = Node Yallist.create = Yallist function Yallist (list) { var self = this if (!(self instanceof Yallist)) { self = new Yallist() } self.tail = null self.head = null self.length = 0 if (list && typeof list.forEach === 'function') { list.forEach(function (item) { self.push(item) }) } else if (arguments.length > 0) { for (var i = 0, l = arguments.length; i < l; i++) { self.push(arguments[i]) } } return self } Yallist.prototype.removeNode = function (node) { if (node.list !== this) { throw new Error('removing node which does not belong to this list') } var next = node.next var prev = node.prev if (next) { next.prev = prev } if (prev) { prev.next = next } if (node === this.head) { this.head = next } if (node === this.tail) { this.tail = prev } node.list.length-- node.next = null node.prev = null node.list = null return next } Yallist.prototype.unshiftNode = function (node) { if (node === this.head) { return } if (node.list) { node.list.removeNode(node) } var head = this.head node.list = this node.next = head if (head) { head.prev = node } this.head = node if (!this.tail) { this.tail = node } this.length++ } Yallist.prototype.pushNode = function (node) { if (node === this.tail) { return } if (node.list) { node.list.removeNode(node) } var tail = this.tail node.list = this node.prev = tail if (tail) { tail.next = node } this.tail = node if (!this.head) { this.head = node } this.length++ } Yallist.prototype.push = function () { for (var i = 0, l = arguments.length; i < l; i++) { push(this, arguments[i]) } return this.length } Yallist.prototype.unshift = function () { for (var i = 0, l = arguments.length; i < l; i++) { unshift(this, arguments[i]) } return this.length } Yallist.prototype.pop = function () { if (!this.tail) { return undefined } var res = this.tail.value this.tail = this.tail.prev if (this.tail) { this.tail.next = null } else { this.head = null } this.length-- return res } Yallist.prototype.shift = function () { if (!this.head) { return undefined } var res = this.head.value this.head = this.head.next if (this.head) { this.head.prev = null } else { this.tail = null } this.length-- return res } Yallist.prototype.forEach = function (fn, thisp) { thisp = thisp || this for (var walker = this.head, i = 0; walker !== null; i++) { fn.call(thisp, walker.value, i, this) walker = walker.next } } Yallist.prototype.forEachReverse = function (fn, thisp) { thisp = thisp || this for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { fn.call(thisp, walker.value, i, this) walker = walker.prev } } Yallist.prototype.get = function (n) { for (var i = 0, walker = this.head; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.next } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.getReverse = function (n) { for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.prev } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.map = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.head; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.next } return res } Yallist.prototype.mapReverse = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.tail; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.prev } return res } Yallist.prototype.reduce = function (fn, initial) { var acc var walker = this.head if (arguments.length > 1) { acc = initial } else if (this.head) { walker = this.head.next acc = this.head.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = 0; walker !== null; i++) { acc = fn(acc, walker.value, i) walker = walker.next } return acc } Yallist.prototype.reduceReverse = function (fn, initial) { var acc var walker = this.tail if (arguments.length > 1) { acc = initial } else if (this.tail) { walker = this.tail.prev acc = this.tail.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = this.length - 1; walker !== null; i--) { acc = fn(acc, walker.value, i) walker = walker.prev } return acc } Yallist.prototype.toArray = function () { var arr = new Array(this.length) for (var i = 0, walker = this.head; walker !== null; i++) { arr[i] = walker.value walker = walker.next } return arr } Yallist.prototype.toArrayReverse = function () { var arr = new Array(this.length) for (var i = 0, walker = this.tail; walker !== null; i++) { arr[i] = walker.value walker = walker.prev } return arr } Yallist.prototype.slice = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = 0, walker = this.head; walker !== null && i < from; i++) { walker = walker.next } for (; walker !== null && i < to; i++, walker = walker.next) { ret.push(walker.value) } return ret } Yallist.prototype.sliceReverse = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { walker = walker.prev } for (; walker !== null && i > from; i--, walker = walker.prev) { ret.push(walker.value) } return ret } Yallist.prototype.splice = function (start, deleteCount, ...nodes) { if (start > this.length) { start = this.length - 1 } if (start < 0) { start = this.length + start; } for (var i = 0, walker = this.head; walker !== null && i < start; i++) { walker = walker.next } var ret = [] for (var i = 0; walker && i < deleteCount; i++) { ret.push(walker.value) walker = this.removeNode(walker) } if (walker === null) { walker = this.tail } if (walker !== this.head && walker !== this.tail) { walker = walker.prev } for (var i = 0; i < nodes.length; i++) { walker = insert(this, walker, nodes[i]) } return ret; } Yallist.prototype.reverse = function () { var head = this.head var tail = this.tail for (var walker = head; walker !== null; walker = walker.prev) { var p = walker.prev walker.prev = walker.next walker.next = p } this.head = tail this.tail = head return this } function insert (self, node, value) { var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self) if (inserted.next === null) { self.tail = inserted } if (inserted.prev === null) { self.head = inserted } self.length++ return inserted } function push (self, item) { self.tail = new Node(item, self.tail, null, self) if (!self.head) { self.head = self.tail } self.length++ } function unshift (self, item) { self.head = new Node(item, null, self.head, self) if (!self.tail) { self.tail = self.head } self.length++ } function Node (value, prev, next, list) { if (!(this instanceof Node)) { return new Node(value, prev, next, list) } this.list = list this.value = value if (prev) { prev.next = this this.prev = prev } else { this.prev = null } if (next) { next.prev = this this.next = next } else { this.next = null } } try { // add if support for Symbol.iterator is present __webpack_require__(5721)(Yallist) } catch (er) {} /***/ }), /***/ 83345: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.cMap = void 0; const pMap = __webpack_require__(86301); const event_loop_spinner_1 = __webpack_require__(77158); /** Run a function each element in an array, with some level of concurrency. * * Defaults to a small, finite concurrency, so as to not to "overload" the database * connection pool or the http client, both of which have small, internal limits. * * Can be used with async functions that don't yield; will yield for you, if necessary. */ async function cMap(input, mapper, options) { var _a; const concurrency = (_a = options === null || options === void 0 ? void 0 : options.concurrency) !== null && _a !== void 0 ? _a : 6; return await pMap(input, async (from) => { if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } return await mapper(from); }, { concurrency }); } exports.cMap = cMap; //# sourceMappingURL=c-map.js.map /***/ }), /***/ 80333: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.extractCorrectIdentifierBySemver = exports.extractNameAndIdentifier = void 0; const semver = __webpack_require__(50460); const extractNameAndIdentifier = (candidate) => { let name, identifier; if (candidate.includes('@')) { const index = candidate.indexOf('@', 1); name = candidate.slice(0, index); identifier = candidate.slice(index + 1); } else { name = candidate; identifier = 'unknown'; } return { name, identifier }; }; exports.extractNameAndIdentifier = extractNameAndIdentifier; // This function will choose an item in a particular list that satisfies the semver provided // i.e. possibleMatches = [debug@1.2.0, debug@2.2.6] and versionToMatch = debug@~2.2.0 // will result in debug@2.2.6 - This is required as yarn list does not have the resolved semver // in dependencies. const extractCorrectIdentifierBySemver = (possibleMatches, versionToMatch) => { const { name: nameToMatch, identifier: identifierToMatch } = (0, exports.extractNameAndIdentifier)(versionToMatch); const hasQualifiers = isNaN(parseInt(identifierToMatch[0])); if (!hasQualifiers) { return versionToMatch; } // Check for matching name, if only one found shortcircuit const match = possibleMatches .filter((name) => name.startsWith(nameToMatch)) .filter((name) => semver.satisfies((0, exports.extractNameAndIdentifier)(name).identifier, identifierToMatch)) .map((name) => ({ name, identifier: (0, exports.extractNameAndIdentifier)(name).identifier, })) .reduce((acc, item) => semver.gt(item.identifier, acc.identifier) ? item : acc); return match.name; }; exports.extractCorrectIdentifierBySemver = extractCorrectIdentifierBySemver; //# sourceMappingURL=cli-parser-utils.js.map /***/ }), /***/ 27819: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildDepGraphFromCliOutput = void 0; const dep_graph_1 = __webpack_require__(71479); const __1 = __webpack_require__(423); const parsers_1 = __webpack_require__(75873); const cli_parser_utils_1 = __webpack_require__(80333); const yarn_info_parser_1 = __webpack_require__(79326); const yarn_list_parser_1 = __webpack_require__(97016); const buildDepGraphFromCliOutput = (rawCliOutput, lockfileContent, manifestFileContent) => { const manifestDependencies = JSON.parse(manifestFileContent).dependencies || {}; const lockfileType = (0, __1.getYarnLockfileType)(lockfileContent); const { name: rootName, version: rootVersion } = JSON.parse(manifestFileContent); const pkgManagerVersion = lockfileType === parsers_1.LockfileType.yarn ? '1' : '2'; // Build depMap object from the cli output const formattedCliOutput = pkgManagerVersion === '1' ? (0, yarn_list_parser_1.parseYarnListOutput)(rawCliOutput, manifestDependencies) : (0, yarn_info_parser_1.parseYarnInfoOutput)(rawCliOutput); const rootPkgInfo = rootName ? Object.assign({ name: rootName }, (rootVersion && { version: rootVersion })) : undefined; const pkgManager = { name: 'yarn', version: pkgManagerVersion, }; const builder = new dep_graph_1.DepGraphBuilder(pkgManager, rootPkgInfo); const { topLevelDeps, dependencies: depMap } = formattedCliOutput; // Add all nodes [...depMap.keys()].forEach((name) => { const { name: pkgName, identifier: pkgVersion } = (0, cli_parser_utils_1.extractNameAndIdentifier)(name); builder.addPkgNode({ name: pkgName, version: pkgVersion.split(':').pop() }, name); }); // Deal with root special case first const rootNodeId = builder.rootNodeId; topLevelDeps.forEach((dep) => builder.connectDep(rootNodeId, dep)); // Now rest of deps [...depMap.entries()].forEach(([parent, deps]) => { deps.forEach((dep) => { builder.connectDep(parent, dep); }); }); return builder.build(); }; exports.buildDepGraphFromCliOutput = buildDepGraphFromCliOutput; //# sourceMappingURL=index.js.map /***/ }), /***/ 79326: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseYarnInfoOutput = void 0; const parseYarnInfoOutput = (rawYarnInfoOutput) => { const formattedYarnInfo = rawYarnInfoOutput .split('\n') .filter(Boolean) .map((el) => JSON.parse(el)); const formattedInfoOutput = formattedYarnInfo.reduce((result, { value, children }) => { var _a; const dependencies = ((_a = children.Dependencies) === null || _a === void 0 ? void 0 : _a.map((el) => el.locator.replace(/@virtual:.*#/, '@'))) || []; return result.set(value, dependencies); }, new Map()); const rootWorkspaceKey = [...formattedInfoOutput.keys()].find((el) => el.includes('@workspace:.')); const topLevelDeps = formattedInfoOutput.get(rootWorkspaceKey) || []; // Now we have rootdeps we delete the key formattedInfoOutput.delete(rootWorkspaceKey); return { topLevelDeps, dependencies: formattedInfoOutput }; }; exports.parseYarnInfoOutput = parseYarnInfoOutput; //# sourceMappingURL=yarn-info-parser.js.map /***/ }), /***/ 97016: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseYarnListOutput = void 0; const cli_parser_utils_1 = __webpack_require__(80333); const parseYarnListOutput = (rawYarnListOutput, manifestDependencies) => { const formattedYarnList = JSON.parse(rawYarnListOutput).data.trees; // Reference to all (resolved) dep names to help cleanup in next step const names = formattedYarnList.map((tree) => tree.name); const formattedListOutput = formattedYarnList.reduce((result, tree) => { const dependencies = tree.children.map((child) => (0, cli_parser_utils_1.extractCorrectIdentifierBySemver)(names, child.name)); return result.set(tree.name, dependencies); }, new Map()); const topLevelDeps = getTopLevelDependencies(formattedListOutput, manifestDependencies); return { topLevelDeps, dependencies: formattedListOutput }; }; exports.parseYarnListOutput = parseYarnListOutput; const getTopLevelDependencies = (formattedListOutput, topLevelDeps) => { // This logic is to construct an item for the rootPkg because // we are dealing with a flat map so far so can't tell const names = [...formattedListOutput.keys()]; return Object.entries(topLevelDeps).map(([name, version]) => (0, cli_parser_utils_1.extractCorrectIdentifierBySemver)(names, `${name}@${version}`)); }; //# sourceMappingURL=yarn-list-parser.js.map /***/ }), /***/ 70104: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.config = void 0; const snyk_config_1 = __webpack_require__(8658); exports.config = (0, snyk_config_1.loadConfig)(__dirname + '../..'); //# sourceMappingURL=config.js.map /***/ }), /***/ 61311: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parsePkgJson = exports.parsePnpmWorkspaceProject = exports.parsePnpmWorkspace = exports.parsePnpmProject = exports.extractPkgsFromYarnLockV2 = exports.parseYarnLockV2Project = exports.buildDepGraphYarnLockV2Simple = exports.extractPkgsFromYarnLockV1 = exports.parseYarnLockV1WorkspaceProject = exports.buildDepGraphYarnLockV1WorkspaceCyclesPruned = exports.buildDepGraphYarnLockV1Simple = exports.buildDepGraphYarnLockV1SimpleCyclesPruned = exports.buildDepGraphYarnLockV1Workspace = exports.parseYarnLockV1Project = exports.parseNpmLockV2Project = void 0; const yarn_lock_v1_1 = __webpack_require__(33248); Object.defineProperty(exports, "parseYarnLockV1Project", ({ enumerable: true, get: function () { return yarn_lock_v1_1.parseYarnLockV1Project; } })); Object.defineProperty(exports, "parseYarnLockV1WorkspaceProject", ({ enumerable: true, get: function () { return yarn_lock_v1_1.parseYarnLockV1WorkspaceProject; } })); Object.defineProperty(exports, "buildDepGraphYarnLockV1SimpleCyclesPruned", ({ enumerable: true, get: function () { return yarn_lock_v1_1.buildDepGraphYarnLockV1SimpleCyclesPruned; } })); Object.defineProperty(exports, "buildDepGraphYarnLockV1Simple", ({ enumerable: true, get: function () { return yarn_lock_v1_1.buildDepGraphYarnLockV1Simple; } })); Object.defineProperty(exports, "buildDepGraphYarnLockV1WorkspaceCyclesPruned", ({ enumerable: true, get: function () { return yarn_lock_v1_1.buildDepGraphYarnLockV1WorkspaceCyclesPruned; } })); Object.defineProperty(exports, "buildDepGraphYarnLockV1Workspace", ({ enumerable: true, get: function () { return yarn_lock_v1_1.buildDepGraphYarnLockV1Workspace; } })); Object.defineProperty(exports, "extractPkgsFromYarnLockV1", ({ enumerable: true, get: function () { return yarn_lock_v1_1.extractPkgsFromYarnLockV1; } })); const yarn_lock_v2_1 = __webpack_require__(29807); Object.defineProperty(exports, "buildDepGraphYarnLockV2Simple", ({ enumerable: true, get: function () { return yarn_lock_v2_1.buildDepGraphYarnLockV2Simple; } })); Object.defineProperty(exports, "parseYarnLockV2Project", ({ enumerable: true, get: function () { return yarn_lock_v2_1.parseYarnLockV2Project; } })); Object.defineProperty(exports, "extractPkgsFromYarnLockV2", ({ enumerable: true, get: function () { return yarn_lock_v2_1.extractPkgsFromYarnLockV2; } })); const npm_lock_v2_1 = __webpack_require__(75741); Object.defineProperty(exports, "parseNpmLockV2Project", ({ enumerable: true, get: function () { return npm_lock_v2_1.parseNpmLockV2Project; } })); const pnpm_1 = __webpack_require__(37693); Object.defineProperty(exports, "parsePnpmProject", ({ enumerable: true, get: function () { return pnpm_1.parsePnpmProject; } })); Object.defineProperty(exports, "parsePnpmWorkspace", ({ enumerable: true, get: function () { return pnpm_1.parsePnpmWorkspace; } })); Object.defineProperty(exports, "parsePnpmWorkspaceProject", ({ enumerable: true, get: function () { return pnpm_1.parsePnpmWorkspaceProject; } })); const util_1 = __webpack_require__(46200); Object.defineProperty(exports, "parsePkgJson", ({ enumerable: true, get: function () { return util_1.parsePkgJson; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 61253: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.extractPkgsFromNpmLockV2 = void 0; const extractPkgsFromNpmLockV2 = (pkgLockContent) => { return JSON.parse(pkgLockContent).packages; }; exports.extractPkgsFromNpmLockV2 = extractPkgsFromNpmLockV2; //# sourceMappingURL=extract-npm-lock-v2-pkgs.js.map /***/ }), /***/ 75741: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.matchOverrideKey = exports.getChildNodeKey = exports.buildDepGraphNpmLockV2 = exports.parseNpmLockV2Project = exports.extractPkgsFromNpmLockV2 = void 0; const extract_npm_lock_v2_pkgs_1 = __webpack_require__(61253); Object.defineProperty(exports, "extractPkgsFromNpmLockV2", ({ enumerable: true, get: function () { return extract_npm_lock_v2_pkgs_1.extractPkgsFromNpmLockV2; } })); const dep_graph_1 = __webpack_require__(71479); const util_1 = __webpack_require__(46200); const errors_1 = __webpack_require__(1706); const parsers_1 = __webpack_require__(75873); const semver = __webpack_require__(50460); const micromatch = __webpack_require__(70850); const pathUtil = __webpack_require__(71017); const event_loop_spinner_1 = __webpack_require__(77158); const parseNpmLockV2Project = async (pkgJsonContent, pkgLockContent, options) => { const { includeDevDeps, strictOutOfSync, includeOptionalDeps, pruneNpmStrictOutOfSync, } = options; const pkgJson = (0, util_1.parsePkgJson)(pkgJsonContent); const pkgs = (0, extract_npm_lock_v2_pkgs_1.extractPkgsFromNpmLockV2)(pkgLockContent); const depgraph = await (0, exports.buildDepGraphNpmLockV2)(pkgs, pkgJson, { includeDevDeps, includeOptionalDeps, strictOutOfSync, pruneNpmStrictOutOfSync, }); return depgraph; }; exports.parseNpmLockV2Project = parseNpmLockV2Project; const buildDepGraphNpmLockV2 = async (npmLockPkgs, pkgJson, options) => { const { includeDevDeps, strictOutOfSync, includeOptionalDeps, pruneNpmStrictOutOfSync, } = options; const depGraphBuilder = new dep_graph_1.DepGraphBuilder({ name: 'npm' }, { name: pkgJson.name, version: pkgJson.version }); const topLevelDeps = (0, util_1.getTopLevelDeps)(pkgJson, { includeDevDeps, includeOptionalDeps, includePeerDeps: true, }); const rootNode = { id: 'root-node', name: pkgJson.name, version: pkgJson.version, dependencies: topLevelDeps, isDev: false, inBundle: false, key: '', }; const pkgKeysByName = Object.keys(npmLockPkgs).reduce((acc, key) => { const name = key.replace(/.*node_modules\//, ''); if (!name) { return acc; } if (!acc.has(name)) { acc.set(name, []); } acc.get(name).push(key); return acc; }, new Map()); const visitedMap = new Set(); await dfsVisit(depGraphBuilder, rootNode, visitedMap, npmLockPkgs, strictOutOfSync, includeDevDeps, includeOptionalDeps, [], pkgKeysByName, pkgJson.overrides, pruneNpmStrictOutOfSync); return depGraphBuilder.build(); }; exports.buildDepGraphNpmLockV2 = buildDepGraphNpmLockV2; const dfsVisit = async (depGraphBuilder, node, visitedMap, npmLockPkgs, strictOutOfSync, includeDevDeps, includeOptionalDeps, ancestry, pkgKeysByName, overrides, pruneNpmStrictOutOfSync) => { visitedMap.add(node.id); for (const [name, depInfo] of Object.entries(node.dependencies || {})) { if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } const childNode = getChildNode(name, depInfo, npmLockPkgs, strictOutOfSync, includeDevDeps, includeOptionalDeps, [ ...ancestry, { name: node.name, version: node.version, key: node.key || '', inBundle: node.inBundle || false, }, ], pkgKeysByName, overrides, pruneNpmStrictOutOfSync); if (!visitedMap.has(childNode.id)) { (0, util_1.addPkgNodeToGraph)(depGraphBuilder, childNode, {}); await dfsVisit(depGraphBuilder, childNode, visitedMap, npmLockPkgs, strictOutOfSync, includeDevDeps, includeOptionalDeps, [ ...ancestry, { name: node.name, version: node.version, key: node.key, inBundle: node.inBundle || false, }, ], pkgKeysByName, overrides); } depGraphBuilder.connectDep(node.id, childNode.id); } }; const getChildNode = (name, depInfo, pkgs, strictOutOfSync, includeDevDeps, includeOptionalDeps, ancestry, pkgKeysByName, overrides, pruneNpmStrictOutOfSync) => { let version = depInfo.version; const override = overrides && checkOverrides([...ancestry, { name, version }], overrides); if (override) { version = override; } if (version.startsWith('npm:')) { version = version.split('@').pop() || version; } let childNodeKey = (0, exports.getChildNodeKey)(name, version, ancestry, pkgs, pkgKeysByName, pruneNpmStrictOutOfSync); if (!childNodeKey) { if (strictOutOfSync) { throw new errors_1.OutOfSyncError(`${name}@${depInfo.version}`, parsers_1.LockfileType.npm); } else { return { id: `${name}@${depInfo.version}`, name: name, version: depInfo.version, dependencies: {}, isDev: depInfo.isDev, missingLockFileEntry: true, key: '', }; } } let depData = pkgs[childNodeKey]; const resolvedToWorkspace = () => { // Workspaces can be set as an array, or as an object // { packages: [] }, this can be checked in // https://github.com/npm/map-workspaces/blob/ff82968a3dbb78659fb7febfce4841bf58c514de/lib/index.js#L27-L41 if (pkgs['']['workspaces'] === undefined) { return false; } const workspacesDeclaration = Array.isArray(pkgs['']['workspaces']['packages']) ? pkgs['']['workspaces']['packages'] : pkgs['']['workspaces'] || []; const resolvedPath = depData.resolved || ''; const fixedResolvedPath = resolvedPath.replace(/\\/g, '/'); const normalizedWorkspacesDefn = workspacesDeclaration.map((p) => { return pathUtil.normalize(p).replace(/\\/g, '/'); }); return micromatch.isMatch(fixedResolvedPath, normalizedWorkspacesDefn); }; // Check for workspaces if (depData['link'] && resolvedToWorkspace()) { childNodeKey = depData.resolved; depData = pkgs[depData.resolved]; } const dependencies = (0, util_1.getGraphDependencies)(depData.dependencies || {}, depInfo.isDev); const devDependencies = includeDevDeps ? (0, util_1.getGraphDependencies)(depData.devDependencies || {}, depInfo.isDev) : {}; const optionalDependencies = includeOptionalDeps ? (0, util_1.getGraphDependencies)(depData.optionalDependencies || {}, depInfo.isDev) : {}; return { id: `${name}@${depData.version}`, name: name, version: depData.version, dependencies: Object.assign(Object.assign(Object.assign({}, dependencies), devDependencies), optionalDependencies), isDev: depInfo.isDev, inBundle: depData.inBundle, key: childNodeKey, }; }; const getChildNodeKey = (name, version, ancestry, pkgs, pkgKeysByName, pruneNpmStrictOutOfSync) => { // This is a list of all our possible options for the childKey const candidateKeys = pkgKeysByName.get(name); // Lockfile missing entry if (!candidateKeys) { return undefined; } // If we only have one candidate then we just take it if (candidateKeys.length === 1) { if (semver.validRange(version) && pkgs[candidateKeys[0]].version && !semver.satisfies(pkgs[candidateKeys[0]].version, version) && pruneNpmStrictOutOfSync) { //TODO: Add some logs to monitor return undefined; } return candidateKeys[0]; } // If we are bundled we assume we are scoped by the bundle root at least // otherwise the ancestry root is the root ignoring the true root const isBundled = ancestry[ancestry.length - 1].inBundle; const rootOperatingIdx = isBundled ? ancestry.findIndex((el) => el.inBundle === true) - 1 : 1; const ancestryFromRootOperatingIdx = [ ...ancestry.slice(rootOperatingIdx).map((el) => el.name), name, ]; // We filter on a number of cases let filteredCandidates = candidateKeys.filter((candidate) => { // This is splitting the candidate that looks like // `node_modules/a/node_modules/b` into ["a", "b"] // To do this we remove the first node_modules substring // and then split on the rest const candidateAncestry = (candidate.startsWith('node_modules/') ? candidate.replace('node_modules/', '').split('/node_modules/') : candidate.split('/node_modules/')).map((el) => { if (pkgs[el]) { return pkgs[el].name || el; } return el; }); // Check the ancestry of the candidate is a subset of // the current pkg. If it is not then it can't be a // valid key. const isCandidateAncestryIsSubsetOfPkgAncestry = candidateAncestry.every((pkg) => { return ancestryFromRootOperatingIdx.includes(pkg); }); if (isCandidateAncestryIsSubsetOfPkgAncestry === false) { return false; } // If we are bundled we assume the bundle root is the first value // in the candidates scoping if (isBundled) { const doesBundledPkgShareBundleRoot = candidateAncestry[0] === ancestryFromRootOperatingIdx[0]; if (doesBundledPkgShareBundleRoot === false) { return false; } } // So now we can check semver to filter out some values // if our version is valid semver if (semver.validRange(version)) { const candidatePkgVersion = pkgs[candidate].version; const doesVersionSatisfySemver = semver.satisfies(candidatePkgVersion, version); return doesVersionSatisfySemver; } return true; }); if (filteredCandidates.length === 1) { return filteredCandidates[0]; } const ancestryNames = ancestry.map((el) => el.name).concat(name); while (ancestryNames.length > 0) { const possibleKey = `node_modules/${ancestryNames.join('/node_modules/')}`; if (filteredCandidates.includes(possibleKey)) { return possibleKey; } ancestryNames.shift(); } // Here we go through th eancestry backwards to find the nearest // ancestor package const reversedAncestry = ancestry.reverse(); for (let parentIndex = 0; parentIndex < reversedAncestry.length; parentIndex++) { const parentName = reversedAncestry[parentIndex].name; const possibleFilteredKeys = filteredCandidates.filter((key) => key.includes(parentName)); if (possibleFilteredKeys.length === 1) { return possibleFilteredKeys[0]; } if (possibleFilteredKeys.length === 0) { continue; } filteredCandidates = possibleFilteredKeys; } return undefined; }; exports.getChildNodeKey = getChildNodeKey; const checkOverrides = (ancestry, overrides) => { const ancestryWithoutRoot = ancestry.slice(1); // First traverse into overrides from root down for (const [idx, pkg] of ancestryWithoutRoot.entries()) { // Do we have this in overrides const override = (0, exports.matchOverrideKey)(overrides, pkg); // If we dont find current element move down the ancestry if (!override) { continue; } // If we find a string as override we know we found what we want *if* // we are at our root if (idx + 1 === ancestryWithoutRoot.length && typeof override === 'string') { return override; } // If we don't find a string we might have a dotted reference // we only care about this if we are the final element in the ancestry. if (idx + 1 === ancestryWithoutRoot.length && override['.']) { return override['.']; } // If we don't find a string or a dotted reference we need to recurse // to find the override const recursiveOverride = checkOverrides(ancestryWithoutRoot, override); // If we get a non-undefined result, it is our answer if (recursiveOverride) { return recursiveOverride; } } return; }; // Here we have to match our pkg to // possible keys in the overrides object const matchOverrideKey = (overrides, pkg) => { if (overrides[pkg.name]) { return overrides[pkg.name]; } const overrideKeysNameToVersions = Object.keys(overrides).reduce((acc, key) => { // Split the key to separate the package name from the version spec const atIndex = key.lastIndexOf('@'); const name = key.substring(0, atIndex); const versionSpec = key.substring(atIndex + 1); // Check if the package name already exists in the accumulator if (!acc[name]) { acc[name] = []; } // Add the version spec to the list of versions for this package name acc[name].push(versionSpec); return acc; }, {}); const computedOverrides = overrideKeysNameToVersions[pkg.name]; if (computedOverrides) { for (const versionSpec of computedOverrides) { const isPkgVersionSubsetOfOverrideSpec = semver.subset(pkg.version, semver.validRange(versionSpec)); if (isPkgVersionSubsetOfOverrideSpec) { return overrides[`${pkg.name}@${versionSpec}`]; } } } return null; }; exports.matchOverrideKey = matchOverrideKey; //# sourceMappingURL=index.js.map /***/ }), /***/ 32032: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildDepGraphPnpm = void 0; const dep_graph_1 = __webpack_require__(71479); const util_1 = __webpack_require__(46200); const utils_1 = __webpack_require__(94865); const event_loop_spinner_1 = __webpack_require__(77158); const error_catalog_nodejs_public_1 = __webpack_require__(88404); const out_of_sync_error_1 = __webpack_require__(9340); const __1 = __webpack_require__(423); const debugModule = __webpack_require__(15158); const constants_1 = __webpack_require__(89468); const debug = debugModule('snyk-pnpm-workspaces'); const buildDepGraphPnpm = async (lockFileParser, pkgJson, options, importer) => { var _a; const { strictOutOfSync, includeOptionalDeps, includeDevDeps, pruneWithinTopLevelDeps, } = options; const depGraphBuilder = new dep_graph_1.DepGraphBuilder({ name: 'pnpm' }, { name: pkgJson.name, version: pkgJson.version || constants_1.UNDEFINED_VERSION }); lockFileParser.extractedPackages = lockFileParser.extractPackages(); const extractedPnpmPkgs = lockFileParser.extractedPackages; const topLevelDeps = (0, util_1.getTopLevelDeps)(pkgJson, options); const extractedTopLevelDeps = lockFileParser.extractTopLevelDependencies(options, importer) || {}; for (const name of Object.keys(topLevelDeps)) { if (!extractedTopLevelDeps[name]) { if (!strictOutOfSync) { continue; } const errMessage = `Dependency ${name} was not found in ` + `${out_of_sync_error_1.LOCK_FILE_NAME[__1.LockfileType.pnpm]}. Your package.json and ` + `${out_of_sync_error_1.LOCK_FILE_NAME[__1.LockfileType.pnpm]} are probably out of sync. Please run ` + `"${out_of_sync_error_1.INSTALL_COMMAND[__1.LockfileType.pnpm]}" and try again.`; debug(errMessage); throw new error_catalog_nodejs_public_1.OpenSourceEcosystems.PnpmOutOfSyncError(errMessage); } topLevelDeps[name].version = extractedTopLevelDeps[name].version; } const rootNode = { id: 'root-node', name: pkgJson.name, version: pkgJson.version, dependencies: topLevelDeps, isDev: false, }; const rootNodeId = `${pkgJson.name}@${pkgJson.version}`; await dfsVisit(depGraphBuilder, rootNodeId, rootNode, extractedPnpmPkgs, strictOutOfSync, includeOptionalDeps, includeDevDeps, ((_a = pkgJson.pnpm) === null || _a === void 0 ? void 0 : _a.overrides) || {}, pruneWithinTopLevelDeps, lockFileParser); return depGraphBuilder.build(); }; exports.buildDepGraphPnpm = buildDepGraphPnpm; /** * Use DFS to add all nodes and edges to the depGraphBuilder and prune cyclic nodes. * The visitedMap keep track of which nodes have already been discovered during traversal. * - If a node doesn't exist in the map, it means it hasn't been visited. * - If a node is already visited, simply connect the new node with this node. */ const dfsVisit = async (depGraphBuilder, rootNodeId, node, extractedPnpmPkgs, strictOutOfSync, includeOptionalDeps, includeDevDeps, overrides, pruneWithinTopLevel, lockFileParser, visited) => { for (const [name, depInfo] of Object.entries(node.dependencies || {})) { if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } const localVisited = visited || new Set(); const childNode = (0, utils_1.getPnpmChildNode)(name, depInfo, extractedPnpmPkgs, strictOutOfSync, includeOptionalDeps, includeDevDeps, lockFileParser); if (localVisited.has(childNode.id) || childNode.id == rootNodeId) { if (pruneWithinTopLevel) { const prunedId = `${childNode.id}:pruned`; depGraphBuilder.addPkgNode({ name: childNode.name, version: childNode.version }, prunedId, { labels: Object.assign({ scope: childNode.isDev ? 'dev' : 'prod', pruned: 'true' }, (node.missingLockFileEntry && { missingLockFileEntry: 'true', })), }); depGraphBuilder.connectDep(node.id, prunedId); } else { depGraphBuilder.connectDep(node.id, childNode.id); } continue; } depGraphBuilder.addPkgNode({ name: childNode.name, version: childNode.version }, childNode.id, { labels: Object.assign({ scope: childNode.isDev ? 'dev' : 'prod' }, (node.missingLockFileEntry && { missingLockFileEntry: 'true', })), }); depGraphBuilder.connectDep(node.id, childNode.id); localVisited.add(childNode.id); await dfsVisit(depGraphBuilder, rootNodeId, childNode, extractedPnpmPkgs, strictOutOfSync, includeOptionalDeps, includeDevDeps, overrides, pruneWithinTopLevel, lockFileParser, localVisited); } }; //# sourceMappingURL=build-dep-graph-pnpm.js.map /***/ }), /***/ 89468: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UNDEFINED_VERSION = void 0; exports.UNDEFINED_VERSION = 'undefined'; //# sourceMappingURL=constants.js.map /***/ }), /***/ 37693: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parsePnpmWorkspaceProject = exports.parsePnpmWorkspace = exports.parsePnpmProject = void 0; const parse_project_1 = __webpack_require__(26864); Object.defineProperty(exports, "parsePnpmProject", ({ enumerable: true, get: function () { return parse_project_1.parsePnpmProject; } })); const parse_workspace_1 = __webpack_require__(35173); Object.defineProperty(exports, "parsePnpmWorkspace", ({ enumerable: true, get: function () { return parse_workspace_1.parsePnpmWorkspace; } })); const parse_workspace_project_1 = __webpack_require__(43305); Object.defineProperty(exports, "parsePnpmWorkspaceProject", ({ enumerable: true, get: function () { return parse_workspace_project_1.parsePnpmWorkspaceProject; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 74093: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getPnpmLockfileParser = void 0; const js_yaml_1 = __webpack_require__(59572); const lockfile_v6_1 = __webpack_require__(84336); const lockfile_v5_1 = __webpack_require__(3704); const lockfile_v9_1 = __webpack_require__(91924); const error_catalog_nodejs_public_1 = __webpack_require__(88404); const utils_1 = __webpack_require__(4426); function getPnpmLockfileParser(pnpmLockContent, lockfileVersion, workspaceArgs) { // In case of no dependencies, pnpm@7 (lokfile version 5) // does not create a lockfile at `pnpm install` // so if there is no lockfile content, default to lockfile version 5 if (!pnpmLockContent) { return new lockfile_v5_1.LockfileV5Parser(pnpmLockContent, workspaceArgs); } const rawPnpmLock = (0, js_yaml_1.load)(pnpmLockContent, { json: true, schema: js_yaml_1.FAILSAFE_SCHEMA, }); const version = rawPnpmLock.lockfileVersion; if (lockfileVersion === utils_1.NodeLockfileVersion.PnpmLockV5 || version.startsWith('5')) { return new lockfile_v5_1.LockfileV5Parser(rawPnpmLock, workspaceArgs); } if (lockfileVersion === utils_1.NodeLockfileVersion.PnpmLockV6 || version.startsWith('6')) { return new lockfile_v6_1.LockfileV6Parser(rawPnpmLock, workspaceArgs); } if (lockfileVersion === utils_1.NodeLockfileVersion.PnpmLockV9 || version.startsWith('9')) { return new lockfile_v9_1.LockfileV9Parser(rawPnpmLock, workspaceArgs); } throw new error_catalog_nodejs_public_1.OpenSourceEcosystems.PnpmUnsupportedLockfileVersionError(`The pnpm-lock.yaml lockfile version ${lockfileVersion} is not supported`); } exports.getPnpmLockfileParser = getPnpmLockfileParser; //# sourceMappingURL=index.js.map /***/ }), /***/ 85811: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PnpmLockfileParser = void 0; const semver_1 = __webpack_require__(50460); const pathUtil = __webpack_require__(71017); const lodash_1 = __webpack_require__(96486); const debugModule = __webpack_require__(15158); const constants_1 = __webpack_require__(89468); const debug = debugModule('snyk-pnpm-workspaces'); class PnpmLockfileParser { constructor(rawPnpmLock, workspaceArgs) { this.rawPnpmLock = rawPnpmLock; this.lockFileVersion = rawPnpmLock.lockfileVersion; this.workspaceArgs = workspaceArgs; this.packages = rawPnpmLock.packages || {}; this.extractedPackages = {}; this.resolvedPackages = {}; this.importers = this.normaliseImporters(rawPnpmLock); } isWorkspaceLockfile() { var _a; return (_a = this.workspaceArgs) === null || _a === void 0 ? void 0 : _a.isWorkspace; } extractPackages() { // Packages should be parsed only one time for a parser if (Object.keys(this.extractedPackages).length > 0) { return this.extractedPackages; } const packages = {}; Object.entries(this.packages).forEach(([depPath, versionData]) => { // name and version are optional in version data - if they don't show up in version data, they can be deducted from the dependency path const { name, version } = versionData; let parsedPath = {}; // Exclude transitive peer deps from depPath // e.g. '/cdktf-cli@0.20.3(ink@3.2.0)(react@17.0.2)' -> cdktf-cli@0.20.3 depPath = this.excludeTransPeerDepsVersions(depPath); if (!(version && name)) { parsedPath = this.parseDepPath(depPath); } const pkg = { id: depPath, name: name || parsedPath.name, version: version || parsedPath.version || depPath, isDev: versionData.dev == 'true', dependencies: versionData.dependencies || {}, devDependencies: versionData.devDependencies || {}, optionalDependencies: versionData.optionalDependencies || {}, }; packages[`${pkg.name}@${pkg.version}`] = pkg; this.resolvedPackages[depPath] = `${pkg.name}@${pkg.version}`; }); return packages; } extractTopLevelDependencies(options, importer) { var _a, _b; let root = this.rawPnpmLock; if (importer) { const { name, version } = (_a = this.workspaceArgs) === null || _a === void 0 ? void 0 : _a.projectsVersionMap[importer]; if ( // Return early because dependencies were already normalized for this importer // as part of another's importer dependency and stored in extractedPackages this.extractedPackages[`${name}@${version}`] && this.extractedPackages[`${name}@${version}`].localWorkspacePackage && !(0, lodash_1.isEmpty)(this.extractedPackages[`${name}@${version}`].dependencies)) { return this.normalizedPkgToTopLevel(this.extractedPackages[`${name}@${version}`]); } root = this.rawPnpmLock.importers[importer]; } const prodDeps = this.normalizeTopLevelDeps(root.dependencies || {}, false, importer); const devDeps = options.includeDevDeps ? this.normalizeTopLevelDeps(root.devDependencies || {}, true, importer) : {}; const optionalDeps = options.includeOptionalDeps ? this.normalizeTopLevelDeps(root.optionalDependencies || {}, false, importer) : {}; const peerDeps = options.includePeerDeps ? this.normalizeTopLevelDeps(root.peerDependencies || {}, false, importer) : {}; if (importer) { const { name, version } = (_b = this.workspaceArgs) === null || _b === void 0 ? void 0 : _b.projectsVersionMap[importer]; this.extractedPackages[`${name}@${version}`] = { id: `${name}@${version}`, name: name, version: version, dependencies: this.topLevelDepsToNormalizedPkgs(prodDeps), devDependencies: this.topLevelDepsToNormalizedPkgs(devDeps), optionalDependencies: this.topLevelDepsToNormalizedPkgs(optionalDeps), isDev: false, localWorkspacePackage: true, }; } return Object.assign(Object.assign(Object.assign(Object.assign({}, prodDeps), devDeps), optionalDeps), peerDeps); } normalizedPkgToTopLevel(pkg) { const topLevel = {}; Object.keys(pkg.dependencies).forEach((depName) => (topLevel[depName] = { name: depName, version: pkg.dependencies[depName], isDev: false, })); Object.keys(pkg.devDependencies).forEach((depName) => (topLevel[depName] = { name: depName, version: pkg.devDependencies[depName], isDev: true, })); return topLevel; } topLevelDepsToNormalizedPkgs(deps) { const normalizedPkgs = {}; Object.values(deps).forEach((dep) => (normalizedPkgs[dep.name] = dep.version)); return normalizedPkgs; } normalizeVersion(name, version, isDev, importerName) { if (this.isWorkspaceLockfile()) { version = this.resolveWorkspacesCrossReference(name, version, isDev, importerName); } if (!(0, semver_1.valid)(version)) { version = this.excludeTransPeerDepsVersions(version); if (!(0, semver_1.valid)(version)) { // for npm and git ref packages // they show up in packages with keys equal to the version in top level deps // e.g. body-parser with version github.com/expressjs/body-parser/263f602e6ae34add6332c1eb4caa808893b0b711 if (this.packages[version]) { return this.packages[version].version || version; } if (this.packages[`${name}@${version}`]) { return this.packages[`${name}@${version}`].version || version; } } } return version; } resolveWorkspacesCrossReference(name, version, isDev, importerName) { if (!this.workspaceArgs) { return version; } if (version.startsWith('link:')) { // In workspaces example: // package-b: // specifier: 1.0.0 // version: link:../pkg-b const depPath = version.split('link:')[1]; const resolvedPathDep = pathUtil .join(importerName || '.', depPath) .replace(/\\/g, '/'); // cross referenced package, we add it to the extracted packages const mappedProjInfo = this.workspaceArgs.projectsVersionMap[resolvedPathDep]; if (!mappedProjInfo) { debug(`Importer ${resolvedPathDep} discovered as a dependency of ${importerName} was not found in the lockfile`); version = constants_1.UNDEFINED_VERSION; } else { version = mappedProjInfo.version; } if (!version) { version = constants_1.UNDEFINED_VERSION; } // Stop recursion here if this package was already normalized and stored in extractedPackages if (this.extractedPackages[`${name}@${version}`]) { return version; } // Initialize this package before recursive calls to avoid inifinte recursion in cycles // We can avoid keeping a visited arrat this way this.extractedPackages[`${name}@${version}`] = { name, version, id: `${name}@${version}`, isDev, dependencies: {}, devDependencies: {}, localWorkspacePackage: true, }; const subDeps = this.rawPnpmLock.importers[resolvedPathDep] || { dependencies: {}, devDependencies: {}, optionalDependencies: {}, }; const resolvedDeps = this.normalizePackagesDeps(subDeps.dependencies || {}, isDev, resolvedPathDep); const resolvedDevDeps = this.normalizePackagesDeps(subDeps.devDependencies || {}, true, resolvedPathDep); const resolvedOptionalDeps = this.normalizePackagesDeps(subDeps.optionalDependencies || {}, true, resolvedPathDep); this.extractedPackages[`${name}@${version}`] = { name, version, id: `${name}@${version}`, isDev, dependencies: resolvedDeps, devDependencies: resolvedDevDeps, optionalDependencies: resolvedOptionalDeps, localWorkspacePackage: true, }; } return version; } } exports.PnpmLockfileParser = PnpmLockfileParser; //# sourceMappingURL=lockfile-parser.js.map /***/ }), /***/ 3704: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LockfileV5Parser = void 0; const dependency_path_1 = __webpack_require__(36577); const lockfile_parser_1 = __webpack_require__(85811); class LockfileV5Parser extends lockfile_parser_1.PnpmLockfileParser { constructor(rawPnpmLock, workspaceArgs) { // In case of no dependencies, pnpm@7 (lokfile version 5) // does not create a lockfile at `pnpm install` if (!rawPnpmLock) { rawPnpmLock = { lockfileVersion: '5', }; } super(rawPnpmLock, workspaceArgs); } parseDepPath(depPath) { // The 'dependency-path' parsing package only works for lockfiles v5 const { name, version } = (0, dependency_path_1.parse)(depPath); if (!version) { return { name }; } return { name, version: this.excludeTransPeerDepsVersions(version), }; } normalizeTopLevelDeps(dependencies, isDev, importerName) { return Object.entries(dependencies).reduce((pnpmDeps, [name, version]) => { version = this.normalizeVersion(name, version, isDev, importerName); pnpmDeps[name] = { name, version, isDev, }; return pnpmDeps; }, {}); } normalizePackagesDeps(dependencies, isDev, importerName) { return Object.entries(dependencies).reduce((pnpmDeps, [name, version]) => { version = this.normalizeVersion(name, version, isDev, importerName); pnpmDeps[name] = version; return pnpmDeps; }, {}); } // Dependency path and versions include transitive peer dependencies separated by '_' // e.g. in dependencies // dependencies: // acorn-jsx: 5.3.2_acorn@7.4.1 // OR in dependency path: // '/@babel/preset-typescript/7.12.13_@babel+core@7.12.13' // https://github.com/pnpm/spec/blob/master/dependency-path.md excludeTransPeerDepsVersions(fullVersionStr) { if (!fullVersionStr.includes('/')) { return fullVersionStr.split('_')[0]; } // When dealing with dependency paths, the dependency name can include '_' // so we need to make sure the '_' we split by is after '/' const splitSlashes = fullVersionStr.split('/'); const stringAfterLastSlash = splitSlashes[splitSlashes.length - 1]; const stringBeforeLastSlash = fullVersionStr.split(stringAfterLastSlash)[0]; const stringBetweenLastSlashAndUnderscore = stringAfterLastSlash.split('_')[0]; return `${stringBeforeLastSlash}${stringBetweenLastSlashAndUnderscore}`; } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types normaliseImporters(rawPnpmLock) { if (!('importers' in rawPnpmLock)) { return {}; } const rawImporters = rawPnpmLock.importers; return Object.entries(rawImporters).reduce( // eslint-disable-next-line @typescript-eslint/no-explicit-any (acc, [key, val]) => { // No deps case if (!('dependencies' in val)) { return Object.assign(Object.assign({}, acc), { [key]: {} }); } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const deps = val.dependencies; const depsNormalized = Object.fromEntries(Object.entries(deps).map(([depName, version]) => { return [depName, version]; })); return Object.assign(Object.assign({}, acc), { [key]: depsNormalized }); }, {}); } } exports.LockfileV5Parser = LockfileV5Parser; //# sourceMappingURL=lockfile-v5.js.map /***/ }), /***/ 84336: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LockfileV6Parser = void 0; const lockfile_parser_1 = __webpack_require__(85811); class LockfileV6Parser extends lockfile_parser_1.PnpmLockfileParser { constructor(rawPnpmLock, workspaceArgs) { super(rawPnpmLock, workspaceArgs); this.settings = rawPnpmLock.settings; } parseDepPath(depPath) { // Check if path is absolute (doesn't start with '/') // If it's not absolute, omit first '/' depPath = LockfileV6Parser.isAbsoluteDepenencyPath(depPath) ? depPath : depPath.substring(1); // This is the case for scoped packages, get version based on the last occurence of '@' separator // to include the '@' in the name if (depPath.startsWith('@')) { // e.g. @babel/code-frame@7.24.2 -> name: @babel/code-frame and version: 7.24.2 const sepIndex = depPath.lastIndexOf('@'); if (sepIndex === -1) { return {}; } const name = depPath.substring(0, sepIndex); const version = depPath.substring(sepIndex + 1); return { name, version, }; } // For non-scoped packages, the dependency specifier should contain only // one '@', separating the name and version const [name, version] = depPath.split('@'); return { name, version, }; } normalizeTopLevelDeps(dependencies, isDev, importerName) { return Object.entries(dependencies).reduce((pnpmDeps, [name, depInfo]) => { const version = this.normalizeVersion(name, depInfo.version, isDev, importerName); pnpmDeps[name] = { name, version, isDev, }; return pnpmDeps; }, {}); } normalizePackagesDeps(dependencies, isDev, importerName) { return Object.entries(dependencies).reduce((pnpmDeps, [name, depInfo]) => { const version = this.normalizeVersion(name, depInfo.version, isDev, importerName); pnpmDeps[name] = version; return pnpmDeps; }, {}); } // Dependency path and versions include transitive peer dependencies encapsulated in dependencies // e.g. '/cdktf-cli@0.20.3(ink@3.2.0)(react@17.0.2)' -> cdktf-cli@0.20.3 excludeTransPeerDepsVersions(fullVersionStr) { return fullVersionStr.split('(')[0]; } static isAbsoluteDepenencyPath(dependencyPath) { return dependencyPath[0] !== '/'; } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types normaliseImporters(rawPnpmLock) { if (!('importers' in rawPnpmLock)) { return {}; } const rawImporters = rawPnpmLock.importers; return Object.entries(rawImporters).reduce( // eslint-disable-next-line @typescript-eslint/no-explicit-any (acc, [key, val]) => { // No deps case if (!('dependencies' in val)) { return Object.assign(Object.assign({}, acc), { [key]: {} }); } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const deps = val.dependencies; const depsNormalized = Object.fromEntries(Object.entries(deps).map(([depName, depInfo]) => { return [depName, depInfo.version]; })); return Object.assign(Object.assign({}, acc), { [key]: depsNormalized }); }, {}); } } exports.LockfileV6Parser = LockfileV6Parser; //# sourceMappingURL=lockfile-v6.js.map /***/ }), /***/ 91924: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LockfileV9Parser = void 0; const lockfile_v6_1 = __webpack_require__(84336); const DEFAULT_WORKSPACE_ARGS = { isWorkspace: true, projectsVersionMap: {}, }; class LockfileV9Parser extends lockfile_v6_1.LockfileV6Parser { constructor(rawPnpmLock, workspaceArgs = DEFAULT_WORKSPACE_ARGS) { super(rawPnpmLock, workspaceArgs); this.settings = rawPnpmLock.settings; this.packages = {}; this.snapshots = rawPnpmLock.snapshots || {}; Object.entries(this.snapshots).forEach(([depPath, versionData]) => { const normalizedDepPath = this.excludeTransPeerDepsVersions(depPath); this.packages[normalizedDepPath] = Object.assign(Object.assign({}, rawPnpmLock.packages[normalizedDepPath]), versionData); }); } } exports.LockfileV9Parser = LockfileV9Parser; //# sourceMappingURL=lockfile-v9.js.map /***/ }), /***/ 26864: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parsePnpmProject = void 0; const util_1 = __webpack_require__(46200); const build_dep_graph_pnpm_1 = __webpack_require__(32032); const index_1 = __webpack_require__(74093); const parsePnpmProject = async (pkgJsonContent, pnpmLockContent, options, lockfileVersion) => { const { includeDevDeps, includePeerDeps, includeOptionalDeps, strictOutOfSync, pruneWithinTopLevelDeps, } = options; let importer = ''; const pkgJson = (0, util_1.parsePkgJson)(pkgJsonContent); const lockFileParser = (0, index_1.getPnpmLockfileParser)(pnpmLockContent, lockfileVersion); // Lockfile V9 simple project has the root importer if (lockFileParser.lockFileVersion.startsWith('9')) { importer = '.'; lockFileParser.workspaceArgs = { projectsVersionMap: { '.': { name: pkgJson.name, version: pkgJson.version }, }, isWorkspace: true, }; } const depgraph = await (0, build_dep_graph_pnpm_1.buildDepGraphPnpm)(lockFileParser, pkgJson, { includeDevDeps, strictOutOfSync, includePeerDeps, includeOptionalDeps, pruneWithinTopLevelDeps, }, importer); return depgraph; }; exports.parsePnpmProject = parsePnpmProject; //# sourceMappingURL=parse-project.js.map /***/ }), /***/ 43305: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parsePnpmWorkspaceProject = void 0; const util_1 = __webpack_require__(46200); const build_dep_graph_pnpm_1 = __webpack_require__(32032); const index_1 = __webpack_require__(74093); const constants_1 = __webpack_require__(89468); const parsePnpmWorkspaceProject = async (pkgJsonContent, pnpmLockfileContents, options, importer, lockfileVersion) => { const { includeDevDeps, includePeerDeps, includeOptionalDeps, strictOutOfSync, pruneWithinTopLevelDeps, } = options; const lockFileParser = (0, index_1.getPnpmLockfileParser)(pnpmLockfileContents, lockfileVersion); const pkgJson = (0, util_1.parsePkgJson)(pkgJsonContent); lockFileParser.workspaceArgs = { isWorkspace: true, projectsVersionMap: { [importer]: { name: pkgJson.name, version: pkgJson.version || constants_1.UNDEFINED_VERSION, }, }, }; const depGraph = await (0, build_dep_graph_pnpm_1.buildDepGraphPnpm)(lockFileParser, pkgJson, { includeDevDeps, includePeerDeps, strictOutOfSync, includeOptionalDeps, pruneWithinTopLevelDeps, }, importer); return depGraph; }; exports.parsePnpmWorkspaceProject = parsePnpmWorkspaceProject; //# sourceMappingURL=parse-workspace-project.js.map /***/ }), /***/ 35173: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parsePnpmWorkspace = void 0; const debugModule = __webpack_require__(15158); const path = __webpack_require__(71017); const util_1 = __webpack_require__(46200); const build_dep_graph_pnpm_1 = __webpack_require__(32032); const index_1 = __webpack_require__(74093); const utils_1 = __webpack_require__(4426); const utils_2 = __webpack_require__(94865); const constants_1 = __webpack_require__(89468); const debug = debugModule('snyk-pnpm-workspaces'); // Compute project versions map // This is needed because the lockfile doesn't present the version of // a project that's part of a workspace, we need to retrieve it from // its corresponding package.json function computeProjectVersionMaps(root, targets) { const projectsVersionMap = {}; for (const target of targets) { const directory = path.join(root, target); const packageJsonFileName = path.join(directory, 'package.json'); const packageJson = (0, utils_2.getFileContents)(root, packageJsonFileName); try { const parsedPkgJson = (0, util_1.parsePkgJson)(packageJson.content); projectsVersionMap[target] = { version: parsedPkgJson.version || constants_1.UNDEFINED_VERSION, name: parsedPkgJson.name, }; } catch (err) { debug(`Error getting version for project: ${packageJsonFileName}. ERROR: ${err}`); continue; } } return projectsVersionMap; } const parsePnpmWorkspace = async (root, workspaceDir, options) => { const scannedProjects = []; const { includeDevDeps, includePeerDeps, includeOptionalDeps, strictOutOfSync, pruneWithinTopLevelDeps, } = options; const pnpmLockfileContents = (0, utils_2.getFileContents)(root, path.join(workspaceDir, 'pnpm-lock.yaml')).content; const lockfileVersion = (0, utils_1.getPnpmLockfileVersion)(pnpmLockfileContents); const lockFileParser = (0, index_1.getPnpmLockfileParser)(pnpmLockfileContents, lockfileVersion); const projectVersionsMaps = computeProjectVersionMaps(workspaceDir, Object.keys(lockFileParser.importers)); for (const importer of Object.keys(lockFileParser.importers)) { const resolvedImporterPath = path.join(workspaceDir, importer); const packagePath = path.join(resolvedImporterPath, 'package.json'); debug(`Processing project ${packagePath} as part of a pnpm workspace`); const pkgJsonFile = (0, utils_2.getFileContents)(root, packagePath); const pkgJson = (0, util_1.parsePkgJson)(pkgJsonFile.content); lockFileParser.workspaceArgs = { isWorkspace: true, projectsVersionMap: projectVersionsMaps, }; try { const depGraph = await (0, build_dep_graph_pnpm_1.buildDepGraphPnpm)(lockFileParser, pkgJson, { includeDevDeps, includePeerDeps, strictOutOfSync, includeOptionalDeps, pruneWithinTopLevelDeps, }, importer); const project = { packageManager: 'pnpm', targetFile: path.relative(root, pkgJsonFile.fileName), depGraph, plugin: { name: 'snyk-nodejs-lockfile-parser', runtime: process.version, }, }; scannedProjects.push(project); } catch (e) { debug(`Error process workspace: ${pkgJsonFile.fileName}. ERROR: ${e}`); } } return scannedProjects; }; exports.parsePnpmWorkspace = parsePnpmWorkspace; //# sourceMappingURL=parse-workspace.js.map /***/ }), /***/ 94865: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getFileContents = exports.getPnpmChildNode = void 0; const path = __webpack_require__(71017); const fs = __webpack_require__(57147); const __1 = __webpack_require__(423); const util_1 = __webpack_require__(46200); const error_catalog_nodejs_public_1 = __webpack_require__(88404); const out_of_sync_error_1 = __webpack_require__(9340); const debugModule = __webpack_require__(15158); const constants_1 = __webpack_require__(89468); const debug = debugModule('snyk-pnpm-workspaces'); const getPnpmChildNode = (name, depInfo, pkgs, strictOutOfSync, includeOptionalDeps, includeDevDeps, lockfileParser) => { const resolvedVersion = lockfileParser.excludeTransPeerDepsVersions(depInfo.version); let childNodeKey = `${name}@${resolvedVersion}`; // For aliases, the version is the dependency path that // shows up in the packages section of lockfiles if (lockfileParser.resolvedPackages[resolvedVersion]) { childNodeKey = lockfileParser.resolvedPackages[resolvedVersion]; } if (lockfileParser.resolvedPackages[childNodeKey]) { childNodeKey = lockfileParser.resolvedPackages[childNodeKey]; } if (!pkgs[childNodeKey]) { if (strictOutOfSync && !/^file:/.test(depInfo.version)) { const errMessage = `Dependency ${childNodeKey} was not found in ` + `${out_of_sync_error_1.LOCK_FILE_NAME[__1.LockfileType.pnpm]}. Your package.json and ` + `${out_of_sync_error_1.LOCK_FILE_NAME[__1.LockfileType.pnpm]} are probably out of sync. Please run ` + `"${out_of_sync_error_1.INSTALL_COMMAND[__1.LockfileType.pnpm]}" and try again.`; debug(errMessage); throw new error_catalog_nodejs_public_1.OpenSourceEcosystems.PnpmOutOfSyncError(errMessage); } else { return { id: childNodeKey, name: name, version: resolvedVersion || constants_1.UNDEFINED_VERSION, dependencies: {}, isDev: depInfo.isDev, missingLockFileEntry: true, }; } } else { const depData = pkgs[childNodeKey]; const dependencies = (0, util_1.getGraphDependencies)(depData.dependencies || {}, depInfo.isDev); const devDependencies = includeDevDeps ? (0, util_1.getGraphDependencies)(depData.devDependencies || {}, true) : {}; const optionalDependencies = includeOptionalDeps ? (0, util_1.getGraphDependencies)(depData.optionalDependencies || {}, depInfo.isDev) : {}; return { id: `${depData.name}@${depData.version}`, name: depData.name, version: depData.version || constants_1.UNDEFINED_VERSION, dependencies: Object.assign(Object.assign(Object.assign({}, dependencies), optionalDependencies), devDependencies), isDev: depInfo.isDev, }; } }; exports.getPnpmChildNode = getPnpmChildNode; function getFileContents(root, fileName) { const fullPath = path.resolve(root, fileName); if (!fs.existsSync(fullPath)) { throw new Error('Manifest ' + fileName + ' not found at location: ' + fileName); } const content = fs.readFileSync(fullPath, 'utf-8'); return { content, fileName, }; } exports.getFileContents = getFileContents; //# sourceMappingURL=utils.js.map /***/ }), /***/ 46200: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getChildNode = exports.parsePkgJson = exports.getGraphDependencies = exports.getTopLevelDeps = exports.addPkgNodeToGraph = void 0; const errors_1 = __webpack_require__(1706); const errors_2 = __webpack_require__(1706); const parsers_1 = __webpack_require__(75873); const addPkgNodeToGraph = (depGraphBuilder, node, options) => { return depGraphBuilder.addPkgNode({ name: node.name, version: node.version }, node.id, { labels: Object.assign(Object.assign(Object.assign({ scope: node.isDev ? 'dev' : 'prod' }, (options.isCyclic && { pruned: 'cyclic' })), (options.isWorkspacePkg && { pruned: 'true' })), (node.missingLockFileEntry && { missingLockFileEntry: 'true' })), }); }; exports.addPkgNodeToGraph = addPkgNodeToGraph; /** * Get top level dependencies from the given package json object which is parsed from a package.json file. * This includes both prod dependencies and dev dependencies supposing includeDevDeps is supported. */ const getTopLevelDeps = (pkgJson, options) => { const prodDeps = (0, exports.getGraphDependencies)(pkgJson.dependencies || {}, false); const devDeps = (0, exports.getGraphDependencies)(pkgJson.devDependencies || {}, true); const optionalDeps = options.includeOptionalDeps ? (0, exports.getGraphDependencies)(pkgJson.optionalDependencies || {}, false) : {}; const peerDeps = options.includePeerDeps ? (0, exports.getGraphDependencies)(pkgJson.peerDependencies || {}, false) : {}; const deps = Object.assign(Object.assign(Object.assign({}, prodDeps), optionalDeps), peerDeps); if (options.includeDevDeps) { // Ensure dev dependency 'isDev' flags are correctly set. // Dev dependencies are applied last to override shared keys with regular dependencies. return Object.assign(Object.assign({}, deps), devDeps); } // For includeDevDeps option set to false, simulate pnpm install --prod // by excluding all devDependencies, // ignoring potential duplicates in other dependency lists. // https://pnpm.io/cli/install#--prod--p return Object.keys(deps) .filter((packageName) => !devDeps.hasOwnProperty(packageName)) .reduce((result, packageName) => { result[packageName] = deps[packageName]; return result; }, {}); }; exports.getTopLevelDeps = getTopLevelDeps; /** * Converts dependencies parsed from the a lock file to a dependencies object required by the graph. * For example, { 'mime-db': '~1.12.0' } will be converted to { 'mime-db': { version: '~1.12.0', isDev: true/false } }. */ const getGraphDependencies = (dependencies, isDev) => { return Object.entries(dependencies).reduce((pnpmDeps, [name, semver]) => { pnpmDeps[name] = { version: semver, isDev: isDev }; return pnpmDeps; }, {}); }; exports.getGraphDependencies = getGraphDependencies; function parsePkgJson(pkgJsonContent) { try { const parsedPkgJson = JSON.parse(pkgJsonContent); if (!parsedPkgJson.name) { parsedPkgJson.name = 'package.json'; } return parsedPkgJson; } catch (e) { throw new errors_1.InvalidUserInputError('package.json parsing failed with error ' + e.message); } } exports.parsePkgJson = parsePkgJson; const getChildNode = (name, depInfo, pkgs, strictOutOfSync, includeOptionalDeps) => { const childNodeKey = `${name}@${depInfo.version}`; let childNode; if (!pkgs[childNodeKey]) { if (strictOutOfSync && !/^file:/.test(depInfo.version)) { throw new errors_2.OutOfSyncError(childNodeKey, parsers_1.LockfileType.yarn); } else { childNode = { id: childNodeKey, name: name, version: depInfo.version, dependencies: {}, isDev: depInfo.isDev, missingLockFileEntry: true, }; } } else { const depData = pkgs[childNodeKey]; const dependencies = (0, exports.getGraphDependencies)(depData.dependencies || {}, depInfo.isDev); const optionalDependencies = includeOptionalDeps ? (0, exports.getGraphDependencies)(depData.optionalDependencies || {}, depInfo.isDev) : {}; childNode = { id: `${name}@${depData.version}`, name: name, version: depData.version, dependencies: Object.assign(Object.assign({}, dependencies), optionalDependencies), isDev: depInfo.isDev, }; } return childNode; }; exports.getChildNode = getChildNode; //# sourceMappingURL=util.js.map /***/ }), /***/ 6431: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildDepGraphYarnLockV1SimpleCyclesPruned = void 0; const dep_graph_1 = __webpack_require__(71479); const util_1 = __webpack_require__(46200); const event_loop_spinner_1 = __webpack_require__(77158); var Color; (function (Color) { Color[Color["GRAY"] = 0] = "GRAY"; Color[Color["BLACK"] = 1] = "BLACK"; })(Color || (Color = {})); const buildDepGraphYarnLockV1SimpleCyclesPruned = async (extractedYarnLockV1Pkgs, pkgJson, options) => { const { includeDevDeps, strictOutOfSync, includeOptionalDeps } = options; const depGraphBuilder = new dep_graph_1.DepGraphBuilder({ name: 'yarn' }, { name: pkgJson.name, version: pkgJson.version }); const colorMap = {}; const topLevelDeps = (0, util_1.getTopLevelDeps)(pkgJson, { includeDevDeps }); const rootNode = { id: 'root-node', name: pkgJson.name, version: pkgJson.version, dependencies: topLevelDeps, isDev: false, }; await dfsVisit(depGraphBuilder, rootNode, colorMap, extractedYarnLockV1Pkgs, strictOutOfSync, includeOptionalDeps); return depGraphBuilder.build(); }; exports.buildDepGraphYarnLockV1SimpleCyclesPruned = buildDepGraphYarnLockV1SimpleCyclesPruned; /** * Use DFS to add all nodes and edges to the depGraphBuilder and prune cyclic nodes. * The colorMap keep track of the state of node during traversal. * - If a node doesn't exist in the map, it means it hasn't been visited. * - If a node is GRAY, it means it has already been discovered but its subtree hasn't been fully traversed. * - If a node is BLACK, it means its subtree has already been fully traversed. * - When first exploring an edge, if it points to a GRAY node, a cycle is found and the GRAY node is pruned. * - A pruned node has id `${originalId}|1` */ const dfsVisit = async (depGraphBuilder, node, colorMap, extractedYarnLockV1Pkgs, strictOutOfSync, includeOptionalDeps) => { colorMap[node.id] = Color.GRAY; for (const [name, depInfo] of Object.entries(node.dependencies || {})) { if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } const childNode = (0, util_1.getChildNode)(name, depInfo, extractedYarnLockV1Pkgs, strictOutOfSync, includeOptionalDeps); if (!colorMap.hasOwnProperty(childNode.id)) { (0, util_1.addPkgNodeToGraph)(depGraphBuilder, childNode, {}); await dfsVisit(depGraphBuilder, childNode, colorMap, extractedYarnLockV1Pkgs, strictOutOfSync, includeOptionalDeps); } else if (colorMap[childNode.id] === Color.GRAY) { // cycle detected childNode.id = `${childNode.id}:pruned`; (0, util_1.addPkgNodeToGraph)(depGraphBuilder, childNode, { isCyclic: true }); } depGraphBuilder.connectDep(node.id, childNode.id); } colorMap[node.id] = Color.BLACK; }; //# sourceMappingURL=build-depgraph-simple-pruned.js.map /***/ }), /***/ 91379: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildDepGraphYarnLockV1Simple = void 0; const dep_graph_1 = __webpack_require__(71479); const util_1 = __webpack_require__(46200); const event_loop_spinner_1 = __webpack_require__(77158); const buildDepGraphYarnLockV1Simple = async (extractedYarnLockV1Pkgs, pkgJson, options) => { const { includeDevDeps, includeOptionalDeps, includePeerDeps, strictOutOfSync, pruneWithinTopLevelDeps, } = options; const depGraphBuilder = new dep_graph_1.DepGraphBuilder({ name: 'yarn' }, { name: pkgJson.name, version: pkgJson.version }); const topLevelDeps = (0, util_1.getTopLevelDeps)(pkgJson, { includeDevDeps, includePeerDeps, includeOptionalDeps, }); const rootNode = { id: 'root-node', name: pkgJson.name, version: pkgJson.version, dependencies: topLevelDeps, isDev: false, }; await dfsVisit(depGraphBuilder, rootNode, extractedYarnLockV1Pkgs, strictOutOfSync, includeOptionalDeps, pruneWithinTopLevelDeps); return depGraphBuilder.build(); }; exports.buildDepGraphYarnLockV1Simple = buildDepGraphYarnLockV1Simple; /** * Use DFS to add all nodes and edges to the depGraphBuilder and prune cyclic nodes. * The visitedMap keep track of which nodes have already been discovered during traversal. * - If a node doesn't exist in the map, it means it hasn't been visited. * - If a node is already visited, simply connect the new node with this node. */ const dfsVisit = async (depGraphBuilder, node, extractedYarnLockV1Pkgs, strictOutOfSync, includeOptionalDeps, pruneWithinTopLevel, visited) => { for (const [name, depInfo] of Object.entries(node.dependencies || {})) { if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } const localVisited = visited || new Set(); const childNode = (0, util_1.getChildNode)(name, depInfo, extractedYarnLockV1Pkgs, strictOutOfSync, includeOptionalDeps); if (localVisited.has(childNode.id)) { if (pruneWithinTopLevel) { const prunedId = `${childNode.id}:pruned`; depGraphBuilder.addPkgNode({ name: childNode.name, version: childNode.version }, prunedId, { labels: Object.assign({ scope: node.isDev ? 'dev' : 'prod', pruned: 'true' }, (node.missingLockFileEntry && { missingLockFileEntry: 'true', })), }); depGraphBuilder.connectDep(node.id, prunedId); } else { depGraphBuilder.connectDep(node.id, childNode.id); } continue; } depGraphBuilder.addPkgNode({ name: childNode.name, version: childNode.version }, childNode.id, { labels: Object.assign({ scope: node.isDev ? 'dev' : 'prod' }, (node.missingLockFileEntry && { missingLockFileEntry: 'true', })), }); depGraphBuilder.connectDep(node.id, childNode.id); localVisited.add(childNode.id); await dfsVisit(depGraphBuilder, childNode, extractedYarnLockV1Pkgs, strictOutOfSync, includeOptionalDeps, pruneWithinTopLevel, localVisited); } }; //# sourceMappingURL=build-depgraph-simple.js.map /***/ }), /***/ 92602: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildDepGraphYarnLockV1WorkspaceCyclesPruned = void 0; const dep_graph_1 = __webpack_require__(71479); const util_1 = __webpack_require__(46200); const util_2 = __webpack_require__(5647); const event_loop_spinner_1 = __webpack_require__(77158); var Color; (function (Color) { Color[Color["GRAY"] = 0] = "GRAY"; Color[Color["BLACK"] = 1] = "BLACK"; })(Color || (Color = {})); // Parse a single workspace package using yarn.lock v1 // workspaces feature const buildDepGraphYarnLockV1WorkspaceCyclesPruned = async (extractedYarnLockV1Pkgs, pkgJson, workspacePkgNameToVersion, options) => { const { includeDevDeps, strictOutOfSync, includeOptionalDeps } = options; const depGraphBuilder = new dep_graph_1.DepGraphBuilder({ name: 'yarn' }, { name: pkgJson.name, version: pkgJson.version }); const colorMap = {}; const topLevelDeps = (0, util_1.getTopLevelDeps)(pkgJson, { includeDevDeps }); const rootNode = { id: 'root-node', name: pkgJson.name, version: pkgJson.version, dependencies: topLevelDeps, isDev: false, }; await dfsVisit(depGraphBuilder, rootNode, colorMap, extractedYarnLockV1Pkgs, workspacePkgNameToVersion, strictOutOfSync, includeOptionalDeps); return depGraphBuilder.build(); }; exports.buildDepGraphYarnLockV1WorkspaceCyclesPruned = buildDepGraphYarnLockV1WorkspaceCyclesPruned; /** * Use DFS to add all nodes and edges to the depGraphBuilder and prune cyclic nodes. * The colorMap keep track of the state of node during traversal. * - If a node doesn't exist in the map, it means it hasn't been visited. * - If a node is GRAY, it means it has already been discovered but its subtree hasn't been fully traversed. * - If a node is BLACK, it means its subtree has already been fully traversed. * - When first exploring an edge, if it points to a GRAY node, a cycle is found and the GRAY node is pruned. * - A pruned node has id `${originalId}|1` * When coming across another workspace package as child node, simply add the node and edge to the graph and mark it as BLACK. */ const dfsVisit = async (depGraphBuilder, node, colorMap, extractedYarnLockV1Pkgs, workspacePkgNameToVersion, strictOutOfSync, includeOptionalDeps) => { colorMap[node.id] = Color.GRAY; for (const [name, depInfo] of Object.entries(node.dependencies || {})) { if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } const isWorkspacePkg = !!workspacePkgNameToVersion[name]; const childNode = (0, util_2.getChildNodeYarnLockV1Workspace)(name, depInfo, workspacePkgNameToVersion, extractedYarnLockV1Pkgs, strictOutOfSync, includeOptionalDeps); if (!colorMap.hasOwnProperty(childNode.id)) { (0, util_1.addPkgNodeToGraph)(depGraphBuilder, childNode, { isCyclic: false, isWorkspacePkg, }); if (!isWorkspacePkg) { await dfsVisit(depGraphBuilder, childNode, colorMap, extractedYarnLockV1Pkgs, workspacePkgNameToVersion, strictOutOfSync, includeOptionalDeps); } else { colorMap[childNode.id] = Color.BLACK; } } else if (colorMap[childNode.id] === Color.GRAY) { // cycle detected childNode.id = `${childNode.id}|1`; (0, util_1.addPkgNodeToGraph)(depGraphBuilder, childNode, { isCyclic: true, isWorkspacePkg, }); } depGraphBuilder.connectDep(node.id, childNode.id); } colorMap[node.id] = Color.BLACK; }; //# sourceMappingURL=build-depgraph-workspace-package-pruned.js.map /***/ }), /***/ 10860: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildDepGraphYarnLockV1Workspace = void 0; const dep_graph_1 = __webpack_require__(71479); const util_1 = __webpack_require__(46200); const util_2 = __webpack_require__(5647); const event_loop_spinner_1 = __webpack_require__(77158); const buildDepGraphYarnLockV1Workspace = async (extractedYarnLockV1Pkgs, pkgJson, workspacePkgNameToVersion, options) => { const { includeDevDeps, strictOutOfSync, includeOptionalDeps } = options; const depGraphBuilder = new dep_graph_1.DepGraphBuilder({ name: 'yarn' }, { name: pkgJson.name, version: pkgJson.version }); const visitedMap = new Set(); const topLevelDeps = (0, util_1.getTopLevelDeps)(pkgJson, { includeDevDeps }); const rootNode = { id: 'root-node', name: pkgJson.name, version: pkgJson.version, dependencies: topLevelDeps, isDev: false, }; await dfsVisit(depGraphBuilder, rootNode, visitedMap, extractedYarnLockV1Pkgs, workspacePkgNameToVersion, strictOutOfSync, includeOptionalDeps); return depGraphBuilder.build(); }; exports.buildDepGraphYarnLockV1Workspace = buildDepGraphYarnLockV1Workspace; /** * Use DFS to add all nodes and edges to the depGraphBuilder and prune cyclic nodes. * The colorMap keep track of the state of node during traversal. * - If a node doesn't exist in the map, it means it hasn't been visited. * - If a node is GRAY, it means it has already been discovered but its subtree hasn't been fully traversed. * - If a node is BLACK, it means its subtree has already been fully traversed. * - When first exploring an edge, if it points to a GRAY node, a cycle is found and the GRAY node is pruned. * - A pruned node has id `${originalId}|1` * When coming across another workspace package as child node, simply add the node and edge to the graph and mark it as BLACK. */ const dfsVisit = async (depGraphBuilder, node, visitedMap, extractedYarnLockV1Pkgs, workspacePkgNameToVersion, strictOutOfSync, includeOptionalDeps) => { visitedMap.add(node.id); for (const [name, depInfo] of Object.entries(node.dependencies || {})) { if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } const isWorkspacePkg = !!workspacePkgNameToVersion[name]; const childNode = (0, util_2.getChildNodeYarnLockV1Workspace)(name, depInfo, workspacePkgNameToVersion, extractedYarnLockV1Pkgs, strictOutOfSync, includeOptionalDeps); if (!visitedMap.has(childNode.id)) { (0, util_1.addPkgNodeToGraph)(depGraphBuilder, childNode, { isCyclic: false, isWorkspacePkg, }); if (!isWorkspacePkg) { await dfsVisit(depGraphBuilder, childNode, visitedMap, extractedYarnLockV1Pkgs, workspacePkgNameToVersion, strictOutOfSync, includeOptionalDeps); } } depGraphBuilder.connectDep(node.id, childNode.id); } }; //# sourceMappingURL=build-depgraph-workspace-package.js.map /***/ }), /***/ 86631: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.extractPkgsFromYarnLockV1 = void 0; const yarnLockfileParser = __webpack_require__(7615); const extractPkgsFromYarnLockV1 = (yarnLockContent) => { return yarnLockfileParser.parse(yarnLockContent).object; }; exports.extractPkgsFromYarnLockV1 = extractPkgsFromYarnLockV1; //# sourceMappingURL=extract-yarnlock-v1-pkgs.js.map /***/ }), /***/ 33248: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildDepGraphYarnLockV1Simple = exports.buildDepGraphYarnLockV1SimpleCyclesPruned = exports.buildDepGraphYarnLockV1Workspace = exports.buildDepGraphYarnLockV1WorkspaceCyclesPruned = exports.extractPkgsFromYarnLockV1 = exports.parseYarnLockV1Project = exports.parseYarnLockV1WorkspaceProject = void 0; const build_depgraph_simple_pruned_1 = __webpack_require__(6431); Object.defineProperty(exports, "buildDepGraphYarnLockV1SimpleCyclesPruned", ({ enumerable: true, get: function () { return build_depgraph_simple_pruned_1.buildDepGraphYarnLockV1SimpleCyclesPruned; } })); const build_depgraph_simple_1 = __webpack_require__(91379); Object.defineProperty(exports, "buildDepGraphYarnLockV1Simple", ({ enumerable: true, get: function () { return build_depgraph_simple_1.buildDepGraphYarnLockV1Simple; } })); const build_depgraph_workspace_package_pruned_1 = __webpack_require__(92602); Object.defineProperty(exports, "buildDepGraphYarnLockV1WorkspaceCyclesPruned", ({ enumerable: true, get: function () { return build_depgraph_workspace_package_pruned_1.buildDepGraphYarnLockV1WorkspaceCyclesPruned; } })); const build_depgraph_workspace_package_1 = __webpack_require__(10860); Object.defineProperty(exports, "buildDepGraphYarnLockV1Workspace", ({ enumerable: true, get: function () { return build_depgraph_workspace_package_1.buildDepGraphYarnLockV1Workspace; } })); const extract_yarnlock_v1_pkgs_1 = __webpack_require__(86631); Object.defineProperty(exports, "extractPkgsFromYarnLockV1", ({ enumerable: true, get: function () { return extract_yarnlock_v1_pkgs_1.extractPkgsFromYarnLockV1; } })); const simple_1 = __webpack_require__(98216); Object.defineProperty(exports, "parseYarnLockV1Project", ({ enumerable: true, get: function () { return simple_1.parseYarnLockV1Project; } })); const workspaces_1 = __webpack_require__(53483); Object.defineProperty(exports, "parseYarnLockV1WorkspaceProject", ({ enumerable: true, get: function () { return workspaces_1.parseYarnLockV1WorkspaceProject; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 98216: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseYarnLockV1Project = void 0; const _1 = __webpack_require__(33248); const util_1 = __webpack_require__(46200); const build_depgraph_simple_pruned_1 = __webpack_require__(6431); const extract_yarnlock_v1_pkgs_1 = __webpack_require__(86631); const parseYarnLockV1Project = async (pkgJsonContent, yarnLockContent, options) => { const { includeDevDeps, includeOptionalDeps, includePeerDeps, pruneLevel, strictOutOfSync, } = options; const pkgs = (0, extract_yarnlock_v1_pkgs_1.extractPkgsFromYarnLockV1)(yarnLockContent); const pkgJson = (0, util_1.parsePkgJson)(pkgJsonContent); const depGraph = pruneLevel === 'cycles' ? await (0, build_depgraph_simple_pruned_1.buildDepGraphYarnLockV1SimpleCyclesPruned)(pkgs, pkgJson, { includeDevDeps, strictOutOfSync, includeOptionalDeps, }) : await (0, _1.buildDepGraphYarnLockV1Simple)(pkgs, pkgJson, { includeDevDeps, includeOptionalDeps, includePeerDeps, strictOutOfSync, pruneWithinTopLevelDeps: pruneLevel === 'withinTopLevelDeps', }); return depGraph; }; exports.parseYarnLockV1Project = parseYarnLockV1Project; //# sourceMappingURL=simple.js.map /***/ }), /***/ 5647: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getChildNodeYarnLockV1Workspace = void 0; const errors_1 = __webpack_require__(1706); const parsers_1 = __webpack_require__(75873); const util_1 = __webpack_require__(46200); const getChildNodeYarnLockV1Workspace = (name, depInfo, workspacePkgNameToVersion, pkgs, strictOutOfSync, includeOptionalDeps) => { let childNode; if (workspacePkgNameToVersion[name]) { const version = workspacePkgNameToVersion[name]; // This is just to mimic old behavior where when StrictOutOfSync is turned on, // any cross referencing between workspace packages will lead to a throw if (strictOutOfSync) { throw new errors_1.OutOfSyncError(`${name}@${version}`, parsers_1.LockfileType.yarn); } childNode = { id: `${name}@${version}`, name: name, version: version, dependencies: {}, isDev: depInfo.isDev, }; } else { childNode = (0, util_1.getChildNode)(name, depInfo, pkgs, strictOutOfSync, includeOptionalDeps); } return childNode; }; exports.getChildNodeYarnLockV1Workspace = getChildNodeYarnLockV1Workspace; //# sourceMappingURL=util.js.map /***/ }), /***/ 53483: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseYarnLockV1WorkspaceProject = void 0; const build_depgraph_workspace_package_pruned_1 = __webpack_require__(92602); const build_depgraph_workspace_package_1 = __webpack_require__(10860); const extract_yarnlock_v1_pkgs_1 = __webpack_require__(86631); const util_1 = __webpack_require__(46200); const c_map_1 = __webpack_require__(83345); const parseYarnLockV1WorkspaceProject = async (yarnLockContent, workspacePackagesPkgJsons, options) => { const { includeDevDeps, includeOptionalDeps, pruneCycles, strictOutOfSync } = options; const extractedYarnLockV1Pkgs = (0, extract_yarnlock_v1_pkgs_1.extractPkgsFromYarnLockV1)(yarnLockContent); // Parse all package.json files and also extract names cross referencing later const workspacePkgNameToVersion = {}; const parsedWorkspacePkgJsons = workspacePackagesPkgJsons.map((wsPkgJsonContent) => { const parsedPkgJson = (0, util_1.parsePkgJson)(wsPkgJsonContent); workspacePkgNameToVersion[parsedPkgJson.name] = parsedPkgJson.version; return parsedPkgJson; }); const depGraphs = (0, c_map_1.cMap)(parsedWorkspacePkgJsons, async (parsedPkgJson) => { return pruneCycles ? await (0, build_depgraph_workspace_package_pruned_1.buildDepGraphYarnLockV1WorkspaceCyclesPruned)(extractedYarnLockV1Pkgs, parsedPkgJson, workspacePkgNameToVersion, { includeDevDeps, strictOutOfSync, includeOptionalDeps, }) : await (0, build_depgraph_workspace_package_1.buildDepGraphYarnLockV1Workspace)(extractedYarnLockV1Pkgs, parsedPkgJson, workspacePkgNameToVersion, { includeDevDeps, strictOutOfSync, includeOptionalDeps, }); }); return depGraphs; }; exports.parseYarnLockV1WorkspaceProject = parseYarnLockV1WorkspaceProject; //# sourceMappingURL=workspaces.js.map /***/ }), /***/ 84570: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildDepGraphYarnLockV2Simple = void 0; const dep_graph_1 = __webpack_require__(71479); const util_1 = __webpack_require__(46200); const utils_1 = __webpack_require__(93093); const event_loop_spinner_1 = __webpack_require__(77158); const buildDepGraphYarnLockV2Simple = async (extractedYarnLockV2Pkgs, pkgJson, options, workspaceArgs) => { const { includeDevDeps, strictOutOfSync, includeOptionalDeps, pruneWithinTopLevelDeps, } = options; const depGraphBuilder = new dep_graph_1.DepGraphBuilder({ name: 'yarn' }, { name: pkgJson.name, version: pkgJson.version }); const topLevelDeps = (0, util_1.getTopLevelDeps)(pkgJson, { includeDevDeps, }); const rootNode = { id: 'root-node', name: pkgJson.name, version: pkgJson.version, dependencies: topLevelDeps, isDev: false, }; await dfsVisit(depGraphBuilder, rootNode, extractedYarnLockV2Pkgs, strictOutOfSync, includeOptionalDeps, // we have rootWorkspaceResolutions if this is workspace pkg with resolutions // at root - therefore it should take precedent (workspaceArgs === null || workspaceArgs === void 0 ? void 0 : workspaceArgs.rootResolutions) || pkgJson.resolutions || {}, pruneWithinTopLevelDeps); return depGraphBuilder.build(); }; exports.buildDepGraphYarnLockV2Simple = buildDepGraphYarnLockV2Simple; /** * Use DFS to add all nodes and edges to the depGraphBuilder and prune cyclic nodes. * The visitedMap keep track of which nodes have already been discovered during traversal. * - If a node doesn't exist in the map, it means it hasn't been visited. * - If a node is already visited, simply connect the new node with this node. */ const dfsVisit = async (depGraphBuilder, node, extractedYarnLockV2Pkgs, strictOutOfSync, includeOptionalDeps, resolutions, pruneWithinTopLevel, visited) => { for (const [name, depInfo] of Object.entries(node.dependencies || {})) { if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } const localVisited = visited || new Set(); const childNode = (0, utils_1.getYarnLockV2ChildNode)(name, depInfo, extractedYarnLockV2Pkgs, strictOutOfSync, includeOptionalDeps, resolutions, node); if (localVisited.has(childNode.id)) { if (pruneWithinTopLevel) { const prunedId = `${childNode.id}:pruned`; depGraphBuilder.addPkgNode({ name: childNode.name, version: childNode.version }, prunedId, { labels: Object.assign({ scope: node.isDev ? 'dev' : 'prod', pruned: 'true' }, (node.missingLockFileEntry && { missingLockFileEntry: 'true', })), }); depGraphBuilder.connectDep(node.id, prunedId); } else { depGraphBuilder.connectDep(node.id, childNode.id); } continue; } depGraphBuilder.addPkgNode({ name: childNode.name, version: childNode.version }, childNode.id, { labels: Object.assign({ scope: node.isDev ? 'dev' : 'prod' }, (node.missingLockFileEntry && { missingLockFileEntry: 'true', })), }); depGraphBuilder.connectDep(node.id, childNode.id); localVisited.add(childNode.id); await dfsVisit(depGraphBuilder, childNode, extractedYarnLockV2Pkgs, strictOutOfSync, includeOptionalDeps, resolutions, pruneWithinTopLevel, localVisited); } }; //# sourceMappingURL=build-depgraph-simple.js.map /***/ }), /***/ 50809: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.extractPkgsFromYarnLockV2 = void 0; const js_yaml_1 = __webpack_require__(59572); const yarnCore = __webpack_require__(74876); const utils_1 = __webpack_require__(93093); const structUtils = yarnCore.structUtils; const parseDescriptor = structUtils.parseDescriptor; const parseRange = structUtils.parseRange; const keyNormalizer = (0, utils_1.yarnLockFileKeyNormalizer)(parseDescriptor, parseRange); const extractPkgsFromYarnLockV2 = (yarnLockContent) => { const rawYarnLock = (0, js_yaml_1.load)(yarnLockContent, { json: true, schema: js_yaml_1.FAILSAFE_SCHEMA, }); delete rawYarnLock.__metadata; const dependencies = {}; Object.entries(rawYarnLock).forEach(([fullDescriptor, versionData]) => { keyNormalizer(fullDescriptor).forEach((descriptor) => { dependencies[descriptor] = versionData; }); }); return dependencies; }; exports.extractPkgsFromYarnLockV2 = extractPkgsFromYarnLockV2; //# sourceMappingURL=extract-yarnlock-v2-pkgs.js.map /***/ }), /***/ 29807: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.extractPkgsFromYarnLockV2 = exports.buildDepGraphYarnLockV2Simple = exports.parseYarnLockV2Project = void 0; const build_depgraph_simple_1 = __webpack_require__(84570); Object.defineProperty(exports, "buildDepGraphYarnLockV2Simple", ({ enumerable: true, get: function () { return build_depgraph_simple_1.buildDepGraphYarnLockV2Simple; } })); const extract_yarnlock_v2_pkgs_1 = __webpack_require__(50809); Object.defineProperty(exports, "extractPkgsFromYarnLockV2", ({ enumerable: true, get: function () { return extract_yarnlock_v2_pkgs_1.extractPkgsFromYarnLockV2; } })); const simple_1 = __webpack_require__(43956); Object.defineProperty(exports, "parseYarnLockV2Project", ({ enumerable: true, get: function () { return simple_1.parseYarnLockV2Project; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 43956: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseYarnLockV2Project = void 0; const extract_yarnlock_v2_pkgs_1 = __webpack_require__(50809); const util_1 = __webpack_require__(46200); const build_depgraph_simple_1 = __webpack_require__(84570); const parseYarnLockV2Project = async (pkgJsonContent, yarnLockContent, options, workspaceArgs) => { const { includeDevDeps, includeOptionalDeps, strictOutOfSync, pruneWithinTopLevelDeps, } = options; const pkgs = (0, extract_yarnlock_v2_pkgs_1.extractPkgsFromYarnLockV2)(yarnLockContent); const pkgJson = (0, util_1.parsePkgJson)(pkgJsonContent); const depgraph = await (0, build_depgraph_simple_1.buildDepGraphYarnLockV2Simple)(pkgs, pkgJson, { includeDevDeps, strictOutOfSync, includeOptionalDeps, pruneWithinTopLevelDeps, }, workspaceArgs); return depgraph; }; exports.parseYarnLockV2Project = parseYarnLockV2Project; //# sourceMappingURL=simple.js.map /***/ }), /***/ 93093: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getYarnLockV2ChildNode = exports.yarnLockFileKeyNormalizer = void 0; const _flatMap = __webpack_require__(78661); const errors_1 = __webpack_require__(1706); const parsers_1 = __webpack_require__(75873); const util_1 = __webpack_require__(46200); const BUILTIN_PLACEHOLDER = 'builtin'; const MULTIPLE_KEYS_REGEXP = / *, */g; const keyNormalizer = (parseDescriptor, parseRange) => (rawDescriptor) => { // See https://yarnpkg.com/features/protocols const descriptors = [rawDescriptor]; const descriptor = parseDescriptor(rawDescriptor); const name = `${descriptor.scope ? '@' + descriptor.scope + '/' : ''}${descriptor.name}`; const range = parseRange(descriptor.range); const protocol = range.protocol; switch (protocol) { case 'npm:': case 'file:': // This is space inneficient but will be kept for now, // Due to how we wish to index using the dependencies map // we want the keys to match name@version but this is handled different // for npm alias and normal install. descriptors.push(`${name}@${range.selector}`); descriptors.push(`${name}@${protocol}${range.selector}`); break; case 'git:': case 'git+ssh:': case 'git+http:': case 'git+https:': case 'github:': if (range.source) { descriptors.push(`${name}@${protocol}${range.source}${range.selector ? '#' + range.selector : ''}`); } else { descriptors.push(`${name}@${protocol}${range.selector}`); } break; case 'patch:': if (range.source && range.selector.indexOf(BUILTIN_PLACEHOLDER) === 0) { descriptors.push(range.source); } else { descriptors.push(`${name}@${protocol}${range.source}${range.selector ? '#' + range.selector : ''}`); } break; case null: case undefined: if (range.source) { descriptors.push(`${name}@${range.source}#${range.selector}`); } else { descriptors.push(`${name}@${range.selector}`); } break; case 'http:': case 'https:': case 'link:': case 'portal:': case 'exec:': case 'workspace:': case 'virtual:': default: // For user defined plugins descriptors.push(`${name}@${protocol}${range.selector}`); break; } return descriptors; }; const yarnLockFileKeyNormalizer = (parseDescriptor, parseRange) => (fullDescriptor) => { const allKeys = fullDescriptor .split(MULTIPLE_KEYS_REGEXP) .map(keyNormalizer(parseDescriptor, parseRange)); return new Set(_flatMap(allKeys)); }; exports.yarnLockFileKeyNormalizer = yarnLockFileKeyNormalizer; const getYarnLockV2ChildNode = (name, depInfo, pkgs, strictOutOfSync, includeOptionalDeps, resolutions, parentNode) => { // First check if a resolution would be used const resolvedVersionFromResolution = (() => { // First check for scoped then simple const scopedKey = `${parentNode.name}/${name}`; if (resolutions[scopedKey]) { return resolutions[scopedKey]; } else if (resolutions[name]) { return resolutions[name]; } return ''; })(); if (resolvedVersionFromResolution) { const childNodeKeyFromResolution = `${name}@${resolvedVersionFromResolution}`; if (!pkgs[childNodeKeyFromResolution]) { if (strictOutOfSync && !/^file:/.test(resolvedVersionFromResolution)) { throw new errors_1.OutOfSyncError(childNodeKeyFromResolution, parsers_1.LockfileType.yarn2); } else { return { id: childNodeKeyFromResolution, name: name, version: resolvedVersionFromResolution, dependencies: {}, isDev: depInfo.isDev, missingLockFileEntry: true, }; } } const { version: versionFromResolution, dependencies, optionalDependencies, } = pkgs[childNodeKeyFromResolution]; const formattedDependencies = (0, util_1.getGraphDependencies)(dependencies || {}, depInfo.isDev); const formattedOptionalDependencies = includeOptionalDeps ? (0, util_1.getGraphDependencies)(optionalDependencies || {}, depInfo.isDev) : {}; return { id: childNodeKeyFromResolution, name: name, version: versionFromResolution, dependencies: Object.assign(Object.assign({}, formattedOptionalDependencies), formattedDependencies), isDev: depInfo.isDev, }; } // No resolutions const childNodeKey = `${name}@${depInfo.version}`; if (!pkgs[childNodeKey]) { if (strictOutOfSync && !/^file:/.test(depInfo.version)) { throw new errors_1.OutOfSyncError(childNodeKey, parsers_1.LockfileType.yarn2); } else { return { id: childNodeKey, name: name, version: depInfo.version, dependencies: {}, isDev: depInfo.isDev, missingLockFileEntry: true, }; } } else { const depData = pkgs[childNodeKey]; const dependencies = (0, util_1.getGraphDependencies)(depData.dependencies || {}, depInfo.isDev); const optionalDependencies = includeOptionalDeps ? (0, util_1.getGraphDependencies)(depData.optionalDependencies || {}, depInfo.isDev) : {}; return { id: `${name}@${depData.version}`, name: name, version: depData.version, dependencies: Object.assign(Object.assign({}, dependencies), optionalDependencies), isDev: depInfo.isDev, }; } }; exports.getYarnLockV2ChildNode = getYarnLockV2ChildNode; //# sourceMappingURL=utils.js.map /***/ }), /***/ 1706: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UnsupportedError = exports.TreeSizeLimitError = exports.OutOfSyncError = exports.UnsupportedRuntimeError = exports.InvalidUserInputError = void 0; var invalid_user_input_error_1 = __webpack_require__(41795); Object.defineProperty(exports, "InvalidUserInputError", ({ enumerable: true, get: function () { return invalid_user_input_error_1.InvalidUserInputError; } })); var unsupported_runtime_error_1 = __webpack_require__(96938); Object.defineProperty(exports, "UnsupportedRuntimeError", ({ enumerable: true, get: function () { return unsupported_runtime_error_1.UnsupportedRuntimeError; } })); var out_of_sync_error_1 = __webpack_require__(9340); Object.defineProperty(exports, "OutOfSyncError", ({ enumerable: true, get: function () { return out_of_sync_error_1.OutOfSyncError; } })); var tree_size_limit_error_1 = __webpack_require__(70923); Object.defineProperty(exports, "TreeSizeLimitError", ({ enumerable: true, get: function () { return tree_size_limit_error_1.TreeSizeLimitError; } })); var unsupported_error_1 = __webpack_require__(99798); Object.defineProperty(exports, "UnsupportedError", ({ enumerable: true, get: function () { return unsupported_error_1.UnsupportedError; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 41795: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.InvalidUserInputError = void 0; class InvalidUserInputError extends Error { constructor(...args) { super(...args); this.code = 422; this.name = 'InvalidUserInputError'; Error.captureStackTrace(this, InvalidUserInputError); } } exports.InvalidUserInputError = InvalidUserInputError; //# sourceMappingURL=invalid-user-input-error.js.map /***/ }), /***/ 9340: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.OutOfSyncError = exports.INSTALL_COMMAND = exports.LOCK_FILE_NAME = void 0; exports.LOCK_FILE_NAME = { npm: 'package-lock.json', npm7: 'package-lock.json', yarn: 'yarn.lock', yarn2: 'yarn.lock', pnpm: 'pnpm-lock.yaml', }; exports.INSTALL_COMMAND = { npm: 'npm install', npm7: 'npm install', yarn: 'yarn install', yarn2: 'yarn install', pnpm: 'pnpm install', }; class OutOfSyncError extends Error { constructor(dependencyName, lockFileType) { super(`Dependency ${dependencyName} was not found in ` + `${exports.LOCK_FILE_NAME[lockFileType]}. Your package.json and ` + `${exports.LOCK_FILE_NAME[lockFileType]} are probably out of sync. Please run ` + `"${exports.INSTALL_COMMAND[lockFileType]}" and try again.`); this.code = 422; this.name = 'OutOfSyncError'; this.dependencyName = dependencyName; this.lockFileType = lockFileType; Error.captureStackTrace(this, OutOfSyncError); } } exports.OutOfSyncError = OutOfSyncError; //# sourceMappingURL=out-of-sync-error.js.map /***/ }), /***/ 70923: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TreeSizeLimitError = void 0; class TreeSizeLimitError extends Error { constructor() { super('Tree size exceeds the allowed limit.'); this.code = 422; this.name = 'TreeSizeLimitError'; Error.captureStackTrace(this, TreeSizeLimitError); } } exports.TreeSizeLimitError = TreeSizeLimitError; //# sourceMappingURL=tree-size-limit-error.js.map /***/ }), /***/ 99798: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UnsupportedError = void 0; class UnsupportedError extends Error { constructor(...args) { super(...args); this.name = 'UnsupportedError'; this.code = 500; Error.captureStackTrace(this, UnsupportedError); } } exports.UnsupportedError = UnsupportedError; //# sourceMappingURL=unsupported-error.js.map /***/ }), /***/ 96938: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UnsupportedRuntimeError = void 0; class UnsupportedRuntimeError extends Error { constructor(...args) { super(...args); this.name = 'UnsupportedRuntimeError'; this.code = 500; Error.captureStackTrace(this, UnsupportedRuntimeError); } } exports.UnsupportedRuntimeError = UnsupportedRuntimeError; //# sourceMappingURL=unsupported-runtime-error.js.map /***/ }), /***/ 423: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getYarnLockfileType = exports.NodeLockfileVersion = exports.getPnpmLockfileVersion = exports.getYarnLockfileVersion = exports.getNpmLockfileVersion = exports.getLockfileVersionFromFile = exports.parsePkgJson = exports.parsePnpmWorkspaceProject = exports.parsePnpmWorkspace = exports.parsePnpmProject = exports.getPnpmLockfileParser = exports.buildDepGraphYarnLockV2Simple = exports.parseYarnLockV2Project = exports.extractPkgsFromYarnLockV2 = exports.buildDepGraphYarnLockV1Workspace = exports.buildDepGraphYarnLockV1WorkspaceCyclesPruned = exports.buildDepGraphYarnLockV1Simple = exports.buildDepGraphYarnLockV1SimpleCyclesPruned = exports.parseYarnLockV1WorkspaceProject = exports.parseYarnLockV1Project = exports.extractPkgsFromYarnLockV1 = exports.parseNpmLockV2Project = exports.OutOfSyncError = exports.InvalidUserInputError = exports.UnsupportedRuntimeError = exports.LockfileType = exports.Scope = exports.getPnpmWorkspaces = exports.getYarnWorkspaces = exports.getYarnWorkspacesFromFiles = exports.buildDepGraphFromCliOutput = exports.buildDepTreeFromFiles = exports.buildDepTree = void 0; const fs = __webpack_require__(57147); const path = __webpack_require__(71017); const parsers_1 = __webpack_require__(75873); Object.defineProperty(exports, "Scope", ({ enumerable: true, get: function () { return parsers_1.Scope; } })); Object.defineProperty(exports, "LockfileType", ({ enumerable: true, get: function () { return parsers_1.LockfileType; } })); Object.defineProperty(exports, "getYarnWorkspaces", ({ enumerable: true, get: function () { return parsers_1.getYarnWorkspaces; } })); Object.defineProperty(exports, "getPnpmWorkspaces", ({ enumerable: true, get: function () { return parsers_1.getPnpmWorkspaces; } })); const package_lock_parser_1 = __webpack_require__(63635); const yarn_lock_parser_1 = __webpack_require__(60949); const yarn2_lock_parser_1 = __webpack_require__(89660); const errors_1 = __webpack_require__(1706); Object.defineProperty(exports, "UnsupportedRuntimeError", ({ enumerable: true, get: function () { return errors_1.UnsupportedRuntimeError; } })); Object.defineProperty(exports, "InvalidUserInputError", ({ enumerable: true, get: function () { return errors_1.InvalidUserInputError; } })); Object.defineProperty(exports, "OutOfSyncError", ({ enumerable: true, get: function () { return errors_1.OutOfSyncError; } })); const cli_parsers_1 = __webpack_require__(27819); Object.defineProperty(exports, "buildDepGraphFromCliOutput", ({ enumerable: true, get: function () { return cli_parsers_1.buildDepGraphFromCliOutput; } })); // Straight to Depgraph Functionality ************* // ************************************************ const dep_graph_builders_1 = __webpack_require__(61311); Object.defineProperty(exports, "parseNpmLockV2Project", ({ enumerable: true, get: function () { return dep_graph_builders_1.parseNpmLockV2Project; } })); Object.defineProperty(exports, "extractPkgsFromYarnLockV1", ({ enumerable: true, get: function () { return dep_graph_builders_1.extractPkgsFromYarnLockV1; } })); Object.defineProperty(exports, "parseYarnLockV1Project", ({ enumerable: true, get: function () { return dep_graph_builders_1.parseYarnLockV1Project; } })); Object.defineProperty(exports, "parseYarnLockV1WorkspaceProject", ({ enumerable: true, get: function () { return dep_graph_builders_1.parseYarnLockV1WorkspaceProject; } })); Object.defineProperty(exports, "buildDepGraphYarnLockV1SimpleCyclesPruned", ({ enumerable: true, get: function () { return dep_graph_builders_1.buildDepGraphYarnLockV1SimpleCyclesPruned; } })); Object.defineProperty(exports, "buildDepGraphYarnLockV1Simple", ({ enumerable: true, get: function () { return dep_graph_builders_1.buildDepGraphYarnLockV1Simple; } })); Object.defineProperty(exports, "buildDepGraphYarnLockV1WorkspaceCyclesPruned", ({ enumerable: true, get: function () { return dep_graph_builders_1.buildDepGraphYarnLockV1WorkspaceCyclesPruned; } })); Object.defineProperty(exports, "buildDepGraphYarnLockV1Workspace", ({ enumerable: true, get: function () { return dep_graph_builders_1.buildDepGraphYarnLockV1Workspace; } })); Object.defineProperty(exports, "extractPkgsFromYarnLockV2", ({ enumerable: true, get: function () { return dep_graph_builders_1.extractPkgsFromYarnLockV2; } })); Object.defineProperty(exports, "parseYarnLockV2Project", ({ enumerable: true, get: function () { return dep_graph_builders_1.parseYarnLockV2Project; } })); Object.defineProperty(exports, "buildDepGraphYarnLockV2Simple", ({ enumerable: true, get: function () { return dep_graph_builders_1.buildDepGraphYarnLockV2Simple; } })); Object.defineProperty(exports, "parsePnpmProject", ({ enumerable: true, get: function () { return dep_graph_builders_1.parsePnpmProject; } })); Object.defineProperty(exports, "parsePnpmWorkspace", ({ enumerable: true, get: function () { return dep_graph_builders_1.parsePnpmWorkspace; } })); Object.defineProperty(exports, "parsePnpmWorkspaceProject", ({ enumerable: true, get: function () { return dep_graph_builders_1.parsePnpmWorkspaceProject; } })); Object.defineProperty(exports, "parsePkgJson", ({ enumerable: true, get: function () { return dep_graph_builders_1.parsePkgJson; } })); const lockfile_parser_1 = __webpack_require__(74093); Object.defineProperty(exports, "getPnpmLockfileParser", ({ enumerable: true, get: function () { return lockfile_parser_1.getPnpmLockfileParser; } })); const utils_1 = __webpack_require__(4426); Object.defineProperty(exports, "getLockfileVersionFromFile", ({ enumerable: true, get: function () { return utils_1.getLockfileVersionFromFile; } })); Object.defineProperty(exports, "getNpmLockfileVersion", ({ enumerable: true, get: function () { return utils_1.getNpmLockfileVersion; } })); Object.defineProperty(exports, "getYarnLockfileVersion", ({ enumerable: true, get: function () { return utils_1.getYarnLockfileVersion; } })); Object.defineProperty(exports, "getPnpmLockfileVersion", ({ enumerable: true, get: function () { return utils_1.getPnpmLockfileVersion; } })); Object.defineProperty(exports, "NodeLockfileVersion", ({ enumerable: true, get: function () { return utils_1.NodeLockfileVersion; } })); // ********************************** async function buildDepTree(manifestFileContents, lockFileContents, includeDev = false, lockfileType, strictOutOfSync = true, defaultManifestFileName = 'package.json') { if (!lockfileType) { lockfileType = parsers_1.LockfileType.npm; } else if (lockfileType === parsers_1.LockfileType.yarn) { lockfileType = getYarnLockfileType(lockFileContents); } let lockfileParser; switch (lockfileType) { case parsers_1.LockfileType.npm: lockfileParser = new package_lock_parser_1.PackageLockParser(); break; case parsers_1.LockfileType.yarn: lockfileParser = new yarn_lock_parser_1.YarnLockParser(); break; case parsers_1.LockfileType.yarn2: lockfileParser = new yarn2_lock_parser_1.Yarn2LockParser(); break; default: throw new errors_1.InvalidUserInputError('Unsupported lockfile type ' + `${lockfileType} provided. Only 'npm' or 'yarn' is currently ` + 'supported.'); } const manifestFile = (0, parsers_1.parseManifestFile)(manifestFileContents); if (!manifestFile.name) { manifestFile.name = path.isAbsolute(defaultManifestFileName) ? path.basename(defaultManifestFileName) : defaultManifestFileName; } const lockFile = lockfileParser.parseLockFile(lockFileContents); return lockfileParser.getDependencyTree(manifestFile, lockFile, includeDev, strictOutOfSync); } exports.buildDepTree = buildDepTree; async function buildDepTreeFromFiles(root, manifestFilePath, lockFilePath, includeDev = false, strictOutOfSync = true) { if (!root || !manifestFilePath || !lockFilePath) { throw new Error('Missing required parameters for buildDepTreeFromFiles()'); } const manifestFileFullPath = path.resolve(root, manifestFilePath); const lockFileFullPath = path.resolve(root, lockFilePath); if (!fs.existsSync(manifestFileFullPath)) { throw new errors_1.InvalidUserInputError('Target file package.json not found at ' + `location: ${manifestFileFullPath}`); } if (!fs.existsSync(lockFileFullPath)) { throw new errors_1.InvalidUserInputError('Lockfile not found at location: ' + lockFileFullPath); } const manifestFileContents = fs.readFileSync(manifestFileFullPath, 'utf-8'); const lockFileContents = fs.readFileSync(lockFileFullPath, 'utf-8'); let lockFileType; if (lockFilePath.endsWith('package-lock.json')) { lockFileType = parsers_1.LockfileType.npm; } else if (lockFilePath.endsWith('yarn.lock')) { lockFileType = getYarnLockfileType(lockFileContents, root, lockFilePath); } else { throw new errors_1.InvalidUserInputError(`Unknown lockfile ${lockFilePath}. ` + 'Please provide either package-lock.json or yarn.lock.'); } return await buildDepTree(manifestFileContents, lockFileContents, includeDev, lockFileType, strictOutOfSync, manifestFilePath); } exports.buildDepTreeFromFiles = buildDepTreeFromFiles; function getYarnWorkspacesFromFiles(root, manifestFilePath) { if (!root || !manifestFilePath) { throw new Error('Missing required parameters for getYarnWorkspacesFromFiles()'); } const manifestFileFullPath = path.resolve(root, manifestFilePath); if (!fs.existsSync(manifestFileFullPath)) { throw new errors_1.InvalidUserInputError('Target file package.json not found at ' + `location: ${manifestFileFullPath}`); } const manifestFileContents = fs.readFileSync(manifestFileFullPath, 'utf-8'); return (0, parsers_1.getYarnWorkspaces)(manifestFileContents); } exports.getYarnWorkspacesFromFiles = getYarnWorkspacesFromFiles; function getYarnLockfileType(lockFileContents, root, lockFilePath) { if (lockFileContents.includes('__metadata') || (root && lockFilePath && fs.existsSync(path.resolve(root, lockFilePath.replace('yarn.lock', '.yarnrc.yml'))))) { return parsers_1.LockfileType.yarn2; } else { return parsers_1.LockfileType.yarn; } } exports.getYarnLockfileType = getYarnLockfileType; //# sourceMappingURL=index.js.map /***/ }), /***/ 75873: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getPnpmWorkspaces = exports.getYarnWorkspaces = exports.createDepTreeDepFromDep = exports.getTopLevelDeps = exports.parseManifestFile = exports.LockfileType = exports.Scope = void 0; const errors_1 = __webpack_require__(1706); const js_yaml_1 = __webpack_require__(59572); var Scope; (function (Scope) { Scope["prod"] = "prod"; Scope["dev"] = "dev"; })(Scope = exports.Scope || (exports.Scope = {})); var LockfileType; (function (LockfileType) { LockfileType["npm"] = "npm"; LockfileType["npm7"] = "npm7"; LockfileType["yarn"] = "yarn"; LockfileType["yarn2"] = "yarn2"; LockfileType["pnpm"] = "pnpm"; })(LockfileType = exports.LockfileType || (exports.LockfileType = {})); function parseManifestFile(manifestFileContents) { try { return JSON.parse(manifestFileContents); } catch (e) { throw new errors_1.InvalidUserInputError('package.json parsing failed with error ' + e.message); } } exports.parseManifestFile = parseManifestFile; function getTopLevelDeps({ targetFile, includeDev, includePeerDeps = false, applyYarn2Resolutions = false, }) { var _a, _b; let dependencies = []; const dependenciesIterator = Object.entries(Object.assign(Object.assign(Object.assign({}, targetFile.dependencies), (includeDev ? targetFile.devDependencies : null)), (targetFile.optionalDependencies || {}))); for (const [name, version] of dependenciesIterator) { dependencies.push({ dev: includeDev && targetFile.devDependencies ? !!targetFile.devDependencies[name] : false, name, version, }); } if (includePeerDeps && targetFile.peerDependencies) { for (const [name, version] of Object.entries(targetFile.peerDependencies)) { if ((_b = (_a = targetFile === null || targetFile === void 0 ? void 0 : targetFile.peerDependenciesMeta) === null || _a === void 0 ? void 0 : _a[name]) === null || _b === void 0 ? void 0 : _b.optional) { continue; } dependencies.push({ name, version, }); } } if (applyYarn2Resolutions && targetFile.resolutions) { const resMap = new Map(Object.entries(targetFile.resolutions).map(([resName, resVersion]) => [ resName.replace(`${targetFile.name}/`, ''), resVersion, ])); dependencies = dependencies.map((dep) => resMap.has(dep.name) ? Object.assign(Object.assign({}, dep), { version: resMap.get(dep.name) }) : dep); } return dependencies; } exports.getTopLevelDeps = getTopLevelDeps; function createDepTreeDepFromDep(dep) { return { labels: { scope: dep.dev ? Scope.dev : Scope.prod, }, name: dep.name, version: dep.version, }; } exports.createDepTreeDepFromDep = createDepTreeDepFromDep; function getYarnWorkspaces(targetFile) { try { const packageJson = parseManifestFile(targetFile); if (!!packageJson.workspaces && !!packageJson.private) { if (Array.isArray(packageJson.workspaces)) { return packageJson.workspaces; } if ('packages' in packageJson.workspaces && Array.isArray(packageJson.workspaces.packages)) { return packageJson.workspaces.packages; } } return false; } catch (e) { throw new errors_1.InvalidUserInputError('package.json parsing failed with ' + `error ${e.message}`); } } exports.getYarnWorkspaces = getYarnWorkspaces; function getPnpmWorkspaces(workspacesYamlFile) { try { const rawPnpmWorkspacesYaml = (0, js_yaml_1.load)(workspacesYamlFile, { json: true, schema: js_yaml_1.FAILSAFE_SCHEMA, }); if (rawPnpmWorkspacesYaml && rawPnpmWorkspacesYaml.packages) { if (Array.isArray(rawPnpmWorkspacesYaml.packages)) { return rawPnpmWorkspacesYaml.packages; } } // By default, all packages of all subdirectories are included. // https://pnpm.io/pnpm-workspace_yaml return ['*']; } catch (e) { throw new errors_1.InvalidUserInputError('package.json parsing failed with ' + `error ${e.message}`); } } exports.getPnpmWorkspaces = getPnpmWorkspaces; //# sourceMappingURL=index.js.map /***/ }), /***/ 53129: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LockParserBase = void 0; const _cloneDeep = __webpack_require__(83465); const _isEmpty = __webpack_require__(99245); const _toPairs = __webpack_require__(28052); const graphlib = __webpack_require__(39322); const uuid_1 = __webpack_require__(96771); const event_loop_spinner_1 = __webpack_require__(77158); const baseDebug = __webpack_require__(15158); const cli_parser_utils_1 = __webpack_require__(80333); const _1 = __webpack_require__(75873); const errors_1 = __webpack_require__(1706); const debug = baseDebug('snyk-nodejs-parser'); class LockParserBase { constructor(type, treeSizeLimit) { this.type = type; this.treeSizeLimit = treeSizeLimit; this.pathDelimiter = '|'; } async getDependencyTree(manifestFile, lockfile, includeDev = false, strictOutOfSync = true) { var _a; if (lockfile.type !== this.type) { throw new errors_1.InvalidUserInputError('Unsupported lockfile provided. Please ' + 'provide `package-lock.json`.'); } const yarnLock = lockfile; const depTree = { dependencies: {}, hasDevDependencies: !_isEmpty(manifestFile.devDependencies), name: manifestFile.name, size: 1, version: manifestFile.version || '', }; const nodeVersion = (_a = manifestFile === null || manifestFile === void 0 ? void 0 : manifestFile.engines) === null || _a === void 0 ? void 0 : _a.node; if (nodeVersion) { if (!depTree.meta) { depTree.meta = {}; } depTree.meta.nodeVersion = nodeVersion; } // asked to process empty deps if (_isEmpty(manifestFile.dependencies) && !includeDev) { return depTree; } // prepare a flat map, where dependency path is a key to dependency object // path is an unique identifier for each dependency and corresponds to the // relative path on disc const depMap = this.getDepMap(yarnLock, manifestFile.resolutions); // all paths are identified, we can create a graph representing what depends on what const depGraph = this.createGraphOfDependencies(depMap, strictOutOfSync); // topological sort will be applied and it requires acyclic graphs let cycleStarts = {}; if (!graphlib.alg.isAcyclic(depGraph)) { const cycles = graphlib.alg.findCycles(depGraph); for (const cycle of cycles) { // Since one of top level dependencies can be a start of cycle and that node // will be duplicated, we need to store a link between original node // and the new one in order to identify those duplicated top level dependencies cycleStarts = Object.assign(Object.assign({}, cycleStarts), this.removeCycle(cycle, depMap, depGraph)); } } // transform depMap to a map of PkgTrees const { depTrees, depTreesSizes } = await this.createDepTrees(depMap, depGraph); // Only include peerDependencies if using npm and npm is at least // version 7 as npm v7 automatically installs peerDependencies // get trees for dependencies from manifest file const topLevelDeps = (0, _1.getTopLevelDeps)({ targetFile: manifestFile, includeDev, includePeerDeps: lockfile.type === _1.LockfileType.npm7, applyYarn2Resolutions: lockfile.type === _1.LockfileType.yarn2, }); // number of dependencies including root one let treeSize = 1; for (const dep of topLevelDeps) { if (treeSize > this.treeSizeLimit) { throw new errors_1.TreeSizeLimitError(); } // if any of top level dependencies is a part of cycle // it now has a different item in the map const key = this.getDepTreeKey(dep); const depName = cycleStarts[key] || key; if (depTrees[depName]) { // if the top level dependency is dev, all children are dev depTree.dependencies[dep.name] = dep.dev ? this.setDevDepRec(_cloneDeep(depTrees[depName])) : depTrees[depName]; treeSize += depTreesSizes[depName]; if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } else if (/^file:/.test(dep.version)) { depTree.dependencies[dep.name] = (0, _1.createDepTreeDepFromDep)(dep); treeSize++; } else { // TODO: also check the package version // for a stricter check if (strictOutOfSync) { throw new errors_1.OutOfSyncError(dep.name, this.type); } depTree.dependencies[dep.name] = (0, _1.createDepTreeDepFromDep)(dep); if (!depTree.dependencies[dep.name].labels) { depTree.dependencies[dep.name].labels = {}; } depTree.dependencies[dep.name].labels.missingLockFileEntry = 'true'; treeSize++; } } depTree.size = treeSize; return depTree; } setDevDepRec(pkgTree) { for (const [name, subTree] of _toPairs(pkgTree.dependencies)) { pkgTree.dependencies[name] = this.setDevDepRec(subTree); } pkgTree.labels = Object.assign(Object.assign({}, pkgTree.labels), { scope: _1.Scope.dev }); return pkgTree; } /* Algorithm for cycle removal: For every node in a cycle: 1. Create a duplicate of entry node (without edges) 2. For every cyclic dependency of entry node, create a duplicate of the dependency and connect it with the duplicated entry node 3.a If edge goes to already-visited dependency, end of cycle is found; update metadata and do not continue traversing 3.b Follow the edge and repeat the process, storing visited dependency-paths. All non-cyclic dependencies of duplicated node need to be updated. 4. All non-cyclic dependencies or dependants of original node need to be updated to be connected with the duplicated one Once completed for all nodes in a cycle, original cyclic nodes can be removed. */ removeCycle(cycle, depMap, depGraph) { /* FUNCTION DEFINITION To keep an order of algorithm steps readable, function is defined on-the-fly Arrow function is used for calling `this` without .bind(this) in the end */ const acyclicDuplicationRec = (node, traversed, currentCycle, nodeCopy) => { // 2. For every cyclic dependency of entry node... const edgesToProcess = depGraph.inEdges(node).filter((e) => currentCycle.includes(e.v)); for (const edge of edgesToProcess) { // ... create a duplicate of the dependency... const child = edge.v; const dependencyCopy = this.cloneNodeWithoutEdges(child, depMap, depGraph); // ...and connect it with the duplicated entry node depGraph.setEdge(dependencyCopy, nodeCopy); // 3.a If edge goes to already-visited dependency, end of cycle is found; if (traversed.includes(child)) { // update metadata and labels and do not continue traversing if (!depMap[dependencyCopy].labels) { depMap[dependencyCopy].labels = {}; } depMap[dependencyCopy].labels.pruned = 'cyclic'; } else { // 3.b Follow the edge and repeat the process, storing visited dependency-paths acyclicDuplicationRec(child, [...traversed, node], currentCycle, dependencyCopy); // All non-cyclic dependencies of duplicated node need to be updated. this.cloneAcyclicNodeEdges(child, dependencyCopy, cycle, depGraph, { inEdges: true, outEdges: false, }); } } }; const cycleStarts = {}; // For every node in a cycle: for (const start of cycle) { // 1. Create a uniqe duplicate of entry node (without edges) const clonedNode = this.cloneNodeWithoutEdges(start, depMap, depGraph); cycleStarts[start] = clonedNode; // CALL of previously defined function acyclicDuplicationRec(start, [], cycle, clonedNode); // 4. All non-cyclic dependencies or dependants of original node need to be // updated to be connected with the duplicated one this.cloneAcyclicNodeEdges(start, clonedNode, cycle, depGraph, { inEdges: true, outEdges: true, }); } // Once completed for all nodes in a cycle, original cyclic nodes can // be removed. for (const start of cycle) { depGraph.removeNode(start); } return cycleStarts; } cloneAcyclicNodeEdges(nodeFrom, nodeTo, cycle, depGraph, { inEdges, outEdges }) { // node has to have edges const edges = depGraph.nodeEdges(nodeFrom); if (outEdges) { const parentEdges = edges.filter((e) => !cycle.includes(e.w)); for (const edge of parentEdges) { const parent = edge.w; depGraph.setEdge(nodeTo, parent); } } if (inEdges) { const childEdges = edges.filter((e) => !cycle.includes(e.v)); for (const edge of childEdges) { const child = edge.v; depGraph.setEdge(child, nodeTo); } } } cloneNodeWithoutEdges(node, depMap, depGraph) { const newNode = node + (0, uuid_1.v4)(); // update depMap with new node depMap[newNode] = _cloneDeep(depMap[node]); // add new node to the graph depGraph.setNode(newNode); return newNode; } createGraphOfDependencies(depMap, strictOutOfSync = true) { const depGraph = new graphlib.Graph(); for (const depKey of Object.keys(depMap)) { depGraph.setNode(depKey); } for (const [depPath, dep] of Object.entries(depMap)) { for (const depName of dep.requires) { const subDepPath = this.findDepsPath(depPath, depName, depMap, strictOutOfSync); // direction is from the dependency to the package requiring it depGraph.setEdge(subDepPath, depPath); } } return depGraph; } // dependency in package-lock.json v1 can be defined either inside `dependencies` // of other dependency or anywhere upward towards root findDepsPath(startPath, depName, depMap, strictOutOfSync = true) { const depPath = startPath.split(this.pathDelimiter); while (depPath.length) { const currentPath = depPath.concat(depName).join(this.pathDelimiter); if (depMap[currentPath]) { return currentPath; } depPath.pop(); } if (!depMap[depName]) { debug(`Dependency ${depName} not found`); if (strictOutOfSync) { throw new errors_1.OutOfSyncError(depName, this.type); } } return depName; } // Algorithm is based on dynamic programming technique and tries to build // "more simple" trees and compose them into bigger ones. async createDepTrees(depMap, depGraph) { var _a; // Graph has to be acyclic if (!graphlib.alg.isAcyclic(depGraph)) { throw new Error('Cycles were not removed from graph.'); } const depTrees = {}; const depTreesSizes = {}; // topological sort guarantees that when we create a pkg-tree for a dep, // all it's sub-trees were already created. This also implies that leaf // packages will be processed first as they have no sub-trees. const depOrder = graphlib.alg.topsort(depGraph); while (depOrder.length) { const depKey = depOrder.shift(); const dep = depMap[depKey]; let treeSize = 1; if (!dep) { debug(`Missing entry for ${depKey}`); continue; } // direction is from the dependency to the package requiring it, so we are // looking for predecessors for (const subDepPath of depGraph.predecessors(depKey)) { let subDep = depTrees[subDepPath]; if (!dep.dependencies) { dep.dependencies = {}; } if (!subDep) { debug(`Missing entry for ${subDepPath}`); const { name, identifier } = (0, cli_parser_utils_1.extractNameAndIdentifier)(subDepPath); subDep = { name: name, version: identifier, dependencies: {}, labels: Object.assign({ missingLockFileEntry: 'true' }, (((_a = dep.labels) === null || _a === void 0 ? void 0 : _a.scope) && { scope: dep.labels.scope })), }; treeSize += 1; } else { treeSize += depTreesSizes[subDepPath]; } dep.dependencies[subDep.name] = subDep; } const depTreeDep = { labels: dep.labels, name: dep.name, version: dep.version, }; if (dep.dependencies) { depTreeDep.dependencies = dep.dependencies; } depTrees[depKey] = depTreeDep; depTreesSizes[depKey] = treeSize; // Since this code doesn't handle any I/O or network, we need to force // event loop to tick while being used in server for request processing if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } return { depTrees, depTreesSizes }; } getDepMap(lockfile, // eslint-disable-line @typescript-eslint/no-unused-vars resolutions) { throw new Error('Not implemented'); } // eslint-disable-next-line @typescript-eslint/no-unused-vars getDepTreeKey(dep) { throw new Error('Not implemented'); } } exports.LockParserBase = LockParserBase; //# sourceMappingURL=lock-parser-base.js.map /***/ }), /***/ 63635: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PackageLockParser = void 0; const index_1 = __webpack_require__(75873); const errors_1 = __webpack_require__(1706); const lock_parser_base_1 = __webpack_require__(53129); const config_1 = __webpack_require__(70104); class PackageLockParser extends lock_parser_base_1.LockParserBase { constructor() { super(index_1.LockfileType.npm, config_1.config.NPM_TREE_SIZE_LIMIT); } parseLockFile(lockFileContents) { try { const packageLock = JSON.parse(lockFileContents); packageLock.type = packageLock.lockfileVersion === 1 ? index_1.LockfileType.npm : index_1.LockfileType.npm7; this.type = packageLock.type; return packageLock; } catch (e) { throw new errors_1.InvalidUserInputError('package-lock.json parsing failed with ' + `error ${e.message}`); } } async getDependencyTree(manifestFile, lockfile, includeDev = false, strictOutOfSync = true) { const dependencyTree = await super.getDependencyTree(manifestFile, lockfile, includeDev, strictOutOfSync); const meta = { lockfileVersion: lockfile.lockfileVersion, packageManager: 'npm', }; const depTreeWithMeta = Object.assign(Object.assign({}, dependencyTree), { meta: Object.assign(Object.assign({}, dependencyTree.meta), meta) }); return depTreeWithMeta; } getDepMap(lockfile) { const packageLock = lockfile; const depMap = {}; const flattenLockfileRec = (lockfileDeps, path) => { for (const [depName, dep] of Object.entries(lockfileDeps)) { const depNode = { labels: { scope: dep.dev ? index_1.Scope.dev : index_1.Scope.prod, }, name: depName, requires: [], version: dep.version, }; if (dep.requires) { depNode.requires = Object.keys(dep.requires); } const depPath = [...path, depName]; const depKey = depPath.join(this.pathDelimiter); depMap[depKey] = depNode; if (dep.dependencies) { flattenLockfileRec(dep.dependencies, depPath); } } }; flattenLockfileRec(packageLock.dependencies || {}, []); return depMap; } getDepTreeKey(dep) { return dep.name; } } exports.PackageLockParser = PackageLockParser; //# sourceMappingURL=package-lock-parser.js.map /***/ }), /***/ 60949: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.YarnLockParser = void 0; const yarnLockfileParser = __webpack_require__(7615); const index_1 = __webpack_require__(75873); const errors_1 = __webpack_require__(1706); const lock_parser_base_1 = __webpack_require__(53129); const config_1 = __webpack_require__(70104); class YarnLockParser extends lock_parser_base_1.LockParserBase { constructor() { super(index_1.LockfileType.yarn, config_1.config.YARN_TREE_SIZE_LIMIT); } parseLockFile(lockFileContents) { try { const yarnLock = yarnLockfileParser.parse(lockFileContents); yarnLock.dependencies = yarnLock.object; yarnLock.type = this.type; return yarnLock; } catch (e) { throw new errors_1.InvalidUserInputError(`yarn.lock parsing failed with an error: ${e.message}`); } } async getDependencyTree(manifestFile, lockfile, includeDev = false, strictOutOfSync = true) { const depTree = await super.getDependencyTree(manifestFile, lockfile, includeDev, strictOutOfSync); const meta = { lockfileVersion: 1, packageManager: 'yarn' }; const depTreeWithMeta = Object.assign(Object.assign({}, depTree), { meta: Object.assign(Object.assign({}, depTree.meta), meta) }); return depTreeWithMeta; } getDepMap(lockfile) { const yarnLockfile = lockfile; const depMap = {}; for (const [depName, dep] of Object.entries(yarnLockfile.object)) { const subDependencies = Object.entries(Object.assign(Object.assign({}, (dep.dependencies || {})), (dep.optionalDependencies || {}))); depMap[depName] = { labels: { scope: index_1.Scope.prod, }, name: getName(depName), requires: subDependencies.map(([key, ver]) => `${key}@${ver}`), version: dep.version, }; } return depMap; } getDepTreeKey(dep) { return `${dep.name}@${dep.version}`; } } exports.YarnLockParser = YarnLockParser; function getName(depName) { return depName.slice(0, depName.indexOf('@', 1)); } //# sourceMappingURL=yarn-lock-parser.js.map /***/ }), /***/ 54760: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.yarnLockFileKeyNormalizer = void 0; const _flatMap = __webpack_require__(78661); const BUILTIN_PLACEHOLDER = 'builtin'; const MULTIPLE_KEYS_REGEXP = / *, */g; const keyNormalizer = (parseDescriptor, parseRange) => (rawDescriptor) => { // See https://yarnpkg.com/features/protocols const descriptors = [rawDescriptor]; const descriptor = parseDescriptor(rawDescriptor); const name = `${descriptor.scope ? '@' + descriptor.scope + '/' : ''}${descriptor.name}`; const range = parseRange(descriptor.range); const protocol = range.protocol; switch (protocol) { case 'npm:': case 'file:': descriptors.push(`${name}@${range.selector}`); descriptors.push(`${name}@${protocol}${range.selector}`); break; case 'git:': case 'git+ssh:': case 'git+http:': case 'git+https:': case 'github:': if (range.source) { descriptors.push(`${name}@${protocol}${range.source}${range.selector ? '#' + range.selector : ''}`); } else { descriptors.push(`${name}@${protocol}${range.selector}`); } break; case 'patch:': if (range.source && range.selector.indexOf(BUILTIN_PLACEHOLDER) === 0) { descriptors.push(range.source); } else { descriptors.push(`${name}@${protocol}${range.source}${range.selector ? '#' + range.selector : ''}`); } break; case null: case undefined: if (range.source) { descriptors.push(`${name}@${range.source}#${range.selector}`); } else { descriptors.push(`${name}@${range.selector}`); } break; case 'http:': case 'https:': case 'link:': case 'portal:': case 'exec:': case 'workspace:': case 'virtual:': default: // For user defined plugins descriptors.push(`${name}@${protocol}${range.selector}`); break; } return descriptors; }; const yarnLockFileKeyNormalizer = (parseDescriptor, parseRange) => (fullDescriptor) => { const allKeys = fullDescriptor .split(MULTIPLE_KEYS_REGEXP) .map(keyNormalizer(parseDescriptor, parseRange)); return new Set(_flatMap(allKeys)); }; exports.yarnLockFileKeyNormalizer = yarnLockFileKeyNormalizer; //# sourceMappingURL=yarn-utils.js.map /***/ }), /***/ 89660: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Yarn2LockParser = void 0; const js_yaml_1 = __webpack_require__(59572); const yarnCore = __webpack_require__(74876); const lock_parser_base_1 = __webpack_require__(53129); const _1 = __webpack_require__(75873); const config_1 = __webpack_require__(70104); const errors_1 = __webpack_require__(1706); const yarn_utils_1 = __webpack_require__(54760); class Yarn2LockParser extends lock_parser_base_1.LockParserBase { constructor() { super(_1.LockfileType.yarn2, config_1.config.YARN_TREE_SIZE_LIMIT); } parseLockFile(lockFileContents) { try { const rawYarnLock = (0, js_yaml_1.load)(lockFileContents, { json: true, schema: js_yaml_1.FAILSAFE_SCHEMA, }); delete rawYarnLock.__metadata; const dependencies = {}; const structUtils = yarnCore.structUtils; const parseDescriptor = structUtils.parseDescriptor; const parseRange = structUtils.parseRange; const keyNormalizer = (0, yarn_utils_1.yarnLockFileKeyNormalizer)(parseDescriptor, parseRange); Object.entries(rawYarnLock).forEach(([fullDescriptor, versionData]) => { keyNormalizer(fullDescriptor).forEach((descriptor) => { dependencies[descriptor] = versionData; }); }); return { dependencies, lockfileType: _1.LockfileType.yarn2, object: dependencies, type: _1.LockfileType.yarn2, }; } catch (e) { throw new errors_1.InvalidUserInputError(`yarn.lock parsing failed with an error: ${e.message}`); } } async getDependencyTree(manifestFile, lockfile, includeDev = false, strictOutOfSync = true) { const depTree = await super.getDependencyTree(manifestFile, lockfile, includeDev, strictOutOfSync); const meta = { lockfileVersion: 2, packageManager: 'yarn' }; const depTreeWithMeta = Object.assign(Object.assign({}, depTree), { meta: Object.assign(Object.assign({}, depTree.meta), meta) }); return depTreeWithMeta; } getDepMap(lockfile, resolutions) { const yarnLockfile = lockfile; const depMap = {}; const dependencies = lockfile.dependencies || {}; for (const [depName, dep] of Object.entries(yarnLockfile.object)) { const subDependencies = Object.entries(Object.assign(Object.assign({}, (dep.dependencies || {})), (dep.optionalDependencies || {}))).map(([key, ver]) => findResolutions(dependencies, depName, key, resolutions) || `${key}@${ver}`); depMap[depName] = { labels: { scope: _1.Scope.prod, }, name: getName(depName), requires: subDependencies, version: dep.version, }; } return depMap; } getDepTreeKey(dep) { return `${dep.name}@${dep.version}`; } } exports.Yarn2LockParser = Yarn2LockParser; function getName(depName) { return depName.slice(0, depName.indexOf('@', 1)); } function findResolutions(dependencies, depName, subDepKey, resolutions) { if (!resolutions) return; const resolutionKeys = Object.keys(resolutions); const index = depName.indexOf('@', 1); const name = depName.slice(0, index); const version = depName.slice(index + 1); const firstMatchingResolution = resolutionKeys.find((res) => { if (!res.endsWith(subDepKey)) { return false; } const leadingPkg = res.split(subDepKey)[0].slice(0, -1); const noSpecifiedParent = !leadingPkg; const specifiedParentMatchesCurrentDep = leadingPkg === name; const specifiedParentWithVersionMatches = leadingPkg.includes(name) && leadingPkg.includes(dependencies[`${name}@${version}`].version); return (noSpecifiedParent || specifiedParentMatchesCurrentDep || specifiedParentWithVersionMatches); }); if (resolutionKeys && firstMatchingResolution) { return `${subDepKey}@${resolutions[firstMatchingResolution]}`; } } //# sourceMappingURL=yarn2-lock-parser.js.map /***/ }), /***/ 4426: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getNpmLockfileVersion = exports.getYarnLockfileVersion = exports.getPnpmLockfileVersion = exports.getLockfileVersionFromFile = exports.NodeLockfileVersion = void 0; const fs_1 = __webpack_require__(57147); const js_yaml_1 = __webpack_require__(59572); const errors_1 = __webpack_require__(1706); const error_catalog_nodejs_public_1 = __webpack_require__(88404); var NodeLockfileVersion; (function (NodeLockfileVersion) { NodeLockfileVersion["NpmLockV1"] = "NPM_LOCK_V1"; NodeLockfileVersion["NpmLockV2"] = "NPM_LOCK_V2"; NodeLockfileVersion["NpmLockV3"] = "NPM_LOCK_V3"; NodeLockfileVersion["YarnLockV1"] = "YARN_LOCK_V1"; NodeLockfileVersion["YarnLockV2"] = "YARN_LOCK_V2"; NodeLockfileVersion["PnpmLockV5"] = "PNPM_LOCK_V5"; NodeLockfileVersion["PnpmLockV6"] = "PNPM_LOCK_V6"; NodeLockfileVersion["PnpmLockV9"] = "PNPM_LOCK_V9"; })(NodeLockfileVersion = exports.NodeLockfileVersion || (exports.NodeLockfileVersion = {})); const getLockfileVersionFromFile = (targetFile) => { const lockFileContents = (0, fs_1.readFileSync)(targetFile, 'utf-8'); if (targetFile.endsWith('package-lock.json')) { return getNpmLockfileVersion(lockFileContents); } else if (targetFile.endsWith('yarn.lock')) { return getYarnLockfileVersion(lockFileContents); } else if (targetFile.endsWith('pnpm-lock.yaml')) { return getPnpmLockfileVersion(lockFileContents); } else { throw new errors_1.InvalidUserInputError(`Unknown lockfile ${targetFile}. ` + 'Please provide either package-lock.json, yarn.lock or pnpm-lock.yaml'); } }; exports.getLockfileVersionFromFile = getLockfileVersionFromFile; function getPnpmLockfileVersion(lockFileContents) { const rawPnpmLock = (0, js_yaml_1.load)(lockFileContents, { json: true, schema: js_yaml_1.FAILSAFE_SCHEMA, }); const { lockfileVersion } = rawPnpmLock; if (lockfileVersion.startsWith('5')) { return NodeLockfileVersion.PnpmLockV5; } else if (lockfileVersion.startsWith('6')) { return NodeLockfileVersion.PnpmLockV6; } else if (lockfileVersion.startsWith('9')) { return NodeLockfileVersion.PnpmLockV9; } else { throw new error_catalog_nodejs_public_1.OpenSourceEcosystems.PnpmUnsupportedLockfileVersionError(`The pnpm-lock.yaml lockfile version ${lockfileVersion} is not supported`); } } exports.getPnpmLockfileVersion = getPnpmLockfileVersion; function getYarnLockfileVersion(lockFileContents) { if (lockFileContents.includes('__metadata')) { return NodeLockfileVersion.YarnLockV2; } else { return NodeLockfileVersion.YarnLockV1; } } exports.getYarnLockfileVersion = getYarnLockfileVersion; function getNpmLockfileVersion(lockFileContents) { try { const lockfileJson = JSON.parse(lockFileContents); const lockfileVersion = lockfileJson.lockfileVersion || null; switch (lockfileVersion) { case null: case 1: return NodeLockfileVersion.NpmLockV1; case 2: return NodeLockfileVersion.NpmLockV2; case 3: return NodeLockfileVersion.NpmLockV3; default: throw new errors_1.InvalidUserInputError(`Unsupported npm lockfile version in package-lock.json. ` + 'Please provide a package-lock.json with lockfileVersion 1, 2 or 3'); } } catch (e) { throw new errors_1.InvalidUserInputError(`Problem parsing package-lock.json - make sure the package-lock.json is a valid JSON file`); } } exports.getNpmLockfileVersion = getNpmLockfileVersion; //# sourceMappingURL=utils.js.map /***/ }), /***/ 59572: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var loader = __webpack_require__(34567); var dumper = __webpack_require__(26772); function renamed(from, to) { return function () { throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' + 'Use yaml.' + to + ' instead, which is now safe by default.'); }; } module.exports.Type = __webpack_require__(55601); module.exports.Schema = __webpack_require__(8237); module.exports.FAILSAFE_SCHEMA = __webpack_require__(98934); module.exports.JSON_SCHEMA = __webpack_require__(92427); module.exports.CORE_SCHEMA = __webpack_require__(41695); module.exports.DEFAULT_SCHEMA = __webpack_require__(4170); module.exports.load = loader.load; module.exports.loadAll = loader.loadAll; module.exports.dump = dumper.dump; module.exports.YAMLException = __webpack_require__(43669); // Re-export all types in case user wants to create custom schema module.exports.types = { binary: __webpack_require__(25167), float: __webpack_require__(75522), map: __webpack_require__(4611), null: __webpack_require__(49252), pairs: __webpack_require__(53490), set: __webpack_require__(79321), timestamp: __webpack_require__(4587), bool: __webpack_require__(72531), int: __webpack_require__(76916), merge: __webpack_require__(441), omap: __webpack_require__(86609), seq: __webpack_require__(31597), str: __webpack_require__(17033) }; // Removed functions from JS-YAML 3.0.x module.exports.safeLoad = renamed('safeLoad', 'load'); module.exports.safeLoadAll = renamed('safeLoadAll', 'loadAll'); module.exports.safeDump = renamed('safeDump', 'dump'); /***/ }), /***/ 46358: /***/ ((module) => { "use strict"; function isNothing(subject) { return (typeof subject === 'undefined') || (subject === null); } function isObject(subject) { return (typeof subject === 'object') && (subject !== null); } function toArray(sequence) { if (Array.isArray(sequence)) return sequence; else if (isNothing(sequence)) return []; return [ sequence ]; } function extend(target, source) { var index, length, key, sourceKeys; if (source) { sourceKeys = Object.keys(source); for (index = 0, length = sourceKeys.length; index < length; index += 1) { key = sourceKeys[index]; target[key] = source[key]; } } return target; } function repeat(string, count) { var result = '', cycle; for (cycle = 0; cycle < count; cycle += 1) { result += string; } return result; } function isNegativeZero(number) { return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); } module.exports.isNothing = isNothing; module.exports.isObject = isObject; module.exports.toArray = toArray; module.exports.repeat = repeat; module.exports.isNegativeZero = isNegativeZero; module.exports.extend = extend; /***/ }), /***/ 26772: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*eslint-disable no-use-before-define*/ var common = __webpack_require__(46358); var YAMLException = __webpack_require__(43669); var DEFAULT_SCHEMA = __webpack_require__(4170); var _toString = Object.prototype.toString; var _hasOwnProperty = Object.prototype.hasOwnProperty; var CHAR_BOM = 0xFEFF; var CHAR_TAB = 0x09; /* Tab */ var CHAR_LINE_FEED = 0x0A; /* LF */ var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ var CHAR_SPACE = 0x20; /* Space */ var CHAR_EXCLAMATION = 0x21; /* ! */ var CHAR_DOUBLE_QUOTE = 0x22; /* " */ var CHAR_SHARP = 0x23; /* # */ var CHAR_PERCENT = 0x25; /* % */ var CHAR_AMPERSAND = 0x26; /* & */ var CHAR_SINGLE_QUOTE = 0x27; /* ' */ var CHAR_ASTERISK = 0x2A; /* * */ var CHAR_COMMA = 0x2C; /* , */ var CHAR_MINUS = 0x2D; /* - */ var CHAR_COLON = 0x3A; /* : */ var CHAR_EQUALS = 0x3D; /* = */ var CHAR_GREATER_THAN = 0x3E; /* > */ var CHAR_QUESTION = 0x3F; /* ? */ var CHAR_COMMERCIAL_AT = 0x40; /* @ */ var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ var CHAR_GRAVE_ACCENT = 0x60; /* ` */ var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ var CHAR_VERTICAL_LINE = 0x7C; /* | */ var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ var ESCAPE_SEQUENCES = {}; ESCAPE_SEQUENCES[0x00] = '\\0'; ESCAPE_SEQUENCES[0x07] = '\\a'; ESCAPE_SEQUENCES[0x08] = '\\b'; ESCAPE_SEQUENCES[0x09] = '\\t'; ESCAPE_SEQUENCES[0x0A] = '\\n'; ESCAPE_SEQUENCES[0x0B] = '\\v'; ESCAPE_SEQUENCES[0x0C] = '\\f'; ESCAPE_SEQUENCES[0x0D] = '\\r'; ESCAPE_SEQUENCES[0x1B] = '\\e'; ESCAPE_SEQUENCES[0x22] = '\\"'; ESCAPE_SEQUENCES[0x5C] = '\\\\'; ESCAPE_SEQUENCES[0x85] = '\\N'; ESCAPE_SEQUENCES[0xA0] = '\\_'; ESCAPE_SEQUENCES[0x2028] = '\\L'; ESCAPE_SEQUENCES[0x2029] = '\\P'; var DEPRECATED_BOOLEANS_SYNTAX = [ 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' ]; var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; function compileStyleMap(schema, map) { var result, keys, index, length, tag, style, type; if (map === null) return {}; result = {}; keys = Object.keys(map); for (index = 0, length = keys.length; index < length; index += 1) { tag = keys[index]; style = String(map[tag]); if (tag.slice(0, 2) === '!!') { tag = 'tag:yaml.org,2002:' + tag.slice(2); } type = schema.compiledTypeMap['fallback'][tag]; if (type && _hasOwnProperty.call(type.styleAliases, style)) { style = type.styleAliases[style]; } result[tag] = style; } return result; } function encodeHex(character) { var string, handle, length; string = character.toString(16).toUpperCase(); if (character <= 0xFF) { handle = 'x'; length = 2; } else if (character <= 0xFFFF) { handle = 'u'; length = 4; } else if (character <= 0xFFFFFFFF) { handle = 'U'; length = 8; } else { throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); } return '\\' + handle + common.repeat('0', length - string.length) + string; } var QUOTING_TYPE_SINGLE = 1, QUOTING_TYPE_DOUBLE = 2; function State(options) { this.schema = options['schema'] || DEFAULT_SCHEMA; this.indent = Math.max(1, (options['indent'] || 2)); this.noArrayIndent = options['noArrayIndent'] || false; this.skipInvalid = options['skipInvalid'] || false; this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); this.styleMap = compileStyleMap(this.schema, options['styles'] || null); this.sortKeys = options['sortKeys'] || false; this.lineWidth = options['lineWidth'] || 80; this.noRefs = options['noRefs'] || false; this.noCompatMode = options['noCompatMode'] || false; this.condenseFlow = options['condenseFlow'] || false; this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; this.forceQuotes = options['forceQuotes'] || false; this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null; this.implicitTypes = this.schema.compiledImplicit; this.explicitTypes = this.schema.compiledExplicit; this.tag = null; this.result = ''; this.duplicates = []; this.usedDuplicates = null; } // Indents every line in a string. Empty lines (\n only) are not indented. function indentString(string, spaces) { var ind = common.repeat(' ', spaces), position = 0, next = -1, result = '', line, length = string.length; while (position < length) { next = string.indexOf('\n', position); if (next === -1) { line = string.slice(position); position = length; } else { line = string.slice(position, next + 1); position = next + 1; } if (line.length && line !== '\n') result += ind; result += line; } return result; } function generateNextLine(state, level) { return '\n' + common.repeat(' ', state.indent * level); } function testImplicitResolving(state, str) { var index, length, type; for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { type = state.implicitTypes[index]; if (type.resolve(str)) { return true; } } return false; } // [33] s-white ::= s-space | s-tab function isWhitespace(c) { return c === CHAR_SPACE || c === CHAR_TAB; } // Returns true if the character can be printed without escaping. // From YAML 1.2: "any allowed characters known to be non-printable // should also be escaped. [However,] This isn’t mandatory" // Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. function isPrintable(c) { return (0x00020 <= c && c <= 0x00007E) || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM) || (0x10000 <= c && c <= 0x10FFFF); } // [34] ns-char ::= nb-char - s-white // [27] nb-char ::= c-printable - b-char - c-byte-order-mark // [26] b-char ::= b-line-feed | b-carriage-return // Including s-white (for some reason, examples doesn't match specs in this aspect) // ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark function isNsCharOrWhitespace(c) { return isPrintable(c) && c !== CHAR_BOM // - b-char && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED; } // [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out // c = flow-in ⇒ ns-plain-safe-in // c = block-key ⇒ ns-plain-safe-out // c = flow-key ⇒ ns-plain-safe-in // [128] ns-plain-safe-out ::= ns-char // [129] ns-plain-safe-in ::= ns-char - c-flow-indicator // [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” ) // | ( /* An ns-char preceding */ “#” ) // | ( “:” /* Followed by an ns-plain-safe(c) */ ) function isPlainSafe(c, prev, inblock) { var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); return ( // ns-plain-safe inblock ? // c = flow-in cIsNsCharOrWhitespace : cIsNsCharOrWhitespace // - c-flow-indicator && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET ) // ns-plain-char && c !== CHAR_SHARP // false on '#' && !(prev === CHAR_COLON && !cIsNsChar) // false on ': ' || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#' || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]' } // Simplified test for values allowed as the first character in plain style. function isPlainSafeFirst(c) { // Uses a subset of ns-char - c-indicator // where ns-char = nb-char - s-white. // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part return isPrintable(c) && c !== CHAR_BOM && !isWhitespace(c) // - s-white // - (c-indicator ::= // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE // | “%” | “@” | “`”) && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT; } // Simplified test for values allowed as the last character in plain style. function isPlainSafeLast(c) { // just not whitespace or colon, it will be checked to be plain character later return !isWhitespace(c) && c !== CHAR_COLON; } // Same as 'string'.codePointAt(pos), but works in older browsers. function codePointAt(string, pos) { var first = string.charCodeAt(pos), second; if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) { second = string.charCodeAt(pos + 1); if (second >= 0xDC00 && second <= 0xDFFF) { // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; } } return first; } // Determines whether block indentation indicator is required. function needIndentIndicator(string) { var leadingSpaceRe = /^\n* /; return leadingSpaceRe.test(string); } var STYLE_PLAIN = 1, STYLE_SINGLE = 2, STYLE_LITERAL = 3, STYLE_FOLDED = 4, STYLE_DOUBLE = 5; // Determines which scalar styles are possible and returns the preferred style. // lineWidth = -1 => no limit. // Pre-conditions: str.length > 0. // Post-conditions: // STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. // STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). // STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) { var i; var char = 0; var prevChar = null; var hasLineBreak = false; var hasFoldableLine = false; // only checked if shouldTrackWidth var shouldTrackWidth = lineWidth !== -1; var previousLineBreak = -1; // count the first line correctly var plain = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1)); if (singleLineOnly || forceQuotes) { // Case: no block styles. // Check for disallowed characters to rule out plain and single. for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { char = codePointAt(string, i); if (!isPrintable(char)) { return STYLE_DOUBLE; } plain = plain && isPlainSafe(char, prevChar, inblock); prevChar = char; } } else { // Case: block styles permitted. for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { char = codePointAt(string, i); if (char === CHAR_LINE_FEED) { hasLineBreak = true; // Check if any line can be folded. if (shouldTrackWidth) { hasFoldableLine = hasFoldableLine || // Foldable line = too long, and not more-indented. (i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== ' '); previousLineBreak = i; } } else if (!isPrintable(char)) { return STYLE_DOUBLE; } plain = plain && isPlainSafe(char, prevChar, inblock); prevChar = char; } // in case the end is missing a \n hasFoldableLine = hasFoldableLine || (shouldTrackWidth && (i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== ' ')); } // Although every style can represent \n without escaping, prefer block styles // for multiline, since they're more readable and they don't add empty lines. // Also prefer folding a super-long line. if (!hasLineBreak && !hasFoldableLine) { // Strings interpretable as another type have to be quoted; // e.g. the string 'true' vs. the boolean true. if (plain && !forceQuotes && !testAmbiguousType(string)) { return STYLE_PLAIN; } return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; } // Edge case: block indentation indicator can only have one digit. if (indentPerLevel > 9 && needIndentIndicator(string)) { return STYLE_DOUBLE; } // At this point we know block styles are valid. // Prefer literal style unless we want to fold. if (!forceQuotes) { return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; } return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; } // Note: line breaking/folding is implemented for only the folded style. // NB. We drop the last trailing newline (if any) of a returned block scalar // since the dumper adds its own newline. This always works: // • No ending newline => unaffected; already using strip "-" chomping. // • Ending newline => removed then restored. // Importantly, this keeps the "+" chomp indicator from gaining an extra line. function writeScalar(state, string, level, iskey, inblock) { state.dump = (function () { if (string.length === 0) { return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''"; } if (!state.noCompatMode) { if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) { return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'"); } } var indent = state.indent * Math.max(1, level); // no 0-indent scalars // As indentation gets deeper, let the width decrease monotonically // to the lower bound min(state.lineWidth, 40). // Note that this implies // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. // state.lineWidth > 40 + state.indent: width decreases until the lower bound. // This behaves better than a constant minimum width which disallows narrower options, // or an indent threshold which causes the width to suddenly increase. var lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); // Without knowing if keys are implicit/explicit, assume implicit for safety. var singleLineOnly = iskey // No block styles in flow mode. || (state.flowLevel > -1 && level >= state.flowLevel); function testAmbiguity(string) { return testImplicitResolving(state, string); } switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { case STYLE_PLAIN: return string; case STYLE_SINGLE: return "'" + string.replace(/'/g, "''") + "'"; case STYLE_LITERAL: return '|' + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent)); case STYLE_FOLDED: return '>' + blockHeader(string, state.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); case STYLE_DOUBLE: return '"' + escapeString(string, lineWidth) + '"'; default: throw new YAMLException('impossible error: invalid scalar style'); } }()); } // Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. function blockHeader(string, indentPerLevel) { var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; // note the special case: the string '\n' counts as a "trailing" empty line. var clip = string[string.length - 1] === '\n'; var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); var chomp = keep ? '+' : (clip ? '' : '-'); return indentIndicator + chomp + '\n'; } // (See the note for writeScalar.) function dropEndingNewline(string) { return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; } // Note: a long line without a suitable break point will exceed the width limit. // Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. function foldString(string, width) { // In folded style, $k$ consecutive newlines output as $k+1$ newlines— // unless they're before or after a more-indented line, or at the very // beginning or end, in which case $k$ maps to $k$. // Therefore, parse each chunk as newline(s) followed by a content line. var lineRe = /(\n+)([^\n]*)/g; // first line (possibly an empty line) var result = (function () { var nextLF = string.indexOf('\n'); nextLF = nextLF !== -1 ? nextLF : string.length; lineRe.lastIndex = nextLF; return foldLine(string.slice(0, nextLF), width); }()); // If we haven't reached the first content line yet, don't add an extra \n. var prevMoreIndented = string[0] === '\n' || string[0] === ' '; var moreIndented; // rest of the lines var match; while ((match = lineRe.exec(string))) { var prefix = match[1], line = match[2]; moreIndented = (line[0] === ' '); result += prefix + (!prevMoreIndented && !moreIndented && line !== '' ? '\n' : '') + foldLine(line, width); prevMoreIndented = moreIndented; } return result; } // Greedy line breaking. // Picks the longest line under the limit each time, // otherwise settles for the shortest line over the limit. // NB. More-indented lines *cannot* be folded, as that would add an extra \n. function foldLine(line, width) { if (line === '' || line[0] === ' ') return line; // Since a more-indented line adds a \n, breaks can't be followed by a space. var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. var match; // start is an inclusive index. end, curr, and next are exclusive. var start = 0, end, curr = 0, next = 0; var result = ''; // Invariants: 0 <= start <= length-1. // 0 <= curr <= next <= max(0, length-2). curr - start <= width. // Inside the loop: // A match implies length >= 2, so curr and next are <= length-2. while ((match = breakRe.exec(line))) { next = match.index; // maintain invariant: curr - start <= width if (next - start > width) { end = (curr > start) ? curr : next; // derive end <= length-2 result += '\n' + line.slice(start, end); // skip the space that was output as \n start = end + 1; // derive start <= length-1 } curr = next; } // By the invariants, start <= length-1, so there is something left over. // It is either the whole string or a part starting from non-whitespace. result += '\n'; // Insert a break if the remainder is too long and there is a break available. if (line.length - start > width && curr > start) { result += line.slice(start, curr) + '\n' + line.slice(curr + 1); } else { result += line.slice(start); } return result.slice(1); // drop extra \n joiner } // Escapes a double-quoted string. function escapeString(string) { var result = ''; var char = 0; var escapeSeq; for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { char = codePointAt(string, i); escapeSeq = ESCAPE_SEQUENCES[char]; if (!escapeSeq && isPrintable(char)) { result += string[i]; if (char >= 0x10000) result += string[i + 1]; } else { result += escapeSeq || encodeHex(char); } } return result; } function writeFlowSequence(state, level, object) { var _result = '', _tag = state.tag, index, length, value; for (index = 0, length = object.length; index < length; index += 1) { value = object[index]; if (state.replacer) { value = state.replacer.call(object, String(index), value); } // Write only valid elements, put null instead of invalid elements. if (writeNode(state, level, value, false, false) || (typeof value === 'undefined' && writeNode(state, level, null, false, false))) { if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : ''); _result += state.dump; } } state.tag = _tag; state.dump = '[' + _result + ']'; } function writeBlockSequence(state, level, object, compact) { var _result = '', _tag = state.tag, index, length, value; for (index = 0, length = object.length; index < length; index += 1) { value = object[index]; if (state.replacer) { value = state.replacer.call(object, String(index), value); } // Write only valid elements, put null instead of invalid elements. if (writeNode(state, level + 1, value, true, true, false, true) || (typeof value === 'undefined' && writeNode(state, level + 1, null, true, true, false, true))) { if (!compact || _result !== '') { _result += generateNextLine(state, level); } if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { _result += '-'; } else { _result += '- '; } _result += state.dump; } } state.tag = _tag; state.dump = _result || '[]'; // Empty sequence if no valid values. } function writeFlowMapping(state, level, object) { var _result = '', _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, pairBuffer; for (index = 0, length = objectKeyList.length; index < length; index += 1) { pairBuffer = ''; if (_result !== '') pairBuffer += ', '; if (state.condenseFlow) pairBuffer += '"'; objectKey = objectKeyList[index]; objectValue = object[objectKey]; if (state.replacer) { objectValue = state.replacer.call(object, objectKey, objectValue); } if (!writeNode(state, level, objectKey, false, false)) { continue; // Skip this pair because of invalid key; } if (state.dump.length > 1024) pairBuffer += '? '; pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); if (!writeNode(state, level, objectValue, false, false)) { continue; // Skip this pair because of invalid value. } pairBuffer += state.dump; // Both key and value are valid. _result += pairBuffer; } state.tag = _tag; state.dump = '{' + _result + '}'; } function writeBlockMapping(state, level, object, compact) { var _result = '', _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, explicitPair, pairBuffer; // Allow sorting keys so that the output file is deterministic if (state.sortKeys === true) { // Default sorting objectKeyList.sort(); } else if (typeof state.sortKeys === 'function') { // Custom sort function objectKeyList.sort(state.sortKeys); } else if (state.sortKeys) { // Something is wrong throw new YAMLException('sortKeys must be a boolean or a function'); } for (index = 0, length = objectKeyList.length; index < length; index += 1) { pairBuffer = ''; if (!compact || _result !== '') { pairBuffer += generateNextLine(state, level); } objectKey = objectKeyList[index]; objectValue = object[objectKey]; if (state.replacer) { objectValue = state.replacer.call(object, objectKey, objectValue); } if (!writeNode(state, level + 1, objectKey, true, true, true)) { continue; // Skip this pair because of invalid key. } explicitPair = (state.tag !== null && state.tag !== '?') || (state.dump && state.dump.length > 1024); if (explicitPair) { if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { pairBuffer += '?'; } else { pairBuffer += '? '; } } pairBuffer += state.dump; if (explicitPair) { pairBuffer += generateNextLine(state, level); } if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { continue; // Skip this pair because of invalid value. } if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { pairBuffer += ':'; } else { pairBuffer += ': '; } pairBuffer += state.dump; // Both key and value are valid. _result += pairBuffer; } state.tag = _tag; state.dump = _result || '{}'; // Empty mapping if no valid pairs. } function detectType(state, object, explicit) { var _result, typeList, index, length, type, style; typeList = explicit ? state.explicitTypes : state.implicitTypes; for (index = 0, length = typeList.length; index < length; index += 1) { type = typeList[index]; if ((type.instanceOf || type.predicate) && (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && (!type.predicate || type.predicate(object))) { if (explicit) { if (type.multi && type.representName) { state.tag = type.representName(object); } else { state.tag = type.tag; } } else { state.tag = '?'; } if (type.represent) { style = state.styleMap[type.tag] || type.defaultStyle; if (_toString.call(type.represent) === '[object Function]') { _result = type.represent(object, style); } else if (_hasOwnProperty.call(type.represent, style)) { _result = type.represent[style](object, style); } else { throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); } state.dump = _result; } return true; } } return false; } // Serializes `object` and writes it to global `result`. // Returns true on success, or false on invalid object. // function writeNode(state, level, object, block, compact, iskey, isblockseq) { state.tag = null; state.dump = object; if (!detectType(state, object, false)) { detectType(state, object, true); } var type = _toString.call(state.dump); var inblock = block; var tagStr; if (block) { block = (state.flowLevel < 0 || state.flowLevel > level); } var objectOrArray = type === '[object Object]' || type === '[object Array]', duplicateIndex, duplicate; if (objectOrArray) { duplicateIndex = state.duplicates.indexOf(object); duplicate = duplicateIndex !== -1; } if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { compact = false; } if (duplicate && state.usedDuplicates[duplicateIndex]) { state.dump = '*ref_' + duplicateIndex; } else { if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { state.usedDuplicates[duplicateIndex] = true; } if (type === '[object Object]') { if (block && (Object.keys(state.dump).length !== 0)) { writeBlockMapping(state, level, state.dump, compact); if (duplicate) { state.dump = '&ref_' + duplicateIndex + state.dump; } } else { writeFlowMapping(state, level, state.dump); if (duplicate) { state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; } } } else if (type === '[object Array]') { if (block && (state.dump.length !== 0)) { if (state.noArrayIndent && !isblockseq && level > 0) { writeBlockSequence(state, level - 1, state.dump, compact); } else { writeBlockSequence(state, level, state.dump, compact); } if (duplicate) { state.dump = '&ref_' + duplicateIndex + state.dump; } } else { writeFlowSequence(state, level, state.dump); if (duplicate) { state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; } } } else if (type === '[object String]') { if (state.tag !== '?') { writeScalar(state, state.dump, level, iskey, inblock); } } else if (type === '[object Undefined]') { return false; } else { if (state.skipInvalid) return false; throw new YAMLException('unacceptable kind of an object to dump ' + type); } if (state.tag !== null && state.tag !== '?') { // Need to encode all characters except those allowed by the spec: // // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */ // [36] ns-hex-digit ::= ns-dec-digit // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */ // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */ // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-” // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#” // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,” // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]” // // Also need to encode '!' because it has special meaning (end of tag prefix). // tagStr = encodeURI( state.tag[0] === '!' ? state.tag.slice(1) : state.tag ).replace(/!/g, '%21'); if (state.tag[0] === '!') { tagStr = '!' + tagStr; } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') { tagStr = '!!' + tagStr.slice(18); } else { tagStr = '!<' + tagStr + '>'; } state.dump = tagStr + ' ' + state.dump; } } return true; } function getDuplicateReferences(object, state) { var objects = [], duplicatesIndexes = [], index, length; inspectNode(object, objects, duplicatesIndexes); for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { state.duplicates.push(objects[duplicatesIndexes[index]]); } state.usedDuplicates = new Array(length); } function inspectNode(object, objects, duplicatesIndexes) { var objectKeyList, index, length; if (object !== null && typeof object === 'object') { index = objects.indexOf(object); if (index !== -1) { if (duplicatesIndexes.indexOf(index) === -1) { duplicatesIndexes.push(index); } } else { objects.push(object); if (Array.isArray(object)) { for (index = 0, length = object.length; index < length; index += 1) { inspectNode(object[index], objects, duplicatesIndexes); } } else { objectKeyList = Object.keys(object); for (index = 0, length = objectKeyList.length; index < length; index += 1) { inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); } } } } } function dump(input, options) { options = options || {}; var state = new State(options); if (!state.noRefs) getDuplicateReferences(input, state); var value = input; if (state.replacer) { value = state.replacer.call({ '': value }, '', value); } if (writeNode(state, 0, value, true, true)) return state.dump + '\n'; return ''; } module.exports.dump = dump; /***/ }), /***/ 43669: /***/ ((module) => { "use strict"; // YAML error class. http://stackoverflow.com/questions/8458984 // function formatError(exception, compact) { var where = '', message = exception.reason || '(unknown reason)'; if (!exception.mark) return message; if (exception.mark.name) { where += 'in "' + exception.mark.name + '" '; } where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'; if (!compact && exception.mark.snippet) { where += '\n\n' + exception.mark.snippet; } return message + ' ' + where; } function YAMLException(reason, mark) { // Super constructor Error.call(this); this.name = 'YAMLException'; this.reason = reason; this.mark = mark; this.message = formatError(this, false); // Include stack trace in error object if (Error.captureStackTrace) { // Chrome and NodeJS Error.captureStackTrace(this, this.constructor); } else { // FF, IE 10+ and Safari 6+. Fallback for others this.stack = (new Error()).stack || ''; } } // Inherit from Error YAMLException.prototype = Object.create(Error.prototype); YAMLException.prototype.constructor = YAMLException; YAMLException.prototype.toString = function toString(compact) { return this.name + ': ' + formatError(this, compact); }; module.exports = YAMLException; /***/ }), /***/ 34567: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*eslint-disable max-len,no-use-before-define*/ var common = __webpack_require__(46358); var YAMLException = __webpack_require__(43669); var makeSnippet = __webpack_require__(13237); var DEFAULT_SCHEMA = __webpack_require__(4170); var _hasOwnProperty = Object.prototype.hasOwnProperty; var CONTEXT_FLOW_IN = 1; var CONTEXT_FLOW_OUT = 2; var CONTEXT_BLOCK_IN = 3; var CONTEXT_BLOCK_OUT = 4; var CHOMPING_CLIP = 1; var CHOMPING_STRIP = 2; var CHOMPING_KEEP = 3; var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; function _class(obj) { return Object.prototype.toString.call(obj); } function is_EOL(c) { return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); } function is_WHITE_SPACE(c) { return (c === 0x09/* Tab */) || (c === 0x20/* Space */); } function is_WS_OR_EOL(c) { return (c === 0x09/* Tab */) || (c === 0x20/* Space */) || (c === 0x0A/* LF */) || (c === 0x0D/* CR */); } function is_FLOW_INDICATOR(c) { return c === 0x2C/* , */ || c === 0x5B/* [ */ || c === 0x5D/* ] */ || c === 0x7B/* { */ || c === 0x7D/* } */; } function fromHexCode(c) { var lc; if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { return c - 0x30; } /*eslint-disable no-bitwise*/ lc = c | 0x20; if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { return lc - 0x61 + 10; } return -1; } function escapedHexLen(c) { if (c === 0x78/* x */) { return 2; } if (c === 0x75/* u */) { return 4; } if (c === 0x55/* U */) { return 8; } return 0; } function fromDecimalCode(c) { if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { return c - 0x30; } return -1; } function simpleEscapeSequence(c) { /* eslint-disable indent */ return (c === 0x30/* 0 */) ? '\x00' : (c === 0x61/* a */) ? '\x07' : (c === 0x62/* b */) ? '\x08' : (c === 0x74/* t */) ? '\x09' : (c === 0x09/* Tab */) ? '\x09' : (c === 0x6E/* n */) ? '\x0A' : (c === 0x76/* v */) ? '\x0B' : (c === 0x66/* f */) ? '\x0C' : (c === 0x72/* r */) ? '\x0D' : (c === 0x65/* e */) ? '\x1B' : (c === 0x20/* Space */) ? ' ' : (c === 0x22/* " */) ? '\x22' : (c === 0x2F/* / */) ? '/' : (c === 0x5C/* \ */) ? '\x5C' : (c === 0x4E/* N */) ? '\x85' : (c === 0x5F/* _ */) ? '\xA0' : (c === 0x4C/* L */) ? '\u2028' : (c === 0x50/* P */) ? '\u2029' : ''; } function charFromCodepoint(c) { if (c <= 0xFFFF) { return String.fromCharCode(c); } // Encode UTF-16 surrogate pair // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF return String.fromCharCode( ((c - 0x010000) >> 10) + 0xD800, ((c - 0x010000) & 0x03FF) + 0xDC00 ); } var simpleEscapeCheck = new Array(256); // integer, for fast access var simpleEscapeMap = new Array(256); for (var i = 0; i < 256; i++) { simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; simpleEscapeMap[i] = simpleEscapeSequence(i); } function State(input, options) { this.input = input; this.filename = options['filename'] || null; this.schema = options['schema'] || DEFAULT_SCHEMA; this.onWarning = options['onWarning'] || null; // (Hidden) Remove? makes the loader to expect YAML 1.1 documents // if such documents have no explicit %YAML directive this.legacy = options['legacy'] || false; this.json = options['json'] || false; this.listener = options['listener'] || null; this.implicitTypes = this.schema.compiledImplicit; this.typeMap = this.schema.compiledTypeMap; this.length = input.length; this.position = 0; this.line = 0; this.lineStart = 0; this.lineIndent = 0; // position of first leading tab in the current line, // used to make sure there are no tabs in the indentation this.firstTabInLine = -1; this.documents = []; /* this.version; this.checkLineBreaks; this.tagMap; this.anchorMap; this.tag; this.anchor; this.kind; this.result;*/ } function generateError(state, message) { var mark = { name: state.filename, buffer: state.input.slice(0, -1), // omit trailing \0 position: state.position, line: state.line, column: state.position - state.lineStart }; mark.snippet = makeSnippet(mark); return new YAMLException(message, mark); } function throwError(state, message) { throw generateError(state, message); } function throwWarning(state, message) { if (state.onWarning) { state.onWarning.call(null, generateError(state, message)); } } var directiveHandlers = { YAML: function handleYamlDirective(state, name, args) { var match, major, minor; if (state.version !== null) { throwError(state, 'duplication of %YAML directive'); } if (args.length !== 1) { throwError(state, 'YAML directive accepts exactly one argument'); } match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); if (match === null) { throwError(state, 'ill-formed argument of the YAML directive'); } major = parseInt(match[1], 10); minor = parseInt(match[2], 10); if (major !== 1) { throwError(state, 'unacceptable YAML version of the document'); } state.version = args[0]; state.checkLineBreaks = (minor < 2); if (minor !== 1 && minor !== 2) { throwWarning(state, 'unsupported YAML version of the document'); } }, TAG: function handleTagDirective(state, name, args) { var handle, prefix; if (args.length !== 2) { throwError(state, 'TAG directive accepts exactly two arguments'); } handle = args[0]; prefix = args[1]; if (!PATTERN_TAG_HANDLE.test(handle)) { throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); } if (_hasOwnProperty.call(state.tagMap, handle)) { throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); } if (!PATTERN_TAG_URI.test(prefix)) { throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); } try { prefix = decodeURIComponent(prefix); } catch (err) { throwError(state, 'tag prefix is malformed: ' + prefix); } state.tagMap[handle] = prefix; } }; function captureSegment(state, start, end, checkJson) { var _position, _length, _character, _result; if (start < end) { _result = state.input.slice(start, end); if (checkJson) { for (_position = 0, _length = _result.length; _position < _length; _position += 1) { _character = _result.charCodeAt(_position); if (!(_character === 0x09 || (0x20 <= _character && _character <= 0x10FFFF))) { throwError(state, 'expected valid JSON character'); } } } else if (PATTERN_NON_PRINTABLE.test(_result)) { throwError(state, 'the stream contains non-printable characters'); } state.result += _result; } } function mergeMappings(state, destination, source, overridableKeys) { var sourceKeys, key, index, quantity; if (!common.isObject(source)) { throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); } sourceKeys = Object.keys(source); for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { key = sourceKeys[index]; if (!_hasOwnProperty.call(destination, key)) { destination[key] = source[key]; overridableKeys[key] = true; } } } function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) { var index, quantity; // The output is a plain object here, so keys can only be strings. // We need to convert keyNode to a string, but doing so can hang the process // (deeply nested arrays that explode exponentially using aliases). if (Array.isArray(keyNode)) { keyNode = Array.prototype.slice.call(keyNode); for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { if (Array.isArray(keyNode[index])) { throwError(state, 'nested arrays are not supported inside keys'); } if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { keyNode[index] = '[object Object]'; } } } // Avoid code execution in load() via toString property // (still use its own toString for arrays, timestamps, // and whatever user schema extensions happen to have @@toStringTag) if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { keyNode = '[object Object]'; } keyNode = String(keyNode); if (_result === null) { _result = {}; } if (keyTag === 'tag:yaml.org,2002:merge') { if (Array.isArray(valueNode)) { for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { mergeMappings(state, _result, valueNode[index], overridableKeys); } } else { mergeMappings(state, _result, valueNode, overridableKeys); } } else { if (!state.json && !_hasOwnProperty.call(overridableKeys, keyNode) && _hasOwnProperty.call(_result, keyNode)) { state.line = startLine || state.line; state.lineStart = startLineStart || state.lineStart; state.position = startPos || state.position; throwError(state, 'duplicated mapping key'); } // used for this specific key only because Object.defineProperty is slow if (keyNode === '__proto__') { Object.defineProperty(_result, keyNode, { configurable: true, enumerable: true, writable: true, value: valueNode }); } else { _result[keyNode] = valueNode; } delete overridableKeys[keyNode]; } return _result; } function readLineBreak(state) { var ch; ch = state.input.charCodeAt(state.position); if (ch === 0x0A/* LF */) { state.position++; } else if (ch === 0x0D/* CR */) { state.position++; if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { state.position++; } } else { throwError(state, 'a line break is expected'); } state.line += 1; state.lineStart = state.position; state.firstTabInLine = -1; } function skipSeparationSpace(state, allowComments, checkIndent) { var lineBreaks = 0, ch = state.input.charCodeAt(state.position); while (ch !== 0) { while (is_WHITE_SPACE(ch)) { if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) { state.firstTabInLine = state.position; } ch = state.input.charCodeAt(++state.position); } if (allowComments && ch === 0x23/* # */) { do { ch = state.input.charCodeAt(++state.position); } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); } if (is_EOL(ch)) { readLineBreak(state); ch = state.input.charCodeAt(state.position); lineBreaks++; state.lineIndent = 0; while (ch === 0x20/* Space */) { state.lineIndent++; ch = state.input.charCodeAt(++state.position); } } else { break; } } if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { throwWarning(state, 'deficient indentation'); } return lineBreaks; } function testDocumentSeparator(state) { var _position = state.position, ch; ch = state.input.charCodeAt(_position); // Condition state.position === state.lineStart is tested // in parent on each call, for efficiency. No needs to test here again. if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) { _position += 3; ch = state.input.charCodeAt(_position); if (ch === 0 || is_WS_OR_EOL(ch)) { return true; } } return false; } function writeFoldedLines(state, count) { if (count === 1) { state.result += ' '; } else if (count > 1) { state.result += common.repeat('\n', count - 1); } } function readPlainScalar(state, nodeIndent, withinFlowCollection) { var preceding, following, captureStart, captureEnd, hasPendingContent, _line, _lineStart, _lineIndent, _kind = state.kind, _result = state.result, ch; ch = state.input.charCodeAt(state.position); if (is_WS_OR_EOL(ch) || is_FLOW_INDICATOR(ch) || ch === 0x23/* # */ || ch === 0x26/* & */ || ch === 0x2A/* * */ || ch === 0x21/* ! */ || ch === 0x7C/* | */ || ch === 0x3E/* > */ || ch === 0x27/* ' */ || ch === 0x22/* " */ || ch === 0x25/* % */ || ch === 0x40/* @ */ || ch === 0x60/* ` */) { return false; } if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) { return false; } } state.kind = 'scalar'; state.result = ''; captureStart = captureEnd = state.position; hasPendingContent = false; while (ch !== 0) { if (ch === 0x3A/* : */) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) { break; } } else if (ch === 0x23/* # */) { preceding = state.input.charCodeAt(state.position - 1); if (is_WS_OR_EOL(preceding)) { break; } } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || withinFlowCollection && is_FLOW_INDICATOR(ch)) { break; } else if (is_EOL(ch)) { _line = state.line; _lineStart = state.lineStart; _lineIndent = state.lineIndent; skipSeparationSpace(state, false, -1); if (state.lineIndent >= nodeIndent) { hasPendingContent = true; ch = state.input.charCodeAt(state.position); continue; } else { state.position = captureEnd; state.line = _line; state.lineStart = _lineStart; state.lineIndent = _lineIndent; break; } } if (hasPendingContent) { captureSegment(state, captureStart, captureEnd, false); writeFoldedLines(state, state.line - _line); captureStart = captureEnd = state.position; hasPendingContent = false; } if (!is_WHITE_SPACE(ch)) { captureEnd = state.position + 1; } ch = state.input.charCodeAt(++state.position); } captureSegment(state, captureStart, captureEnd, false); if (state.result) { return true; } state.kind = _kind; state.result = _result; return false; } function readSingleQuotedScalar(state, nodeIndent) { var ch, captureStart, captureEnd; ch = state.input.charCodeAt(state.position); if (ch !== 0x27/* ' */) { return false; } state.kind = 'scalar'; state.result = ''; state.position++; captureStart = captureEnd = state.position; while ((ch = state.input.charCodeAt(state.position)) !== 0) { if (ch === 0x27/* ' */) { captureSegment(state, captureStart, state.position, true); ch = state.input.charCodeAt(++state.position); if (ch === 0x27/* ' */) { captureStart = state.position; state.position++; captureEnd = state.position; } else { return true; } } else if (is_EOL(ch)) { captureSegment(state, captureStart, captureEnd, true); writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); captureStart = captureEnd = state.position; } else if (state.position === state.lineStart && testDocumentSeparator(state)) { throwError(state, 'unexpected end of the document within a single quoted scalar'); } else { state.position++; captureEnd = state.position; } } throwError(state, 'unexpected end of the stream within a single quoted scalar'); } function readDoubleQuotedScalar(state, nodeIndent) { var captureStart, captureEnd, hexLength, hexResult, tmp, ch; ch = state.input.charCodeAt(state.position); if (ch !== 0x22/* " */) { return false; } state.kind = 'scalar'; state.result = ''; state.position++; captureStart = captureEnd = state.position; while ((ch = state.input.charCodeAt(state.position)) !== 0) { if (ch === 0x22/* " */) { captureSegment(state, captureStart, state.position, true); state.position++; return true; } else if (ch === 0x5C/* \ */) { captureSegment(state, captureStart, state.position, true); ch = state.input.charCodeAt(++state.position); if (is_EOL(ch)) { skipSeparationSpace(state, false, nodeIndent); // TODO: rework to inline fn with no type cast? } else if (ch < 256 && simpleEscapeCheck[ch]) { state.result += simpleEscapeMap[ch]; state.position++; } else if ((tmp = escapedHexLen(ch)) > 0) { hexLength = tmp; hexResult = 0; for (; hexLength > 0; hexLength--) { ch = state.input.charCodeAt(++state.position); if ((tmp = fromHexCode(ch)) >= 0) { hexResult = (hexResult << 4) + tmp; } else { throwError(state, 'expected hexadecimal character'); } } state.result += charFromCodepoint(hexResult); state.position++; } else { throwError(state, 'unknown escape sequence'); } captureStart = captureEnd = state.position; } else if (is_EOL(ch)) { captureSegment(state, captureStart, captureEnd, true); writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); captureStart = captureEnd = state.position; } else if (state.position === state.lineStart && testDocumentSeparator(state)) { throwError(state, 'unexpected end of the document within a double quoted scalar'); } else { state.position++; captureEnd = state.position; } } throwError(state, 'unexpected end of the stream within a double quoted scalar'); } function readFlowCollection(state, nodeIndent) { var readNext = true, _line, _lineStart, _pos, _tag = state.tag, _result, _anchor = state.anchor, following, terminator, isPair, isExplicitPair, isMapping, overridableKeys = Object.create(null), keyNode, keyTag, valueNode, ch; ch = state.input.charCodeAt(state.position); if (ch === 0x5B/* [ */) { terminator = 0x5D;/* ] */ isMapping = false; _result = []; } else if (ch === 0x7B/* { */) { terminator = 0x7D;/* } */ isMapping = true; _result = {}; } else { return false; } if (state.anchor !== null) { state.anchorMap[state.anchor] = _result; } ch = state.input.charCodeAt(++state.position); while (ch !== 0) { skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if (ch === terminator) { state.position++; state.tag = _tag; state.anchor = _anchor; state.kind = isMapping ? 'mapping' : 'sequence'; state.result = _result; return true; } else if (!readNext) { throwError(state, 'missed comma between flow collection entries'); } else if (ch === 0x2C/* , */) { // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4 throwError(state, "expected the node content, but found ','"); } keyTag = keyNode = valueNode = null; isPair = isExplicitPair = false; if (ch === 0x3F/* ? */) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following)) { isPair = isExplicitPair = true; state.position++; skipSeparationSpace(state, true, nodeIndent); } } _line = state.line; // Save the current line. _lineStart = state.lineStart; _pos = state.position; composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); keyTag = state.tag; keyNode = state.result; skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { isPair = true; ch = state.input.charCodeAt(++state.position); skipSeparationSpace(state, true, nodeIndent); composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); valueNode = state.result; } if (isMapping) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); } else if (isPair) { _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); } else { _result.push(keyNode); } skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if (ch === 0x2C/* , */) { readNext = true; ch = state.input.charCodeAt(++state.position); } else { readNext = false; } } throwError(state, 'unexpected end of the stream within a flow collection'); } function readBlockScalar(state, nodeIndent) { var captureStart, folding, chomping = CHOMPING_CLIP, didReadContent = false, detectedIndent = false, textIndent = nodeIndent, emptyLines = 0, atMoreIndented = false, tmp, ch; ch = state.input.charCodeAt(state.position); if (ch === 0x7C/* | */) { folding = false; } else if (ch === 0x3E/* > */) { folding = true; } else { return false; } state.kind = 'scalar'; state.result = ''; while (ch !== 0) { ch = state.input.charCodeAt(++state.position); if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { if (CHOMPING_CLIP === chomping) { chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; } else { throwError(state, 'repeat of a chomping mode identifier'); } } else if ((tmp = fromDecimalCode(ch)) >= 0) { if (tmp === 0) { throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); } else if (!detectedIndent) { textIndent = nodeIndent + tmp - 1; detectedIndent = true; } else { throwError(state, 'repeat of an indentation width identifier'); } } else { break; } } if (is_WHITE_SPACE(ch)) { do { ch = state.input.charCodeAt(++state.position); } while (is_WHITE_SPACE(ch)); if (ch === 0x23/* # */) { do { ch = state.input.charCodeAt(++state.position); } while (!is_EOL(ch) && (ch !== 0)); } } while (ch !== 0) { readLineBreak(state); state.lineIndent = 0; ch = state.input.charCodeAt(state.position); while ((!detectedIndent || state.lineIndent < textIndent) && (ch === 0x20/* Space */)) { state.lineIndent++; ch = state.input.charCodeAt(++state.position); } if (!detectedIndent && state.lineIndent > textIndent) { textIndent = state.lineIndent; } if (is_EOL(ch)) { emptyLines++; continue; } // End of the scalar. if (state.lineIndent < textIndent) { // Perform the chomping. if (chomping === CHOMPING_KEEP) { state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); } else if (chomping === CHOMPING_CLIP) { if (didReadContent) { // i.e. only if the scalar is not empty. state.result += '\n'; } } // Break this `while` cycle and go to the funciton's epilogue. break; } // Folded style: use fancy rules to handle line breaks. if (folding) { // Lines starting with white space characters (more-indented lines) are not folded. if (is_WHITE_SPACE(ch)) { atMoreIndented = true; // except for the first content line (cf. Example 8.1) state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); // End of more-indented block. } else if (atMoreIndented) { atMoreIndented = false; state.result += common.repeat('\n', emptyLines + 1); // Just one line break - perceive as the same line. } else if (emptyLines === 0) { if (didReadContent) { // i.e. only if we have already read some scalar content. state.result += ' '; } // Several line breaks - perceive as different lines. } else { state.result += common.repeat('\n', emptyLines); } // Literal style: just add exact number of line breaks between content lines. } else { // Keep all line breaks except the header line break. state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); } didReadContent = true; detectedIndent = true; emptyLines = 0; captureStart = state.position; while (!is_EOL(ch) && (ch !== 0)) { ch = state.input.charCodeAt(++state.position); } captureSegment(state, captureStart, state.position, false); } return true; } function readBlockSequence(state, nodeIndent) { var _line, _tag = state.tag, _anchor = state.anchor, _result = [], following, detected = false, ch; // there is a leading tab before this token, so it can't be a block sequence/mapping; // it can still be flow sequence/mapping or a scalar if (state.firstTabInLine !== -1) return false; if (state.anchor !== null) { state.anchorMap[state.anchor] = _result; } ch = state.input.charCodeAt(state.position); while (ch !== 0) { if (state.firstTabInLine !== -1) { state.position = state.firstTabInLine; throwError(state, 'tab characters must not be used in indentation'); } if (ch !== 0x2D/* - */) { break; } following = state.input.charCodeAt(state.position + 1); if (!is_WS_OR_EOL(following)) { break; } detected = true; state.position++; if (skipSeparationSpace(state, true, -1)) { if (state.lineIndent <= nodeIndent) { _result.push(null); ch = state.input.charCodeAt(state.position); continue; } } _line = state.line; composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); _result.push(state.result); skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { throwError(state, 'bad indentation of a sequence entry'); } else if (state.lineIndent < nodeIndent) { break; } } if (detected) { state.tag = _tag; state.anchor = _anchor; state.kind = 'sequence'; state.result = _result; return true; } return false; } function readBlockMapping(state, nodeIndent, flowIndent) { var following, allowCompact, _line, _keyLine, _keyLineStart, _keyPos, _tag = state.tag, _anchor = state.anchor, _result = {}, overridableKeys = Object.create(null), keyTag = null, keyNode = null, valueNode = null, atExplicitKey = false, detected = false, ch; // there is a leading tab before this token, so it can't be a block sequence/mapping; // it can still be flow sequence/mapping or a scalar if (state.firstTabInLine !== -1) return false; if (state.anchor !== null) { state.anchorMap[state.anchor] = _result; } ch = state.input.charCodeAt(state.position); while (ch !== 0) { if (!atExplicitKey && state.firstTabInLine !== -1) { state.position = state.firstTabInLine; throwError(state, 'tab characters must not be used in indentation'); } following = state.input.charCodeAt(state.position + 1); _line = state.line; // Save the current line. // // Explicit notation case. There are two separate blocks: // first for the key (denoted by "?") and second for the value (denoted by ":") // if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { if (ch === 0x3F/* ? */) { if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } detected = true; atExplicitKey = true; allowCompact = true; } else if (atExplicitKey) { // i.e. 0x3A/* : */ === character after the explicit key. atExplicitKey = false; allowCompact = true; } else { throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); } state.position += 1; ch = following; // // Implicit notation case. Flow-style node as the key first, then ":", and the value. // } else { _keyLine = state.line; _keyLineStart = state.lineStart; _keyPos = state.position; if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { // Neither implicit nor explicit notation. // Reading is done. Go to the epilogue. break; } if (state.line === _line) { ch = state.input.charCodeAt(state.position); while (is_WHITE_SPACE(ch)) { ch = state.input.charCodeAt(++state.position); } if (ch === 0x3A/* : */) { ch = state.input.charCodeAt(++state.position); if (!is_WS_OR_EOL(ch)) { throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); } if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } detected = true; atExplicitKey = false; allowCompact = false; keyTag = state.tag; keyNode = state.result; } else if (detected) { throwError(state, 'can not read an implicit mapping pair; a colon is missed'); } else { state.tag = _tag; state.anchor = _anchor; return true; // Keep the result of `composeNode`. } } else if (detected) { throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); } else { state.tag = _tag; state.anchor = _anchor; return true; // Keep the result of `composeNode`. } } // // Common reading code for both explicit and implicit notations. // if (state.line === _line || state.lineIndent > nodeIndent) { if (atExplicitKey) { _keyLine = state.line; _keyLineStart = state.lineStart; _keyPos = state.position; } if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { if (atExplicitKey) { keyNode = state.result; } else { valueNode = state.result; } } if (!atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); } if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { throwError(state, 'bad indentation of a mapping entry'); } else if (state.lineIndent < nodeIndent) { break; } } // // Epilogue. // // Special case: last mapping's node contains only the key in explicit notation. if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); } // Expose the resulting mapping. if (detected) { state.tag = _tag; state.anchor = _anchor; state.kind = 'mapping'; state.result = _result; } return detected; } function readTagProperty(state) { var _position, isVerbatim = false, isNamed = false, tagHandle, tagName, ch; ch = state.input.charCodeAt(state.position); if (ch !== 0x21/* ! */) return false; if (state.tag !== null) { throwError(state, 'duplication of a tag property'); } ch = state.input.charCodeAt(++state.position); if (ch === 0x3C/* < */) { isVerbatim = true; ch = state.input.charCodeAt(++state.position); } else if (ch === 0x21/* ! */) { isNamed = true; tagHandle = '!!'; ch = state.input.charCodeAt(++state.position); } else { tagHandle = '!'; } _position = state.position; if (isVerbatim) { do { ch = state.input.charCodeAt(++state.position); } while (ch !== 0 && ch !== 0x3E/* > */); if (state.position < state.length) { tagName = state.input.slice(_position, state.position); ch = state.input.charCodeAt(++state.position); } else { throwError(state, 'unexpected end of the stream within a verbatim tag'); } } else { while (ch !== 0 && !is_WS_OR_EOL(ch)) { if (ch === 0x21/* ! */) { if (!isNamed) { tagHandle = state.input.slice(_position - 1, state.position + 1); if (!PATTERN_TAG_HANDLE.test(tagHandle)) { throwError(state, 'named tag handle cannot contain such characters'); } isNamed = true; _position = state.position + 1; } else { throwError(state, 'tag suffix cannot contain exclamation marks'); } } ch = state.input.charCodeAt(++state.position); } tagName = state.input.slice(_position, state.position); if (PATTERN_FLOW_INDICATORS.test(tagName)) { throwError(state, 'tag suffix cannot contain flow indicator characters'); } } if (tagName && !PATTERN_TAG_URI.test(tagName)) { throwError(state, 'tag name cannot contain such characters: ' + tagName); } try { tagName = decodeURIComponent(tagName); } catch (err) { throwError(state, 'tag name is malformed: ' + tagName); } if (isVerbatim) { state.tag = tagName; } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { state.tag = state.tagMap[tagHandle] + tagName; } else if (tagHandle === '!') { state.tag = '!' + tagName; } else if (tagHandle === '!!') { state.tag = 'tag:yaml.org,2002:' + tagName; } else { throwError(state, 'undeclared tag handle "' + tagHandle + '"'); } return true; } function readAnchorProperty(state) { var _position, ch; ch = state.input.charCodeAt(state.position); if (ch !== 0x26/* & */) return false; if (state.anchor !== null) { throwError(state, 'duplication of an anchor property'); } ch = state.input.charCodeAt(++state.position); _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { ch = state.input.charCodeAt(++state.position); } if (state.position === _position) { throwError(state, 'name of an anchor node must contain at least one character'); } state.anchor = state.input.slice(_position, state.position); return true; } function readAlias(state) { var _position, alias, ch; ch = state.input.charCodeAt(state.position); if (ch !== 0x2A/* * */) return false; ch = state.input.charCodeAt(++state.position); _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { ch = state.input.charCodeAt(++state.position); } if (state.position === _position) { throwError(state, 'name of an alias node must contain at least one character'); } alias = state.input.slice(_position, state.position); if (!_hasOwnProperty.call(state.anchorMap, alias)) { throwError(state, 'unidentified alias "' + alias + '"'); } state.result = state.anchorMap[alias]; skipSeparationSpace(state, true, -1); return true; } function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { var allowBlockStyles, allowBlockScalars, allowBlockCollections, indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { indentStatus = 1; } else if (state.lineIndent === parentIndent) { indentStatus = 0; } else if (state.lineIndent < parentIndent) { indentStatus = -1; } } } if (indentStatus === 1) { while (readTagProperty(state) || readAnchorProperty(state)) { if (skipSeparationSpace(state, true, -1)) { atNewLine = true; allowBlockCollections = allowBlockStyles; if (state.lineIndent > parentIndent) { indentStatus = 1; } else if (state.lineIndent === parentIndent) { indentStatus = 0; } else if (state.lineIndent < parentIndent) { indentStatus = -1; } } else { allowBlockCollections = false; } } } if (allowBlockCollections) { allowBlockCollections = atNewLine || allowCompact; } if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { flowIndent = parentIndent; } else { flowIndent = parentIndent + 1; } blockIndent = state.position - state.lineStart; if (indentStatus === 1) { if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) { hasContent = true; } else { if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) { hasContent = true; } else if (readAlias(state)) { hasContent = true; if (state.tag !== null || state.anchor !== null) { throwError(state, 'alias node should not have any properties'); } } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { hasContent = true; if (state.tag === null) { state.tag = '?'; } } if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } } } else if (indentStatus === 0) { // Special case: block sequences are allowed to have same indentation level as the parent. // http://www.yaml.org/spec/1.2/spec.html#id2799784 hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); } } if (state.tag === null) { if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } } else if (state.tag === '?') { // Implicit resolving is not allowed for non-scalar types, and '?' // non-specific tag is only automatically assigned to plain scalars. // // We only need to check kind conformity in case user explicitly assigns '?' // tag, for example like this: "! [0]" // if (state.result !== null && state.kind !== 'scalar') { throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); } for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { type = state.implicitTypes[typeIndex]; if (type.resolve(state.result)) { // `state.result` updated in resolver if matched state.result = type.construct(state.result); state.tag = type.tag; if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } break; } } } else if (state.tag !== '!') { if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { type = state.typeMap[state.kind || 'fallback'][state.tag]; } else { // looking for multi type type = null; typeList = state.typeMap.multi[state.kind || 'fallback']; for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { type = typeList[typeIndex]; break; } } } if (!type) { throwError(state, 'unknown tag !<' + state.tag + '>'); } if (state.result !== null && type.kind !== state.kind) { throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); } if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); } else { state.result = type.construct(state.result, state.tag); if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } } } if (state.listener !== null) { state.listener('close', state); } return state.tag !== null || state.anchor !== null || hasContent; } function readDocument(state) { var documentStart = state.position, _position, directiveName, directiveArgs, hasDirectives = false, ch; state.version = null; state.checkLineBreaks = state.legacy; state.tagMap = Object.create(null); state.anchorMap = Object.create(null); while ((ch = state.input.charCodeAt(state.position)) !== 0) { skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); if (state.lineIndent > 0 || ch !== 0x25/* % */) { break; } hasDirectives = true; ch = state.input.charCodeAt(++state.position); _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch)) { ch = state.input.charCodeAt(++state.position); } directiveName = state.input.slice(_position, state.position); directiveArgs = []; if (directiveName.length < 1) { throwError(state, 'directive name must not be less than one character in length'); } while (ch !== 0) { while (is_WHITE_SPACE(ch)) { ch = state.input.charCodeAt(++state.position); } if (ch === 0x23/* # */) { do { ch = state.input.charCodeAt(++state.position); } while (ch !== 0 && !is_EOL(ch)); break; } if (is_EOL(ch)) break; _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch)) { ch = state.input.charCodeAt(++state.position); } directiveArgs.push(state.input.slice(_position, state.position)); } if (ch !== 0) readLineBreak(state); if (_hasOwnProperty.call(directiveHandlers, directiveName)) { directiveHandlers[directiveName](state, directiveName, directiveArgs); } else { throwWarning(state, 'unknown document directive "' + directiveName + '"'); } } skipSeparationSpace(state, true, -1); if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 0x2D/* - */ && state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { state.position += 3; skipSeparationSpace(state, true, -1); } else if (hasDirectives) { throwError(state, 'directives end mark is expected'); } composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); skipSeparationSpace(state, true, -1); if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { throwWarning(state, 'non-ASCII line breaks are interpreted as content'); } state.documents.push(state.result); if (state.position === state.lineStart && testDocumentSeparator(state)) { if (state.input.charCodeAt(state.position) === 0x2E/* . */) { state.position += 3; skipSeparationSpace(state, true, -1); } return; } if (state.position < (state.length - 1)) { throwError(state, 'end of the stream or a document separator is expected'); } else { return; } } function loadDocuments(input, options) { input = String(input); options = options || {}; if (input.length !== 0) { // Add tailing `\n` if not exists if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { input += '\n'; } // Strip BOM if (input.charCodeAt(0) === 0xFEFF) { input = input.slice(1); } } var state = new State(input, options); var nullpos = input.indexOf('\0'); if (nullpos !== -1) { state.position = nullpos; throwError(state, 'null byte is not allowed in input'); } // Use 0 as string terminator. That significantly simplifies bounds check. state.input += '\0'; while (state.input.charCodeAt(state.position) === 0x20/* Space */) { state.lineIndent += 1; state.position += 1; } while (state.position < (state.length - 1)) { readDocument(state); } return state.documents; } function loadAll(input, iterator, options) { if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { options = iterator; iterator = null; } var documents = loadDocuments(input, options); if (typeof iterator !== 'function') { return documents; } for (var index = 0, length = documents.length; index < length; index += 1) { iterator(documents[index]); } } function load(input, options) { var documents = loadDocuments(input, options); if (documents.length === 0) { /*eslint-disable no-undefined*/ return undefined; } else if (documents.length === 1) { return documents[0]; } throw new YAMLException('expected a single document in the stream, but found more'); } module.exports.loadAll = loadAll; module.exports.load = load; /***/ }), /***/ 8237: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*eslint-disable max-len*/ var YAMLException = __webpack_require__(43669); var Type = __webpack_require__(55601); function compileList(schema, name) { var result = []; schema[name].forEach(function (currentType) { var newIndex = result.length; result.forEach(function (previousType, previousIndex) { if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) { newIndex = previousIndex; } }); result[newIndex] = currentType; }); return result; } function compileMap(/* lists... */) { var result = { scalar: {}, sequence: {}, mapping: {}, fallback: {}, multi: { scalar: [], sequence: [], mapping: [], fallback: [] } }, index, length; function collectType(type) { if (type.multi) { result.multi[type.kind].push(type); result.multi['fallback'].push(type); } else { result[type.kind][type.tag] = result['fallback'][type.tag] = type; } } for (index = 0, length = arguments.length; index < length; index += 1) { arguments[index].forEach(collectType); } return result; } function Schema(definition) { return this.extend(definition); } Schema.prototype.extend = function extend(definition) { var implicit = []; var explicit = []; if (definition instanceof Type) { // Schema.extend(type) explicit.push(definition); } else if (Array.isArray(definition)) { // Schema.extend([ type1, type2, ... ]) explicit = explicit.concat(definition); } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] }) if (definition.implicit) implicit = implicit.concat(definition.implicit); if (definition.explicit) explicit = explicit.concat(definition.explicit); } else { throw new YAMLException('Schema.extend argument should be a Type, [ Type ], ' + 'or a schema definition ({ implicit: [...], explicit: [...] })'); } implicit.forEach(function (type) { if (!(type instanceof Type)) { throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); } if (type.loadKind && type.loadKind !== 'scalar') { throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); } if (type.multi) { throw new YAMLException('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.'); } }); explicit.forEach(function (type) { if (!(type instanceof Type)) { throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); } }); var result = Object.create(Schema.prototype); result.implicit = (this.implicit || []).concat(implicit); result.explicit = (this.explicit || []).concat(explicit); result.compiledImplicit = compileList(result, 'implicit'); result.compiledExplicit = compileList(result, 'explicit'); result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); return result; }; module.exports = Schema; /***/ }), /***/ 41695: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Standard YAML's Core schema. // http://www.yaml.org/spec/1.2/spec.html#id2804923 // // NOTE: JS-YAML does not support schema-specific tag resolution restrictions. // So, Core schema has no distinctions from JSON schema is JS-YAML. module.exports = __webpack_require__(92427); /***/ }), /***/ 4170: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // JS-YAML's default schema for `safeLoad` function. // It is not described in the YAML specification. // // This schema is based on standard YAML's Core schema and includes most of // extra types described at YAML tag repository. (http://yaml.org/type/) module.exports = __webpack_require__(41695).extend({ implicit: [ __webpack_require__(4587), __webpack_require__(441) ], explicit: [ __webpack_require__(25167), __webpack_require__(86609), __webpack_require__(53490), __webpack_require__(79321) ] }); /***/ }), /***/ 98934: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Standard YAML's Failsafe schema. // http://www.yaml.org/spec/1.2/spec.html#id2802346 var Schema = __webpack_require__(8237); module.exports = new Schema({ explicit: [ __webpack_require__(17033), __webpack_require__(31597), __webpack_require__(4611) ] }); /***/ }), /***/ 92427: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Standard YAML's JSON schema. // http://www.yaml.org/spec/1.2/spec.html#id2803231 // // NOTE: JS-YAML does not support schema-specific tag resolution restrictions. // So, this schema is not such strict as defined in the YAML specification. // It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. module.exports = __webpack_require__(98934).extend({ implicit: [ __webpack_require__(49252), __webpack_require__(72531), __webpack_require__(76916), __webpack_require__(75522) ] }); /***/ }), /***/ 13237: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var common = __webpack_require__(46358); // get snippet for a single line, respecting maxLength function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { var head = ''; var tail = ''; var maxHalfLength = Math.floor(maxLineLength / 2) - 1; if (position - lineStart > maxHalfLength) { head = ' ... '; lineStart = position - maxHalfLength + head.length; } if (lineEnd - position > maxHalfLength) { tail = ' ...'; lineEnd = position + maxHalfLength - tail.length; } return { str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, pos: position - lineStart + head.length // relative position }; } function padStart(string, max) { return common.repeat(' ', max - string.length) + string; } function makeSnippet(mark, options) { options = Object.create(options || null); if (!mark.buffer) return null; if (!options.maxLength) options.maxLength = 79; if (typeof options.indent !== 'number') options.indent = 1; if (typeof options.linesBefore !== 'number') options.linesBefore = 3; if (typeof options.linesAfter !== 'number') options.linesAfter = 2; var re = /\r?\n|\r|\0/g; var lineStarts = [ 0 ]; var lineEnds = []; var match; var foundLineNo = -1; while ((match = re.exec(mark.buffer))) { lineEnds.push(match.index); lineStarts.push(match.index + match[0].length); if (mark.position <= match.index && foundLineNo < 0) { foundLineNo = lineStarts.length - 2; } } if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; var result = '', i, line; var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); for (i = 1; i <= options.linesBefore; i++) { if (foundLineNo - i < 0) break; line = getLine( mark.buffer, lineStarts[foundLineNo - i], lineEnds[foundLineNo - i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), maxLineLength ); result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + ' | ' + line.str + '\n' + result; } line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + ' | ' + line.str + '\n'; result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; for (i = 1; i <= options.linesAfter; i++) { if (foundLineNo + i >= lineEnds.length) break; line = getLine( mark.buffer, lineStarts[foundLineNo + i], lineEnds[foundLineNo + i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), maxLineLength ); result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + ' | ' + line.str + '\n'; } return result.replace(/\n$/, ''); } module.exports = makeSnippet; /***/ }), /***/ 55601: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var YAMLException = __webpack_require__(43669); var TYPE_CONSTRUCTOR_OPTIONS = [ 'kind', 'multi', 'resolve', 'construct', 'instanceOf', 'predicate', 'represent', 'representName', 'defaultStyle', 'styleAliases' ]; var YAML_NODE_KINDS = [ 'scalar', 'sequence', 'mapping' ]; function compileStyleAliases(map) { var result = {}; if (map !== null) { Object.keys(map).forEach(function (style) { map[style].forEach(function (alias) { result[String(alias)] = style; }); }); } return result; } function Type(tag, options) { options = options || {}; Object.keys(options).forEach(function (name) { if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); } }); // TODO: Add tag format check. this.options = options; // keep original options in case user wants to extend this type later this.tag = tag; this.kind = options['kind'] || null; this.resolve = options['resolve'] || function () { return true; }; this.construct = options['construct'] || function (data) { return data; }; this.instanceOf = options['instanceOf'] || null; this.predicate = options['predicate'] || null; this.represent = options['represent'] || null; this.representName = options['representName'] || null; this.defaultStyle = options['defaultStyle'] || null; this.multi = options['multi'] || false; this.styleAliases = compileStyleAliases(options['styleAliases'] || null); if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); } } module.exports = Type; /***/ }), /***/ 25167: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*eslint-disable no-bitwise*/ var Type = __webpack_require__(55601); // [ 64, 65, 66 ] -> [ padding, CR, LF ] var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; function resolveYamlBinary(data) { if (data === null) return false; var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; // Convert one by one. for (idx = 0; idx < max; idx++) { code = map.indexOf(data.charAt(idx)); // Skip CR/LF if (code > 64) continue; // Fail on illegal characters if (code < 0) return false; bitlen += 6; } // If there are any bits left, source was corrupted return (bitlen % 8) === 0; } function constructYamlBinary(data) { var idx, tailbits, input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan max = input.length, map = BASE64_MAP, bits = 0, result = []; // Collect by 6*4 bits (3 bytes) for (idx = 0; idx < max; idx++) { if ((idx % 4 === 0) && idx) { result.push((bits >> 16) & 0xFF); result.push((bits >> 8) & 0xFF); result.push(bits & 0xFF); } bits = (bits << 6) | map.indexOf(input.charAt(idx)); } // Dump tail tailbits = (max % 4) * 6; if (tailbits === 0) { result.push((bits >> 16) & 0xFF); result.push((bits >> 8) & 0xFF); result.push(bits & 0xFF); } else if (tailbits === 18) { result.push((bits >> 10) & 0xFF); result.push((bits >> 2) & 0xFF); } else if (tailbits === 12) { result.push((bits >> 4) & 0xFF); } return new Uint8Array(result); } function representYamlBinary(object /*, style*/) { var result = '', bits = 0, idx, tail, max = object.length, map = BASE64_MAP; // Convert every three bytes to 4 ASCII characters. for (idx = 0; idx < max; idx++) { if ((idx % 3 === 0) && idx) { result += map[(bits >> 18) & 0x3F]; result += map[(bits >> 12) & 0x3F]; result += map[(bits >> 6) & 0x3F]; result += map[bits & 0x3F]; } bits = (bits << 8) + object[idx]; } // Dump tail tail = max % 3; if (tail === 0) { result += map[(bits >> 18) & 0x3F]; result += map[(bits >> 12) & 0x3F]; result += map[(bits >> 6) & 0x3F]; result += map[bits & 0x3F]; } else if (tail === 2) { result += map[(bits >> 10) & 0x3F]; result += map[(bits >> 4) & 0x3F]; result += map[(bits << 2) & 0x3F]; result += map[64]; } else if (tail === 1) { result += map[(bits >> 2) & 0x3F]; result += map[(bits << 4) & 0x3F]; result += map[64]; result += map[64]; } return result; } function isBinary(obj) { return Object.prototype.toString.call(obj) === '[object Uint8Array]'; } module.exports = new Type('tag:yaml.org,2002:binary', { kind: 'scalar', resolve: resolveYamlBinary, construct: constructYamlBinary, predicate: isBinary, represent: representYamlBinary }); /***/ }), /***/ 72531: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Type = __webpack_require__(55601); function resolveYamlBoolean(data) { if (data === null) return false; var max = data.length; return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); } function constructYamlBoolean(data) { return data === 'true' || data === 'True' || data === 'TRUE'; } function isBoolean(object) { return Object.prototype.toString.call(object) === '[object Boolean]'; } module.exports = new Type('tag:yaml.org,2002:bool', { kind: 'scalar', resolve: resolveYamlBoolean, construct: constructYamlBoolean, predicate: isBoolean, represent: { lowercase: function (object) { return object ? 'true' : 'false'; }, uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, camelcase: function (object) { return object ? 'True' : 'False'; } }, defaultStyle: 'lowercase' }); /***/ }), /***/ 75522: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var common = __webpack_require__(46358); var Type = __webpack_require__(55601); var YAML_FLOAT_PATTERN = new RegExp( // 2.5e4, 2.5 and integers '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + // .2e4, .2 // special case, seems not from spec '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + // .inf '|[-+]?\\.(?:inf|Inf|INF)' + // .nan '|\\.(?:nan|NaN|NAN))$'); function resolveYamlFloat(data) { if (data === null) return false; if (!YAML_FLOAT_PATTERN.test(data) || // Quick hack to not allow integers end with `_` // Probably should update regexp & check speed data[data.length - 1] === '_') { return false; } return true; } function constructYamlFloat(data) { var value, sign; value = data.replace(/_/g, '').toLowerCase(); sign = value[0] === '-' ? -1 : 1; if ('+-'.indexOf(value[0]) >= 0) { value = value.slice(1); } if (value === '.inf') { return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; } else if (value === '.nan') { return NaN; } return sign * parseFloat(value, 10); } var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; function representYamlFloat(object, style) { var res; if (isNaN(object)) { switch (style) { case 'lowercase': return '.nan'; case 'uppercase': return '.NAN'; case 'camelcase': return '.NaN'; } } else if (Number.POSITIVE_INFINITY === object) { switch (style) { case 'lowercase': return '.inf'; case 'uppercase': return '.INF'; case 'camelcase': return '.Inf'; } } else if (Number.NEGATIVE_INFINITY === object) { switch (style) { case 'lowercase': return '-.inf'; case 'uppercase': return '-.INF'; case 'camelcase': return '-.Inf'; } } else if (common.isNegativeZero(object)) { return '-0.0'; } res = object.toString(10); // JS stringifier can build scientific format without dots: 5e-100, // while YAML requres dot: 5.e-100. Fix it with simple hack return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; } function isFloat(object) { return (Object.prototype.toString.call(object) === '[object Number]') && (object % 1 !== 0 || common.isNegativeZero(object)); } module.exports = new Type('tag:yaml.org,2002:float', { kind: 'scalar', resolve: resolveYamlFloat, construct: constructYamlFloat, predicate: isFloat, represent: representYamlFloat, defaultStyle: 'lowercase' }); /***/ }), /***/ 76916: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var common = __webpack_require__(46358); var Type = __webpack_require__(55601); function isHexCode(c) { return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || ((0x61/* a */ <= c) && (c <= 0x66/* f */)); } function isOctCode(c) { return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); } function isDecCode(c) { return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); } function resolveYamlInteger(data) { if (data === null) return false; var max = data.length, index = 0, hasDigits = false, ch; if (!max) return false; ch = data[index]; // sign if (ch === '-' || ch === '+') { ch = data[++index]; } if (ch === '0') { // 0 if (index + 1 === max) return true; ch = data[++index]; // base 2, base 8, base 16 if (ch === 'b') { // base 2 index++; for (; index < max; index++) { ch = data[index]; if (ch === '_') continue; if (ch !== '0' && ch !== '1') return false; hasDigits = true; } return hasDigits && ch !== '_'; } if (ch === 'x') { // base 16 index++; for (; index < max; index++) { ch = data[index]; if (ch === '_') continue; if (!isHexCode(data.charCodeAt(index))) return false; hasDigits = true; } return hasDigits && ch !== '_'; } if (ch === 'o') { // base 8 index++; for (; index < max; index++) { ch = data[index]; if (ch === '_') continue; if (!isOctCode(data.charCodeAt(index))) return false; hasDigits = true; } return hasDigits && ch !== '_'; } } // base 10 (except 0) // value should not start with `_`; if (ch === '_') return false; for (; index < max; index++) { ch = data[index]; if (ch === '_') continue; if (!isDecCode(data.charCodeAt(index))) { return false; } hasDigits = true; } // Should have digits and should not end with `_` if (!hasDigits || ch === '_') return false; return true; } function constructYamlInteger(data) { var value = data, sign = 1, ch; if (value.indexOf('_') !== -1) { value = value.replace(/_/g, ''); } ch = value[0]; if (ch === '-' || ch === '+') { if (ch === '-') sign = -1; value = value.slice(1); ch = value[0]; } if (value === '0') return 0; if (ch === '0') { if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); if (value[1] === 'x') return sign * parseInt(value.slice(2), 16); if (value[1] === 'o') return sign * parseInt(value.slice(2), 8); } return sign * parseInt(value, 10); } function isInteger(object) { return (Object.prototype.toString.call(object)) === '[object Number]' && (object % 1 === 0 && !common.isNegativeZero(object)); } module.exports = new Type('tag:yaml.org,2002:int', { kind: 'scalar', resolve: resolveYamlInteger, construct: constructYamlInteger, predicate: isInteger, represent: { binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); }, decimal: function (obj) { return obj.toString(10); }, /* eslint-disable max-len */ hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } }, defaultStyle: 'decimal', styleAliases: { binary: [ 2, 'bin' ], octal: [ 8, 'oct' ], decimal: [ 10, 'dec' ], hexadecimal: [ 16, 'hex' ] } }); /***/ }), /***/ 4611: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Type = __webpack_require__(55601); module.exports = new Type('tag:yaml.org,2002:map', { kind: 'mapping', construct: function (data) { return data !== null ? data : {}; } }); /***/ }), /***/ 441: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Type = __webpack_require__(55601); function resolveYamlMerge(data) { return data === '<<' || data === null; } module.exports = new Type('tag:yaml.org,2002:merge', { kind: 'scalar', resolve: resolveYamlMerge }); /***/ }), /***/ 49252: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Type = __webpack_require__(55601); function resolveYamlNull(data) { if (data === null) return true; var max = data.length; return (max === 1 && data === '~') || (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); } function constructYamlNull() { return null; } function isNull(object) { return object === null; } module.exports = new Type('tag:yaml.org,2002:null', { kind: 'scalar', resolve: resolveYamlNull, construct: constructYamlNull, predicate: isNull, represent: { canonical: function () { return '~'; }, lowercase: function () { return 'null'; }, uppercase: function () { return 'NULL'; }, camelcase: function () { return 'Null'; }, empty: function () { return ''; } }, defaultStyle: 'lowercase' }); /***/ }), /***/ 86609: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Type = __webpack_require__(55601); var _hasOwnProperty = Object.prototype.hasOwnProperty; var _toString = Object.prototype.toString; function resolveYamlOmap(data) { if (data === null) return true; var objectKeys = [], index, length, pair, pairKey, pairHasKey, object = data; for (index = 0, length = object.length; index < length; index += 1) { pair = object[index]; pairHasKey = false; if (_toString.call(pair) !== '[object Object]') return false; for (pairKey in pair) { if (_hasOwnProperty.call(pair, pairKey)) { if (!pairHasKey) pairHasKey = true; else return false; } } if (!pairHasKey) return false; if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); else return false; } return true; } function constructYamlOmap(data) { return data !== null ? data : []; } module.exports = new Type('tag:yaml.org,2002:omap', { kind: 'sequence', resolve: resolveYamlOmap, construct: constructYamlOmap }); /***/ }), /***/ 53490: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Type = __webpack_require__(55601); var _toString = Object.prototype.toString; function resolveYamlPairs(data) { if (data === null) return true; var index, length, pair, keys, result, object = data; result = new Array(object.length); for (index = 0, length = object.length; index < length; index += 1) { pair = object[index]; if (_toString.call(pair) !== '[object Object]') return false; keys = Object.keys(pair); if (keys.length !== 1) return false; result[index] = [ keys[0], pair[keys[0]] ]; } return true; } function constructYamlPairs(data) { if (data === null) return []; var index, length, pair, keys, result, object = data; result = new Array(object.length); for (index = 0, length = object.length; index < length; index += 1) { pair = object[index]; keys = Object.keys(pair); result[index] = [ keys[0], pair[keys[0]] ]; } return result; } module.exports = new Type('tag:yaml.org,2002:pairs', { kind: 'sequence', resolve: resolveYamlPairs, construct: constructYamlPairs }); /***/ }), /***/ 31597: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Type = __webpack_require__(55601); module.exports = new Type('tag:yaml.org,2002:seq', { kind: 'sequence', construct: function (data) { return data !== null ? data : []; } }); /***/ }), /***/ 79321: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Type = __webpack_require__(55601); var _hasOwnProperty = Object.prototype.hasOwnProperty; function resolveYamlSet(data) { if (data === null) return true; var key, object = data; for (key in object) { if (_hasOwnProperty.call(object, key)) { if (object[key] !== null) return false; } } return true; } function constructYamlSet(data) { return data !== null ? data : {}; } module.exports = new Type('tag:yaml.org,2002:set', { kind: 'mapping', resolve: resolveYamlSet, construct: constructYamlSet }); /***/ }), /***/ 17033: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Type = __webpack_require__(55601); module.exports = new Type('tag:yaml.org,2002:str', { kind: 'scalar', construct: function (data) { return data !== null ? data : ''; } }); /***/ }), /***/ 4587: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Type = __webpack_require__(55601); var YAML_DATE_REGEXP = new RegExp( '^([0-9][0-9][0-9][0-9])' + // [1] year '-([0-9][0-9])' + // [2] month '-([0-9][0-9])$'); // [3] day var YAML_TIMESTAMP_REGEXP = new RegExp( '^([0-9][0-9][0-9][0-9])' + // [1] year '-([0-9][0-9]?)' + // [2] month '-([0-9][0-9]?)' + // [3] day '(?:[Tt]|[ \\t]+)' + // ... '([0-9][0-9]?)' + // [4] hour ':([0-9][0-9])' + // [5] minute ':([0-9][0-9])' + // [6] second '(?:\\.([0-9]*))?' + // [7] fraction '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour '(?::([0-9][0-9]))?))?$'); // [11] tz_minute function resolveYamlTimestamp(data) { if (data === null) return false; if (YAML_DATE_REGEXP.exec(data) !== null) return true; if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; return false; } function constructYamlTimestamp(data) { var match, year, month, day, hour, minute, second, fraction = 0, delta = null, tz_hour, tz_minute, date; match = YAML_DATE_REGEXP.exec(data); if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); if (match === null) throw new Error('Date resolve error'); // match: [1] year [2] month [3] day year = +(match[1]); month = +(match[2]) - 1; // JS month starts with 0 day = +(match[3]); if (!match[4]) { // no hour return new Date(Date.UTC(year, month, day)); } // match: [4] hour [5] minute [6] second [7] fraction hour = +(match[4]); minute = +(match[5]); second = +(match[6]); if (match[7]) { fraction = match[7].slice(0, 3); while (fraction.length < 3) { // milli-seconds fraction += '0'; } fraction = +fraction; } // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute if (match[9]) { tz_hour = +(match[10]); tz_minute = +(match[11] || 0); delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds if (match[9] === '-') delta = -delta; } date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); if (delta) date.setTime(date.getTime() - delta); return date; } function representYamlTimestamp(object /*, style*/) { return object.toISOString(); } module.exports = new Type('tag:yaml.org,2002:timestamp', { kind: 'scalar', resolve: resolveYamlTimestamp, construct: constructYamlTimestamp, instanceOf: Date, represent: representYamlTimestamp }); /***/ }), /***/ 17689: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // A linked list to keep track of recently-used-ness const Yallist = __webpack_require__(5436) const MAX = Symbol('max') const LENGTH = Symbol('length') const LENGTH_CALCULATOR = Symbol('lengthCalculator') const ALLOW_STALE = Symbol('allowStale') const MAX_AGE = Symbol('maxAge') const DISPOSE = Symbol('dispose') const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') const LRU_LIST = Symbol('lruList') const CACHE = Symbol('cache') const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') const naiveLength = () => 1 // lruList is a yallist where the head is the youngest // item, and the tail is the oldest. the list contains the Hit // objects as the entries. // Each Hit object has a reference to its Yallist.Node. This // never changes. // // cache is a Map (or PseudoMap) that matches the keys to // the Yallist.Node object. class LRUCache { constructor (options) { if (typeof options === 'number') options = { max: options } if (!options) options = {} if (options.max && (typeof options.max !== 'number' || options.max < 0)) throw new TypeError('max must be a non-negative number') // Kind of weird to have a default max of Infinity, but oh well. const max = this[MAX] = options.max || Infinity const lc = options.length || naiveLength this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc this[ALLOW_STALE] = options.stale || false if (options.maxAge && typeof options.maxAge !== 'number') throw new TypeError('maxAge must be a number') this[MAX_AGE] = options.maxAge || 0 this[DISPOSE] = options.dispose this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false this.reset() } // resize the cache when the max changes. set max (mL) { if (typeof mL !== 'number' || mL < 0) throw new TypeError('max must be a non-negative number') this[MAX] = mL || Infinity trim(this) } get max () { return this[MAX] } set allowStale (allowStale) { this[ALLOW_STALE] = !!allowStale } get allowStale () { return this[ALLOW_STALE] } set maxAge (mA) { if (typeof mA !== 'number') throw new TypeError('maxAge must be a non-negative number') this[MAX_AGE] = mA trim(this) } get maxAge () { return this[MAX_AGE] } // resize the cache when the lengthCalculator changes. set lengthCalculator (lC) { if (typeof lC !== 'function') lC = naiveLength if (lC !== this[LENGTH_CALCULATOR]) { this[LENGTH_CALCULATOR] = lC this[LENGTH] = 0 this[LRU_LIST].forEach(hit => { hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) this[LENGTH] += hit.length }) } trim(this) } get lengthCalculator () { return this[LENGTH_CALCULATOR] } get length () { return this[LENGTH] } get itemCount () { return this[LRU_LIST].length } rforEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].tail; walker !== null;) { const prev = walker.prev forEachStep(this, fn, walker, thisp) walker = prev } } forEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].head; walker !== null;) { const next = walker.next forEachStep(this, fn, walker, thisp) walker = next } } keys () { return this[LRU_LIST].toArray().map(k => k.key) } values () { return this[LRU_LIST].toArray().map(k => k.value) } reset () { if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) { this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) } this[CACHE] = new Map() // hash of items by key this[LRU_LIST] = new Yallist() // list of items in order of use recency this[LENGTH] = 0 // length of items in the list } dump () { return this[LRU_LIST].map(hit => isStale(this, hit) ? false : { k: hit.key, v: hit.value, e: hit.now + (hit.maxAge || 0) }).toArray().filter(h => h) } dumpLru () { return this[LRU_LIST] } set (key, value, maxAge) { maxAge = maxAge || this[MAX_AGE] if (maxAge && typeof maxAge !== 'number') throw new TypeError('maxAge must be a number') const now = maxAge ? Date.now() : 0 const len = this[LENGTH_CALCULATOR](value, key) if (this[CACHE].has(key)) { if (len > this[MAX]) { del(this, this[CACHE].get(key)) return false } const node = this[CACHE].get(key) const item = node.value // dispose of the old one before overwriting // split out into 2 ifs for better coverage tracking if (this[DISPOSE]) { if (!this[NO_DISPOSE_ON_SET]) this[DISPOSE](key, item.value) } item.now = now item.maxAge = maxAge item.value = value this[LENGTH] += len - item.length item.length = len this.get(key) trim(this) return true } const hit = new Entry(key, value, len, now, maxAge) // oversized objects fall out of cache automatically. if (hit.length > this[MAX]) { if (this[DISPOSE]) this[DISPOSE](key, value) return false } this[LENGTH] += hit.length this[LRU_LIST].unshift(hit) this[CACHE].set(key, this[LRU_LIST].head) trim(this) return true } has (key) { if (!this[CACHE].has(key)) return false const hit = this[CACHE].get(key).value return !isStale(this, hit) } get (key) { return get(this, key, true) } peek (key) { return get(this, key, false) } pop () { const node = this[LRU_LIST].tail if (!node) return null del(this, node) return node.value } del (key) { del(this, this[CACHE].get(key)) } load (arr) { // reset the cache this.reset() const now = Date.now() // A previous serialized cache has the most recent items first for (let l = arr.length - 1; l >= 0; l--) { const hit = arr[l] const expiresAt = hit.e || 0 if (expiresAt === 0) // the item was created without expiration in a non aged cache this.set(hit.k, hit.v) else { const maxAge = expiresAt - now // dont add already expired items if (maxAge > 0) { this.set(hit.k, hit.v, maxAge) } } } } prune () { this[CACHE].forEach((value, key) => get(this, key, false)) } } const get = (self, key, doUse) => { const node = self[CACHE].get(key) if (node) { const hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) return undefined } else { if (doUse) { if (self[UPDATE_AGE_ON_GET]) node.value.now = Date.now() self[LRU_LIST].unshiftNode(node) } } return hit.value } } const isStale = (self, hit) => { if (!hit || (!hit.maxAge && !self[MAX_AGE])) return false const diff = Date.now() - hit.now return hit.maxAge ? diff > hit.maxAge : self[MAX_AGE] && (diff > self[MAX_AGE]) } const trim = self => { if (self[LENGTH] > self[MAX]) { for (let walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) { // We know that we're about to delete this one, and also // what the next least recently used key will be, so just // go ahead and set it now. const prev = walker.prev del(self, walker) walker = prev } } } const del = (self, node) => { if (node) { const hit = node.value if (self[DISPOSE]) self[DISPOSE](hit.key, hit.value) self[LENGTH] -= hit.length self[CACHE].delete(hit.key) self[LRU_LIST].removeNode(node) } } class Entry { constructor (key, value, length, now, maxAge) { this.key = key this.value = value this.length = length this.now = now this.maxAge = maxAge || 0 } } const forEachStep = (self, fn, node, thisp) => { let hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) hit = undefined } if (hit) fn.call(thisp, hit.value, hit.key, self) } module.exports = LRUCache /***/ }), /***/ 47860: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const ANY = Symbol('SemVer ANY') // hoisted class for cyclic dependency class Comparator { static get ANY () { return ANY } constructor (comp, options) { options = parseOptions(options) if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } comp = comp.trim().split(/\s+/).join(' ') debug('comparator', comp, options) this.options = options this.loose = !!options.loose this.parse(comp) if (this.semver === ANY) { this.value = '' } else { this.value = this.operator + this.semver.version } debug('comp', this) } parse (comp) { const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] const m = comp.match(r) if (!m) { throw new TypeError(`Invalid comparator: ${comp}`) } this.operator = m[1] !== undefined ? m[1] : '' if (this.operator === '=') { this.operator = '' } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY } else { this.semver = new SemVer(m[2], this.options.loose) } } toString () { return this.value } test (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY || version === ANY) { return true } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } return cmp(version, this.operator, this.semver, this.options) } intersects (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (this.operator === '') { if (this.value === '') { return true } return new Range(comp.value, options).test(this.value) } else if (comp.operator === '') { if (comp.value === '') { return true } return new Range(this.value, options).test(comp.semver) } options = parseOptions(options) // Special cases where nothing can possibly be lower if (options.includePrerelease && (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { return false } if (!options.includePrerelease && (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { return false } // Same direction increasing (> or >=) if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { return true } // Same direction decreasing (< or <=) if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { return true } // same SemVer and both sides are inclusive (<= or >=) if ( (this.semver.version === comp.semver.version) && this.operator.includes('=') && comp.operator.includes('=')) { return true } // opposite directions less than if (cmp(this.semver, '<', comp.semver, options) && this.operator.startsWith('>') && comp.operator.startsWith('<')) { return true } // opposite directions greater than if (cmp(this.semver, '>', comp.semver, options) && this.operator.startsWith('<') && comp.operator.startsWith('>')) { return true } return false } } module.exports = Comparator const parseOptions = __webpack_require__(20321) const { safeRe: re, t } = __webpack_require__(54278) const cmp = __webpack_require__(27175) const debug = __webpack_require__(26467) const SemVer = __webpack_require__(24495) const Range = __webpack_require__(75481) /***/ }), /***/ 75481: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // hoisted class for cyclic dependency class Range { constructor (range, options) { options = parseOptions(options) if (range instanceof Range) { if ( range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease ) { return range } else { return new Range(range.raw, options) } } if (range instanceof Comparator) { // just put it in the set and return this.raw = range.value this.set = [[range]] this.format() return this } this.options = options this.loose = !!options.loose this.includePrerelease = !!options.includePrerelease // First reduce all whitespace as much as possible so we do not have to rely // on potentially slow regexes like \s*. This is then stored and used for // future error messages as well. this.raw = range .trim() .split(/\s+/) .join(' ') // First, split on || this.set = this.raw .split('||') // map the range to a 2d array of comparators .map(r => this.parseRange(r.trim())) // throw out any comparator lists that are empty // this generally means that it was not a valid range, which is allowed // in loose mode, but will still throw if the WHOLE range is invalid. .filter(c => c.length) if (!this.set.length) { throw new TypeError(`Invalid SemVer Range: ${this.raw}`) } // if we have any that are not the null set, throw out null sets. if (this.set.length > 1) { // keep the first one, in case they're all null sets const first = this.set[0] this.set = this.set.filter(c => !isNullSet(c[0])) if (this.set.length === 0) { this.set = [first] } else if (this.set.length > 1) { // if we have any that are *, then the range is just * for (const c of this.set) { if (c.length === 1 && isAny(c[0])) { this.set = [c] break } } } } this.format() } format () { this.range = this.set .map((comps) => comps.join(' ').trim()) .join('||') .trim() return this.range } toString () { return this.range } parseRange (range) { // memoize range parsing for performance. // this is a very hot path, and fully deterministic. const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE) const memoKey = memoOpts + ':' + range const cached = cache.get(memoKey) if (cached) { return cached } const loose = this.options.loose // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range) // `~ 1.2.3` => `~1.2.3` range = range.replace(re[t.TILDETRIM], tildeTrimReplace) debug('tilde trim', range) // `^ 1.2.3` => `^1.2.3` range = range.replace(re[t.CARETTRIM], caretTrimReplace) debug('caret trim', range) // At this point, the range is completely trimmed and // ready to be split into comparators. let rangeList = range .split(' ') .map(comp => parseComparator(comp, this.options)) .join(' ') .split(/\s+/) // >=0.0.0 is equivalent to * .map(comp => replaceGTE0(comp, this.options)) if (loose) { // in loose mode, throw out any that are not valid comparators rangeList = rangeList.filter(comp => { debug('loose invalid filter', comp, this.options) return !!comp.match(re[t.COMPARATORLOOSE]) }) } debug('range list', rangeList) // if any comparators are the null set, then replace with JUST null set // if more than one comparator, remove any * comparators // also, don't include the same comparator more than once const rangeMap = new Map() const comparators = rangeList.map(comp => new Comparator(comp, this.options)) for (const comp of comparators) { if (isNullSet(comp)) { return [comp] } rangeMap.set(comp.value, comp) } if (rangeMap.size > 1 && rangeMap.has('')) { rangeMap.delete('') } const result = [...rangeMap.values()] cache.set(memoKey, result) return result } intersects (range, options) { if (!(range instanceof Range)) { throw new TypeError('a Range is required') } return this.set.some((thisComparators) => { return ( isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => { return ( isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { return rangeComparators.every((rangeComparator) => { return thisComparator.intersects(rangeComparator, options) }) }) ) }) ) }) } // if ANY of the sets match ALL of its comparators, then pass test (version) { if (!version) { return false } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } for (let i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true } } return false } } module.exports = Range const LRU = __webpack_require__(17689) const cache = new LRU({ max: 1000 }) const parseOptions = __webpack_require__(20321) const Comparator = __webpack_require__(47860) const debug = __webpack_require__(26467) const SemVer = __webpack_require__(24495) const { safeRe: re, t, comparatorTrimReplace, tildeTrimReplace, caretTrimReplace, } = __webpack_require__(54278) const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __webpack_require__(64149) const isNullSet = c => c.value === '<0.0.0-0' const isAny = c => c.value === '' // take a set of comparators and determine whether there // exists a version which can satisfy it const isSatisfiable = (comparators, options) => { let result = true const remainingComparators = comparators.slice() let testComparator = remainingComparators.pop() while (result && remainingComparators.length) { result = remainingComparators.every((otherComparator) => { return testComparator.intersects(otherComparator, options) }) testComparator = remainingComparators.pop() } return result } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. const parseComparator = (comp, options) => { debug('comp', comp, options) comp = replaceCarets(comp, options) debug('caret', comp) comp = replaceTildes(comp, options) debug('tildes', comp) comp = replaceXRanges(comp, options) debug('xrange', comp) comp = replaceStars(comp, options) debug('stars', comp) return comp } const isX = id => !id || id.toLowerCase() === 'x' || id === '*' // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 // ~0.0.1 --> >=0.0.1 <0.1.0-0 const replaceTildes = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceTilde(c, options)) .join(' ') } const replaceTilde = (comp, options) => { const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] return comp.replace(r, (_, M, m, p, pr) => { debug('tilde', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0 <${+M + 1}.0.0-0` } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0-0 ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` } else if (pr) { debug('replaceTilde pr', pr) ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } else { // ~1.2.3 == >=1.2.3 <1.3.0-0 ret = `>=${M}.${m}.${p } <${M}.${+m + 1}.0-0` } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 // ^1.2.3 --> >=1.2.3 <2.0.0-0 // ^1.2.0 --> >=1.2.0 <2.0.0-0 // ^0.0.1 --> >=0.0.1 <0.0.2-0 // ^0.1.0 --> >=0.1.0 <0.2.0-0 const replaceCarets = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceCaret(c, options)) .join(' ') } const replaceCaret = (comp, options) => { debug('caret', comp, options) const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] const z = options.includePrerelease ? '-0' : '' return comp.replace(r, (_, M, m, p, pr) => { debug('caret', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` } else if (isX(p)) { if (M === '0') { ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` } else { ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p}-${pr } <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p}-${pr } <${+M + 1}.0.0-0` } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p }${z} <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p }${z} <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p } <${+M + 1}.0.0-0` } } debug('caret return', ret) return ret }) } const replaceXRanges = (comp, options) => { debug('replaceXRanges', comp, options) return comp .split(/\s+/) .map((c) => replaceXRange(c, options)) .join(' ') } const replaceXRange = (comp, options) => { comp = comp.trim() const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] return comp.replace(r, (ret, gtlt, M, m, p, pr) => { debug('xRange', comp, ret, gtlt, M, m, p, pr) const xM = isX(M) const xm = xM || isX(m) const xp = xm || isX(p) const anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } // if we're including prereleases in the match, then we need // to fix this to -0, the lowest possible prerelease value pr = options.includePrerelease ? '-0' : '' if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0-0' } else { // nothing is forbidden ret = '*' } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0 } p = 0 if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 gtlt = '>=' if (xm) { M = +M + 1 m = 0 p = 0 } else { m = +m + 1 p = 0 } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<' if (xm) { M = +M + 1 } else { m = +m + 1 } } if (gtlt === '<') { pr = '-0' } ret = `${gtlt + M}.${m}.${p}${pr}` } else if (xm) { ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` } else if (xp) { ret = `>=${M}.${m}.0${pr } <${M}.${+m + 1}.0-0` } debug('xRange return', ret) return ret }) } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. const replaceStars = (comp, options) => { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp .trim() .replace(re[t.STAR], '') } const replaceGTE0 = (comp, options) => { debug('replaceGTE0', comp, options) return comp .trim() .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') } // This function is passed to string.replace(re[t.HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 const hyphenReplace = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) => { if (isX(fM)) { from = '' } else if (isX(fm)) { from = `>=${fM}.0.0${incPr ? '-0' : ''}` } else if (isX(fp)) { from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` } else if (fpr) { from = `>=${from}` } else { from = `>=${from}${incPr ? '-0' : ''}` } if (isX(tM)) { to = '' } else if (isX(tm)) { to = `<${+tM + 1}.0.0-0` } else if (isX(tp)) { to = `<${tM}.${+tm + 1}.0-0` } else if (tpr) { to = `<=${tM}.${tm}.${tp}-${tpr}` } else if (incPr) { to = `<${tM}.${tm}.${+tp + 1}-0` } else { to = `<=${to}` } return `${from} ${to}`.trim() } const testSet = (set, version, options) => { for (let i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (let i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === Comparator.ANY) { continue } if (set[i].semver.prerelease.length > 0) { const allowed = set[i].semver if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } /***/ }), /***/ 24495: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const debug = __webpack_require__(26467) const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(64149) const { safeRe: re, t } = __webpack_require__(54278) const parseOptions = __webpack_require__(20321) const { compareIdentifiers } = __webpack_require__(73757) class SemVer { constructor (version, options) { options = parseOptions(options) if (version instanceof SemVer) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) } if (version.length > MAX_LENGTH) { throw new TypeError( `version is longer than ${MAX_LENGTH} characters` ) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose // this isn't actually relevant for versions, but keep it so that we // don't run into trouble passing this.options around. this.includePrerelease = !!options.includePrerelease const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) if (!m) { throw new TypeError(`Invalid Version: ${version}`) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map((id) => { if (/^[0-9]+$/.test(id)) { const num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } format () { this.version = `${this.major}.${this.minor}.${this.patch}` if (this.prerelease.length) { this.version += `-${this.prerelease.join('.')}` } return this.version } toString () { return this.version } compare (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { if (typeof other === 'string' && other === this.version) { return 0 } other = new SemVer(other, this.options) } if (other.version === this.version) { return 0 } return this.compareMain(other) || this.comparePre(other) } compareMain (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return ( compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) ) } comparePre (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } let i = 0 do { const a = this.prerelease[i] const b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } compareBuild (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } let i = 0 do { const a = this.build[i] const b = other.build[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc (release, identifier, identifierBase) { switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier, identifierBase) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier, identifierBase) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier, identifierBase) this.inc('pre', identifier, identifierBase) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier, identifierBase) } this.inc('pre', identifier, identifierBase) break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if ( this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0 ) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. case 'pre': { const base = Number(identifierBase) ? 1 : 0 if (!identifier && identifierBase === false) { throw new Error('invalid increment argument: identifier is empty') } if (this.prerelease.length === 0) { this.prerelease = [base] } else { let i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything if (identifier === this.prerelease.join('.') && identifierBase === false) { throw new Error('invalid increment argument: identifier already exists') } this.prerelease.push(base) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 let prerelease = [identifier, base] if (identifierBase === false) { prerelease = [identifier] } if (compareIdentifiers(this.prerelease[0], identifier) === 0) { if (isNaN(this.prerelease[1])) { this.prerelease = prerelease } } else { this.prerelease = prerelease } } break } default: throw new Error(`invalid increment argument: ${release}`) } this.raw = this.format() if (this.build.length) { this.raw += `+${this.build.join('.')}` } return this } } module.exports = SemVer /***/ }), /***/ 81953: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(98489) const clean = (version, options) => { const s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } module.exports = clean /***/ }), /***/ 27175: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const eq = __webpack_require__(57342) const neq = __webpack_require__(15882) const gt = __webpack_require__(79920) const gte = __webpack_require__(81571) const lt = __webpack_require__(4329) const lte = __webpack_require__(34436) const cmp = (a, op, b, loose) => { switch (op) { case '===': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a === b case '!==': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError(`Invalid operator: ${op}`) } } module.exports = cmp /***/ }), /***/ 22298: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(24495) const parse = __webpack_require__(98489) const { safeRe: re, t } = __webpack_require__(54278) const coerce = (version, options) => { if (version instanceof SemVer) { return version } if (typeof version === 'number') { version = String(version) } if (typeof version !== 'string') { return null } options = options || {} let match = null if (!options.rtl) { match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]) } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4' // // Walk through the string checking with a /g regexp // Manually set the index so as to pick up overlapping matches. // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL] let next while ((next = coerceRtlRegex.exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next } coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length } // leave it in a clean state coerceRtlRegex.lastIndex = -1 } if (match === null) { return null } const major = match[2] const minor = match[3] || '0' const patch = match[4] || '0' const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '' const build = options.includePrerelease && match[6] ? `+${match[6]}` : '' return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options) } module.exports = coerce /***/ }), /***/ 49971: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(24495) const compareBuild = (a, b, loose) => { const versionA = new SemVer(a, loose) const versionB = new SemVer(b, loose) return versionA.compare(versionB) || versionA.compareBuild(versionB) } module.exports = compareBuild /***/ }), /***/ 19153: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(69902) const compareLoose = (a, b) => compare(a, b, true) module.exports = compareLoose /***/ }), /***/ 69902: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(24495) const compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)) module.exports = compare /***/ }), /***/ 12999: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(98489) const diff = (version1, version2) => { const v1 = parse(version1, null, true) const v2 = parse(version2, null, true) const comparison = v1.compare(v2) if (comparison === 0) { return null } const v1Higher = comparison > 0 const highVersion = v1Higher ? v1 : v2 const lowVersion = v1Higher ? v2 : v1 const highHasPre = !!highVersion.prerelease.length const lowHasPre = !!lowVersion.prerelease.length if (lowHasPre && !highHasPre) { // Going from prerelease -> no prerelease requires some special casing // If the low version has only a major, then it will always be a major // Some examples: // 1.0.0-1 -> 1.0.0 // 1.0.0-1 -> 1.1.1 // 1.0.0-1 -> 2.0.0 if (!lowVersion.patch && !lowVersion.minor) { return 'major' } // Otherwise it can be determined by checking the high version if (highVersion.patch) { // anything higher than a patch bump would result in the wrong version return 'patch' } if (highVersion.minor) { // anything higher than a minor bump would result in the wrong version return 'minor' } // bumping major/minor/patch all have same result return 'major' } // add the `pre` prefix if we are going to a prerelease version const prefix = highHasPre ? 'pre' : '' if (v1.major !== v2.major) { return prefix + 'major' } if (v1.minor !== v2.minor) { return prefix + 'minor' } if (v1.patch !== v2.patch) { return prefix + 'patch' } // high and low are preleases return 'prerelease' } module.exports = diff /***/ }), /***/ 57342: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(69902) const eq = (a, b, loose) => compare(a, b, loose) === 0 module.exports = eq /***/ }), /***/ 79920: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(69902) const gt = (a, b, loose) => compare(a, b, loose) > 0 module.exports = gt /***/ }), /***/ 81571: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(69902) const gte = (a, b, loose) => compare(a, b, loose) >= 0 module.exports = gte /***/ }), /***/ 40248: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(24495) const inc = (version, release, options, identifier, identifierBase) => { if (typeof (options) === 'string') { identifierBase = identifier identifier = options options = undefined } try { return new SemVer( version instanceof SemVer ? version.version : version, options ).inc(release, identifier, identifierBase).version } catch (er) { return null } } module.exports = inc /***/ }), /***/ 4329: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(69902) const lt = (a, b, loose) => compare(a, b, loose) < 0 module.exports = lt /***/ }), /***/ 34436: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(69902) const lte = (a, b, loose) => compare(a, b, loose) <= 0 module.exports = lte /***/ }), /***/ 50158: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(24495) const major = (a, loose) => new SemVer(a, loose).major module.exports = major /***/ }), /***/ 7811: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(24495) const minor = (a, loose) => new SemVer(a, loose).minor module.exports = minor /***/ }), /***/ 15882: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(69902) const neq = (a, b, loose) => compare(a, b, loose) !== 0 module.exports = neq /***/ }), /***/ 98489: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(24495) const parse = (version, options, throwErrors = false) => { if (version instanceof SemVer) { return version } try { return new SemVer(version, options) } catch (er) { if (!throwErrors) { return null } throw er } } module.exports = parse /***/ }), /***/ 11313: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(24495) const patch = (a, loose) => new SemVer(a, loose).patch module.exports = patch /***/ }), /***/ 54811: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(98489) const prerelease = (version, options) => { const parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } module.exports = prerelease /***/ }), /***/ 22066: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(69902) const rcompare = (a, b, loose) => compare(b, a, loose) module.exports = rcompare /***/ }), /***/ 97830: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(49971) const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) module.exports = rsort /***/ }), /***/ 2851: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(75481) const satisfies = (version, range, options) => { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } module.exports = satisfies /***/ }), /***/ 26350: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(49971) const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) module.exports = sort /***/ }), /***/ 5113: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(98489) const valid = (version, options) => { const v = parse(version, options) return v ? v.version : null } module.exports = valid /***/ }), /***/ 50460: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // just pre-load all the stuff that index.js lazily exports const internalRe = __webpack_require__(54278) const constants = __webpack_require__(64149) const SemVer = __webpack_require__(24495) const identifiers = __webpack_require__(73757) const parse = __webpack_require__(98489) const valid = __webpack_require__(5113) const clean = __webpack_require__(81953) const inc = __webpack_require__(40248) const diff = __webpack_require__(12999) const major = __webpack_require__(50158) const minor = __webpack_require__(7811) const patch = __webpack_require__(11313) const prerelease = __webpack_require__(54811) const compare = __webpack_require__(69902) const rcompare = __webpack_require__(22066) const compareLoose = __webpack_require__(19153) const compareBuild = __webpack_require__(49971) const sort = __webpack_require__(26350) const rsort = __webpack_require__(97830) const gt = __webpack_require__(79920) const lt = __webpack_require__(4329) const eq = __webpack_require__(57342) const neq = __webpack_require__(15882) const gte = __webpack_require__(81571) const lte = __webpack_require__(34436) const cmp = __webpack_require__(27175) const coerce = __webpack_require__(22298) const Comparator = __webpack_require__(47860) const Range = __webpack_require__(75481) const satisfies = __webpack_require__(2851) const toComparators = __webpack_require__(1010) const maxSatisfying = __webpack_require__(41296) const minSatisfying = __webpack_require__(67476) const minVersion = __webpack_require__(63253) const validRange = __webpack_require__(95826) const outside = __webpack_require__(37139) const gtr = __webpack_require__(76352) const ltr = __webpack_require__(93370) const intersects = __webpack_require__(55668) const simplifyRange = __webpack_require__(97708) const subset = __webpack_require__(55155) module.exports = { parse, valid, clean, inc, diff, major, minor, patch, prerelease, compare, rcompare, compareLoose, compareBuild, sort, rsort, gt, lt, eq, neq, gte, lte, cmp, coerce, Comparator, Range, satisfies, toComparators, maxSatisfying, minSatisfying, minVersion, validRange, outside, gtr, ltr, intersects, simplifyRange, subset, SemVer, re: internalRe.re, src: internalRe.src, tokens: internalRe.t, SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, RELEASE_TYPES: constants.RELEASE_TYPES, compareIdentifiers: identifiers.compareIdentifiers, rcompareIdentifiers: identifiers.rcompareIdentifiers, } /***/ }), /***/ 64149: /***/ ((module) => { // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. const SEMVER_SPEC_VERSION = '2.0.0' const MAX_LENGTH = 256 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. const MAX_SAFE_COMPONENT_LENGTH = 16 // Max safe length for a build identifier. The max length minus 6 characters for // the shortest version with a build 0.0.0+BUILD. const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 const RELEASE_TYPES = [ 'major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease', ] module.exports = { MAX_LENGTH, MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_SAFE_INTEGER, RELEASE_TYPES, SEMVER_SPEC_VERSION, FLAG_INCLUDE_PRERELEASE: 0b001, FLAG_LOOSE: 0b010, } /***/ }), /***/ 26467: /***/ ((module) => { const debug = ( typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ) ? (...args) => console.error('SEMVER', ...args) : () => {} module.exports = debug /***/ }), /***/ 73757: /***/ ((module) => { const numeric = /^[0-9]+$/ const compareIdentifiers = (a, b) => { const anum = numeric.test(a) const bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) module.exports = { compareIdentifiers, rcompareIdentifiers, } /***/ }), /***/ 20321: /***/ ((module) => { // parse out just the options we care about const looseOption = Object.freeze({ loose: true }) const emptyOpts = Object.freeze({ }) const parseOptions = options => { if (!options) { return emptyOpts } if (typeof options !== 'object') { return looseOption } return options } module.exports = parseOptions /***/ }), /***/ 54278: /***/ ((module, exports, __webpack_require__) => { const { MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_LENGTH, } = __webpack_require__(64149) const debug = __webpack_require__(26467) exports = module.exports = {} // The actual regexps go on exports.re const re = exports.re = [] const safeRe = exports.safeRe = [] const src = exports.src = [] const t = exports.t = {} let R = 0 const LETTERDASHNUMBER = '[a-zA-Z0-9-]' // Replace some greedy regex tokens to prevent regex dos issues. These regex are // used internally via the safeRe object since all inputs in this library get // normalized first to trim and collapse all extra whitespace. The original // regexes are exported for userland consumption and lower level usage. A // future breaking change could export the safer regex only with a note that // all input should have extra whitespace removed. const safeRegexReplacements = [ ['\\s', 1], ['\\d', MAX_LENGTH], [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], ] const makeSafeRegex = (value) => { for (const [token, max] of safeRegexReplacements) { value = value .split(`${token}*`).join(`${token}{0,${max}}`) .split(`${token}+`).join(`${token}{1,${max}}`) } return value } const createToken = (name, value, isGlobal) => { const safe = makeSafeRegex(value) const index = R++ debug(name, index, value) t[name] = index src[index] = value re[index] = new RegExp(value, isGlobal ? 'g' : undefined) safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) } // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') createToken('NUMERICIDENTIFIERLOOSE', '\\d+') // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) // ## Main Version // Three dot-separated numeric identifiers. createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`) createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] }|${src[t.NONNUMERICIDENTIFIER]})`) createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] }|${src[t.NONNUMERICIDENTIFIER]})`) // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] }(?:\\.${src[t.BUILDIDENTIFIER]})*))`) // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. createToken('FULLPLAIN', `v?${src[t.MAINVERSION] }${src[t.PRERELEASE]}?${ src[t.BUILD]}?`) createToken('FULL', `^${src[t.FULLPLAIN]}$`) // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] }${src[t.PRERELEASELOOSE]}?${ src[t.BUILD]}?`) createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) createToken('GTLT', '((?:<|>)?=?)') // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) // Coercion. // Extract anything that could conceivably be a part of a valid semver createToken('COERCEPLAIN', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`) createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`) createToken('COERCEFULL', src[t.COERCEPLAIN] + `(?:${src[t.PRERELEASE]})?` + `(?:${src[t.BUILD]})?` + `(?:$|[^\\d])`) createToken('COERCERTL', src[t.COERCE], true) createToken('COERCERTLFULL', src[t.COERCEFULL], true) // Tilde ranges. // Meaning is "reasonably at or greater than" createToken('LONETILDE', '(?:~>?)') createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) exports.tildeTrimReplace = '$1~' createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) // Caret ranges. // Meaning is "at least and backwards compatible with" createToken('LONECARET', '(?:\\^)') createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) exports.caretTrimReplace = '$1^' createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) // A simple gt/lt/eq thing, or just "" to indicate "any version" createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) exports.comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`) createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`) // Star ranges basically just allow anything at all. createToken('STAR', '(<|>)?=?\\s*\\*') // >=0.0.0 is like a star createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') /***/ }), /***/ 76352: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Determine if version is greater than all the versions possible in the range. const outside = __webpack_require__(37139) const gtr = (version, range, options) => outside(version, range, '>', options) module.exports = gtr /***/ }), /***/ 55668: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(75481) const intersects = (r1, r2, options) => { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2, options) } module.exports = intersects /***/ }), /***/ 93370: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const outside = __webpack_require__(37139) // Determine if version is less than all the versions possible in the range const ltr = (version, range, options) => outside(version, range, '<', options) module.exports = ltr /***/ }), /***/ 41296: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(24495) const Range = __webpack_require__(75481) const maxSatisfying = (versions, range, options) => { let max = null let maxSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } module.exports = maxSatisfying /***/ }), /***/ 67476: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(24495) const Range = __webpack_require__(75481) const minSatisfying = (versions, range, options) => { let min = null let minSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } module.exports = minSatisfying /***/ }), /***/ 63253: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(24495) const Range = __webpack_require__(75481) const gt = __webpack_require__(79920) const minVersion = (range, loose) => { range = new Range(range, loose) let minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let setMin = null comparators.forEach((comparator) => { // Clone to avoid manipulating the comparator's semver object. const compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!setMin || gt(compver, setMin)) { setMin = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error(`Unexpected operation: ${comparator.operator}`) } }) if (setMin && (!minver || gt(minver, setMin))) { minver = setMin } } if (minver && range.test(minver)) { return minver } return null } module.exports = minVersion /***/ }), /***/ 37139: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(24495) const Comparator = __webpack_require__(47860) const { ANY } = Comparator const Range = __webpack_require__(75481) const satisfies = __webpack_require__(2851) const gt = __webpack_require__(79920) const lt = __webpack_require__(4329) const lte = __webpack_require__(34436) const gte = __webpack_require__(81571) const outside = (version, range, hilo, options) => { version = new SemVer(version, options) range = new Range(range, options) let gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisfies the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let high = null let low = null comparators.forEach((comparator) => { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } module.exports = outside /***/ }), /***/ 97708: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // given a set of versions and a range, create a "simplified" range // that includes the same versions that the original range does // If the original range is shorter than the simplified one, return that. const satisfies = __webpack_require__(2851) const compare = __webpack_require__(69902) module.exports = (versions, range, options) => { const set = [] let first = null let prev = null const v = versions.sort((a, b) => compare(a, b, options)) for (const version of v) { const included = satisfies(version, range, options) if (included) { prev = version if (!first) { first = version } } else { if (prev) { set.push([first, prev]) } prev = null first = null } } if (first) { set.push([first, null]) } const ranges = [] for (const [min, max] of set) { if (min === max) { ranges.push(min) } else if (!max && min === v[0]) { ranges.push('*') } else if (!max) { ranges.push(`>=${min}`) } else if (min === v[0]) { ranges.push(`<=${max}`) } else { ranges.push(`${min} - ${max}`) } } const simplified = ranges.join(' || ') const original = typeof range.raw === 'string' ? range.raw : String(range) return simplified.length < original.length ? simplified : range } /***/ }), /***/ 55155: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(75481) const Comparator = __webpack_require__(47860) const { ANY } = Comparator const satisfies = __webpack_require__(2851) const compare = __webpack_require__(69902) // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: // - Every simple range `r1, r2, ...` is a null set, OR // - Every simple range `r1, r2, ...` which is not a null set is a subset of // some `R1, R2, ...` // // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: // - If c is only the ANY comparator // - If C is only the ANY comparator, return true // - Else if in prerelease mode, return false // - else replace c with `[>=0.0.0]` // - If C is only the ANY comparator // - if in prerelease mode, return true // - else replace C with `[>=0.0.0]` // - Let EQ be the set of = comparators in c // - If EQ is more than one, return true (null set) // - Let GT be the highest > or >= comparator in c // - Let LT be the lowest < or <= comparator in c // - If GT and LT, and GT.semver > LT.semver, return true (null set) // - If any C is a = range, and GT or LT are set, return false // - If EQ // - If GT, and EQ does not satisfy GT, return true (null set) // - If LT, and EQ does not satisfy LT, return true (null set) // - If EQ satisfies every C, return true // - Else return false // - If GT // - If GT.semver is lower than any > or >= comp in C, return false // - If GT is >=, and GT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the GT.semver tuple, return false // - If LT // - If LT.semver is greater than any < or <= comp in C, return false // - If LT is <=, and LT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the LT.semver tuple, return false // - Else return true const subset = (sub, dom, options = {}) => { if (sub === dom) { return true } sub = new Range(sub, options) dom = new Range(dom, options) let sawNonNull = false OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { const isSub = simpleSubset(simpleSub, simpleDom, options) sawNonNull = sawNonNull || isSub !== null if (isSub) { continue OUTER } } // the null set is a subset of everything, but null simple ranges in // a complex range should be ignored. so if we saw a non-null range, // then we know this isn't a subset, but if EVERY simple range was null, // then it is a subset. if (sawNonNull) { return false } } return true } const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] const minimumVersion = [new Comparator('>=0.0.0')] const simpleSubset = (sub, dom, options) => { if (sub === dom) { return true } if (sub.length === 1 && sub[0].semver === ANY) { if (dom.length === 1 && dom[0].semver === ANY) { return true } else if (options.includePrerelease) { sub = minimumVersionWithPreRelease } else { sub = minimumVersion } } if (dom.length === 1 && dom[0].semver === ANY) { if (options.includePrerelease) { return true } else { dom = minimumVersion } } const eqSet = new Set() let gt, lt for (const c of sub) { if (c.operator === '>' || c.operator === '>=') { gt = higherGT(gt, c, options) } else if (c.operator === '<' || c.operator === '<=') { lt = lowerLT(lt, c, options) } else { eqSet.add(c.semver) } } if (eqSet.size > 1) { return null } let gtltComp if (gt && lt) { gtltComp = compare(gt.semver, lt.semver, options) if (gtltComp > 0) { return null } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { return null } } // will iterate one or zero times for (const eq of eqSet) { if (gt && !satisfies(eq, String(gt), options)) { return null } if (lt && !satisfies(eq, String(lt), options)) { return null } for (const c of dom) { if (!satisfies(eq, String(c), options)) { return false } } return true } let higher, lower let hasDomLT, hasDomGT // if the subset has a prerelease, we need a comparator in the superset // with the same tuple and a prerelease, or it's not a subset let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false // exception: <1.2.3-0 is the same as <1.2.3 if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { needDomLTPre = false } for (const c of dom) { hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' if (gt) { if (needDomGTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { needDomGTPre = false } } if (c.operator === '>' || c.operator === '>=') { higher = higherGT(gt, c, options) if (higher === c && higher !== gt) { return false } } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { return false } } if (lt) { if (needDomLTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { needDomLTPre = false } } if (c.operator === '<' || c.operator === '<=') { lower = lowerLT(lt, c, options) if (lower === c && lower !== lt) { return false } } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { return false } } if (!c.operator && (lt || gt) && gtltComp !== 0) { return false } } // if there was a < or >, and nothing in the dom, then must be false // UNLESS it was limited by another range in the other direction. // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 if (gt && hasDomLT && !lt && gtltComp !== 0) { return false } if (lt && hasDomGT && !gt && gtltComp !== 0) { return false } // we needed a prerelease range in a specific tuple, but didn't get one // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, // because it includes prereleases in the 1.2.3 tuple if (needDomGTPre || needDomLTPre) { return false } return true } // >=1.2.3 is lower than >1.2.3 const higherGT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp > 0 ? a : comp < 0 ? b : b.operator === '>' && a.operator === '>=' ? b : a } // <=1.2.3 is higher than <1.2.3 const lowerLT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp < 0 ? a : comp > 0 ? b : b.operator === '<' && a.operator === '<=' ? b : a } module.exports = subset /***/ }), /***/ 1010: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(75481) // Mostly just for testing and legacy API reasons const toComparators = (range, options) => new Range(range, options).set .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) module.exports = toComparators /***/ }), /***/ 95826: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(75481) const validRange = (range, options) => { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } module.exports = validRange /***/ }), /***/ 68323: /***/ ((module) => { "use strict"; module.exports = function (Yallist) { Yallist.prototype[Symbol.iterator] = function* () { for (let walker = this.head; walker; walker = walker.next) { yield walker.value } } } /***/ }), /***/ 5436: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = Yallist Yallist.Node = Node Yallist.create = Yallist function Yallist (list) { var self = this if (!(self instanceof Yallist)) { self = new Yallist() } self.tail = null self.head = null self.length = 0 if (list && typeof list.forEach === 'function') { list.forEach(function (item) { self.push(item) }) } else if (arguments.length > 0) { for (var i = 0, l = arguments.length; i < l; i++) { self.push(arguments[i]) } } return self } Yallist.prototype.removeNode = function (node) { if (node.list !== this) { throw new Error('removing node which does not belong to this list') } var next = node.next var prev = node.prev if (next) { next.prev = prev } if (prev) { prev.next = next } if (node === this.head) { this.head = next } if (node === this.tail) { this.tail = prev } node.list.length-- node.next = null node.prev = null node.list = null return next } Yallist.prototype.unshiftNode = function (node) { if (node === this.head) { return } if (node.list) { node.list.removeNode(node) } var head = this.head node.list = this node.next = head if (head) { head.prev = node } this.head = node if (!this.tail) { this.tail = node } this.length++ } Yallist.prototype.pushNode = function (node) { if (node === this.tail) { return } if (node.list) { node.list.removeNode(node) } var tail = this.tail node.list = this node.prev = tail if (tail) { tail.next = node } this.tail = node if (!this.head) { this.head = node } this.length++ } Yallist.prototype.push = function () { for (var i = 0, l = arguments.length; i < l; i++) { push(this, arguments[i]) } return this.length } Yallist.prototype.unshift = function () { for (var i = 0, l = arguments.length; i < l; i++) { unshift(this, arguments[i]) } return this.length } Yallist.prototype.pop = function () { if (!this.tail) { return undefined } var res = this.tail.value this.tail = this.tail.prev if (this.tail) { this.tail.next = null } else { this.head = null } this.length-- return res } Yallist.prototype.shift = function () { if (!this.head) { return undefined } var res = this.head.value this.head = this.head.next if (this.head) { this.head.prev = null } else { this.tail = null } this.length-- return res } Yallist.prototype.forEach = function (fn, thisp) { thisp = thisp || this for (var walker = this.head, i = 0; walker !== null; i++) { fn.call(thisp, walker.value, i, this) walker = walker.next } } Yallist.prototype.forEachReverse = function (fn, thisp) { thisp = thisp || this for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { fn.call(thisp, walker.value, i, this) walker = walker.prev } } Yallist.prototype.get = function (n) { for (var i = 0, walker = this.head; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.next } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.getReverse = function (n) { for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.prev } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.map = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.head; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.next } return res } Yallist.prototype.mapReverse = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.tail; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.prev } return res } Yallist.prototype.reduce = function (fn, initial) { var acc var walker = this.head if (arguments.length > 1) { acc = initial } else if (this.head) { walker = this.head.next acc = this.head.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = 0; walker !== null; i++) { acc = fn(acc, walker.value, i) walker = walker.next } return acc } Yallist.prototype.reduceReverse = function (fn, initial) { var acc var walker = this.tail if (arguments.length > 1) { acc = initial } else if (this.tail) { walker = this.tail.prev acc = this.tail.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = this.length - 1; walker !== null; i--) { acc = fn(acc, walker.value, i) walker = walker.prev } return acc } Yallist.prototype.toArray = function () { var arr = new Array(this.length) for (var i = 0, walker = this.head; walker !== null; i++) { arr[i] = walker.value walker = walker.next } return arr } Yallist.prototype.toArrayReverse = function () { var arr = new Array(this.length) for (var i = 0, walker = this.tail; walker !== null; i++) { arr[i] = walker.value walker = walker.prev } return arr } Yallist.prototype.slice = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = 0, walker = this.head; walker !== null && i < from; i++) { walker = walker.next } for (; walker !== null && i < to; i++, walker = walker.next) { ret.push(walker.value) } return ret } Yallist.prototype.sliceReverse = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { walker = walker.prev } for (; walker !== null && i > from; i--, walker = walker.prev) { ret.push(walker.value) } return ret } Yallist.prototype.splice = function (start, deleteCount, ...nodes) { if (start > this.length) { start = this.length - 1 } if (start < 0) { start = this.length + start; } for (var i = 0, walker = this.head; walker !== null && i < start; i++) { walker = walker.next } var ret = [] for (var i = 0; walker && i < deleteCount; i++) { ret.push(walker.value) walker = this.removeNode(walker) } if (walker === null) { walker = this.tail } if (walker !== this.head && walker !== this.tail) { walker = walker.prev } for (var i = 0; i < nodes.length; i++) { walker = insert(this, walker, nodes[i]) } return ret; } Yallist.prototype.reverse = function () { var head = this.head var tail = this.tail for (var walker = head; walker !== null; walker = walker.prev) { var p = walker.prev walker.prev = walker.next walker.next = p } this.head = tail this.tail = head return this } function insert (self, node, value) { var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self) if (inserted.next === null) { self.tail = inserted } if (inserted.prev === null) { self.head = inserted } self.length++ return inserted } function push (self, item) { self.tail = new Node(item, self.tail, null, self) if (!self.head) { self.head = self.tail } self.length++ } function unshift (self, item) { self.head = new Node(item, null, self.head, self) if (!self.tail) { self.tail = self.head } self.length++ } function Node (value, prev, next, list) { if (!(this instanceof Node)) { return new Node(value, prev, next, list) } this.list = list this.value = value if (prev) { prev.next = this this.prev = prev } else { this.prev = null } if (next) { next.prev = this this.next = next } else { this.next = null } } try { // add if support for Symbol.iterator is present __webpack_require__(68323)(Yallist) } catch (er) {} /***/ }), /***/ 35786: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CustomError = void 0; exports.MissingTargetFileError = MissingTargetFileError; exports.NoSupportedManifestsFoundError = NoSupportedManifestsFoundError; class CustomError extends Error { constructor(message) { super(message); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.code = undefined; this.strCode = undefined; this.innerError = undefined; this.userMessage = undefined; } } exports.CustomError = CustomError; function MissingTargetFileError(path) { const errorMsg = `Not a recognised option did you mean --file=${path}? ` + 'Check other options by running snyk --help'; const error = new CustomError(errorMsg); error.code = 422; error.userMessage = errorMsg; return error; } function NoSupportedManifestsFoundError(atLocations) { const locationsStr = atLocations.join(', '); const errorMsg = 'Could not detect supported target files in ' + locationsStr + '.\nPlease see our documentation for supported languages and ' + 'target files: https://snyk.co/udVgQ' + ' and make sure you are in the right directory.'; const error = new CustomError(errorMsg); error.code = 422; error.userMessage = errorMsg; return error; } //# sourceMappingURL=errors.js.map /***/ }), /***/ 12608: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.processYarnWorkspaces = exports.processPnpmWorkspaces = exports.processNpmWorkspaces = exports.inspect = void 0; const inspect_1 = __webpack_require__(16095); Object.defineProperty(exports, "inspect", ({ enumerable: true, get: function () { return inspect_1.inspect; } })); const workspaces_1 = __webpack_require__(51957); Object.defineProperty(exports, "processNpmWorkspaces", ({ enumerable: true, get: function () { return workspaces_1.processNpmWorkspaces; } })); Object.defineProperty(exports, "processPnpmWorkspaces", ({ enumerable: true, get: function () { return workspaces_1.processPnpmWorkspaces; } })); Object.defineProperty(exports, "processYarnWorkspaces", ({ enumerable: true, get: function () { return workspaces_1.processYarnWorkspaces; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 16095: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.inspect = inspect; const modulesParser = __webpack_require__(32016); const lockParser = __webpack_require__(96663); const errors_1 = __webpack_require__(35786); const utils_1 = __webpack_require__(12992); async function inspect(root, targetFile, options = {}) { if (!targetFile) { throw (0, errors_1.MissingTargetFileError)(root); } const isLockFileBased = targetFile.endsWith('package-lock.json') || targetFile.endsWith('yarn.lock') || targetFile.endsWith('pnpm-lock.yaml'); const getLockFileDeps = isLockFileBased && !options.traverseNodeModules; const depRes = getLockFileDeps ? await lockParser.parse(root, targetFile, options) : await modulesParser.parse(root, targetFile, options); let scannedProjects = []; if ((0, utils_1.isResDepGraph)(depRes)) { scannedProjects = [{ depGraph: depRes }]; } else { scannedProjects = [{ depTree: depRes }]; } return { plugin: { name: 'snyk-nodejs-lockfile-parser', runtime: process.version, }, scannedProjects, }; } //# sourceMappingURL=inspect.js.map /***/ }), /***/ 6700: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildDepGraph = buildDepGraph; const path = __webpack_require__(71017); const fs = __webpack_require__(57147); const lockFileParser = __webpack_require__(79790); const snyk_nodejs_lockfile_parser_1 = __webpack_require__(79790); async function buildDepGraph(root, manifestFilePath, lockfilePath, lockfileVersion, options) { const manifestFileFullPath = path.resolve(root, manifestFilePath); const lockFileFullPath = path.resolve(root, lockfilePath); if (!fs.existsSync(manifestFileFullPath)) { throw new snyk_nodejs_lockfile_parser_1.InvalidUserInputError('Target file package.json not found at ' + `location: ${manifestFileFullPath}`); } if (!fs.existsSync(lockFileFullPath)) { throw new snyk_nodejs_lockfile_parser_1.InvalidUserInputError('Lockfile not found at location: ' + lockFileFullPath); } const manifestFileContents = fs.readFileSync(manifestFileFullPath, 'utf-8'); const lockFileContents = fs.readFileSync(lockFileFullPath, 'utf-8'); const workspaceRootPath = path.parse(lockFileFullPath).dir; const workspaceFileFullPath = path.resolve(workspaceRootPath, 'pnpm-workspace.yaml'); switch (lockfileVersion) { case snyk_nodejs_lockfile_parser_1.NodeLockfileVersion.PnpmLockV5: case snyk_nodejs_lockfile_parser_1.NodeLockfileVersion.PnpmLockV6: case snyk_nodejs_lockfile_parser_1.NodeLockfileVersion.PnpmLockV9: if (fs.existsSync(workspaceFileFullPath)) { throw new snyk_nodejs_lockfile_parser_1.InvalidUserInputError('Both `pnpm-lock.yaml` and `pnpm-workspace.yaml` were found in ' + workspaceRootPath + '.\n' + 'Please run your command again specifying `--all-projects` flag.'); } return await lockFileParser.parsePnpmProject(manifestFileContents, lockFileContents, { includeDevDeps: options.includeDevDeps, includeOptionalDeps: options.includeOptionalDeps || true, includePeerDeps: true, pruneWithinTopLevelDeps: true, strictOutOfSync: options.strictOutOfSync, }, lockfileVersion); case snyk_nodejs_lockfile_parser_1.NodeLockfileVersion.YarnLockV1: return await lockFileParser.parseYarnLockV1Project(manifestFileContents, lockFileContents, { includeDevDeps: options.includeDevDeps, includeOptionalDeps: options.includeOptionalDeps, includePeerDeps: options.includePeerDeps || false, pruneLevel: 'withinTopLevelDeps', strictOutOfSync: options.strictOutOfSync, }); case snyk_nodejs_lockfile_parser_1.NodeLockfileVersion.YarnLockV2: return await lockFileParser.parseYarnLockV2Project(manifestFileContents, lockFileContents, { includeDevDeps: options.includeDevDeps, includeOptionalDeps: options.includeOptionalDeps, pruneWithinTopLevelDeps: true, strictOutOfSync: options.strictOutOfSync, }); case snyk_nodejs_lockfile_parser_1.NodeLockfileVersion.NpmLockV2: case snyk_nodejs_lockfile_parser_1.NodeLockfileVersion.NpmLockV3: return await lockFileParser.parseNpmLockV2Project(manifestFileContents, lockFileContents, options); default: throw new Error('Failed to build dep graph from current project'); } } //# sourceMappingURL=build-dep-graph.js.map /***/ }), /***/ 96663: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parse = parse; const path = __webpack_require__(71017); const fs = __webpack_require__(57147); const build_dep_graph_1 = __webpack_require__(6700); const lockFileParser = __webpack_require__(79790); const snyk_nodejs_lockfile_parser_1 = __webpack_require__(79790); async function parse(root, targetFile, options) { const lockFileFullPath = path.resolve(root, targetFile); if (!fs.existsSync(lockFileFullPath)) { throw new Error('Lockfile ' + targetFile + ' not found at location: ' + lockFileFullPath); } const fullPath = path.parse(lockFileFullPath); const manifestFileFullPath = path.resolve(fullPath.dir, 'package.json'); const shrinkwrapFullPath = path.resolve(fullPath.dir, 'npm-shrinkwrap.json'); if (!fs.existsSync(manifestFileFullPath)) { throw new Error(`Could not find package.json at ${manifestFileFullPath} ` + `(lockfile found at ${targetFile})`); } if (fs.existsSync(shrinkwrapFullPath)) { throw new Error('Both `npm-shrinkwrap.json` and `package-lock.json` were found in ' + fullPath.dir + '.\n' + 'Please run your command again specifying `--file=package.json` flag.'); } const strictOutOfSync = options.strictOutOfSync !== false; const lockfileVersion = lockFileParser.getLockfileVersionFromFile(lockFileFullPath); if (lockfileVersion === snyk_nodejs_lockfile_parser_1.NodeLockfileVersion.YarnLockV1 || lockfileVersion === snyk_nodejs_lockfile_parser_1.NodeLockfileVersion.YarnLockV2 || lockfileVersion === snyk_nodejs_lockfile_parser_1.NodeLockfileVersion.NpmLockV2 || lockfileVersion === snyk_nodejs_lockfile_parser_1.NodeLockfileVersion.NpmLockV3 || lockfileVersion === snyk_nodejs_lockfile_parser_1.NodeLockfileVersion.PnpmLockV5 || lockfileVersion === snyk_nodejs_lockfile_parser_1.NodeLockfileVersion.PnpmLockV6 || lockfileVersion === snyk_nodejs_lockfile_parser_1.NodeLockfileVersion.PnpmLockV9) { return await (0, build_dep_graph_1.buildDepGraph)(root, manifestFileFullPath, lockFileFullPath, lockfileVersion, { includeDevDeps: options.dev || false, includeOptionalDeps: true, strictOutOfSync, pruneCycles: true, }); } return lockFileParser.buildDepTreeFromFiles(root, manifestFileFullPath, lockFileFullPath, options.dev, strictOutOfSync); } //# sourceMappingURL=index.js.map /***/ }), /***/ 32016: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parse = parse; const path = __webpack_require__(71017); const fs = __webpack_require__(57147); const resolveNodeDeps = __webpack_require__(40068); const baseDebug = __webpack_require__(15158); const lodash_1 = __webpack_require__(96486); const utils_1 = __webpack_require__(12992); const debug = baseDebug('snyk-nodejs-plugin'); async function parse(root, targetFile, options) { if (targetFile.endsWith('yarn.lock')) { options.file = options.file && options.file.replace('yarn.lock', 'package.json'); } if (targetFile.endsWith('pnpm-lock.yaml')) { options.file = options.file && options.file.replace('pnpm-lock.yaml', 'package.json'); } // package-lock.json falls back to package.json (used in wizard code) if (targetFile.endsWith('package-lock.json')) { options.file = options.file && options.file.replace('package-lock.json', 'package.json'); } // check if there any dependencies const packageJsonFileName = path.resolve(root, options.file); const packageManager = options.packageManager || 'npm'; try { const packageJson = JSON.parse((0, utils_1.getFileContents)(root, packageJsonFileName).content); let dependencies = packageJson.dependencies; if (options.dev) { dependencies = { ...dependencies, ...packageJson.devDependencies }; } if ((0, lodash_1.isEmpty)(dependencies)) { return new Promise((resolve) => resolve({ name: packageJson.name || 'package.json', dependencies: {}, version: packageJson.version, })); } } catch (e) { debug(`Failed to read ${packageJsonFileName}: Error: ${e}`); throw new Error(`Failed to read ${packageJsonFileName}. Error: ${e.message}`); } const nodeModulesPath = path.join(path.dirname(path.resolve(root, targetFile)), 'node_modules'); if (!fs.existsSync(nodeModulesPath)) { // throw a custom error throw new Error("Missing node_modules folder: we can't test " + `without dependencies.\nPlease run '${packageManager} install' first.`); } return resolveNodeDeps(root, Object.assign({}, options, { noFromArrays: true })); } //# sourceMappingURL=npm-modules-parser.js.map /***/ }), /***/ 12992: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getFileContents = getFileContents; exports.fileExists = fileExists; exports.isResDepGraph = isResDepGraph; exports.normalizeFilePath = normalizeFilePath; exports.isSubpath = isSubpath; const fs = __webpack_require__(57147); const path = __webpack_require__(71017); function getFileContents(root, fileName) { const fullPath = path.resolve(root, fileName); if (!fs.existsSync(fullPath)) { throw new Error('Manifest ' + fileName + ' not found at location: ' + fileName); } const content = fs.readFileSync(fullPath, 'utf-8'); return { content, fileName, }; } function fileExists(root, fileName) { const fullPath = path.resolve(root, fileName); return fs.existsSync(fullPath); } function isResDepGraph(depRes) { return 'rootPkg' in depRes; } function normalizeFilePath(filePath) { return path.normalize(filePath).replace(/\\/g, '/'); } function isSubpath(subpath, parentPath) { // Normalize both paths (ensure consistent separators) const normalizedSubpath = normalizeFilePath(subpath); const normalizedParentPath = normalizeFilePath(parentPath); // Ensure subpath starts with parent path return (normalizedSubpath == normalizedParentPath || normalizedSubpath.startsWith(`${normalizedParentPath}/`)); } //# sourceMappingURL=utils.js.map /***/ }), /***/ 51957: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.processYarnWorkspaces = exports.processPnpmWorkspaces = exports.processNpmWorkspaces = void 0; const npm_workspaces_parser_1 = __webpack_require__(59823); Object.defineProperty(exports, "processNpmWorkspaces", ({ enumerable: true, get: function () { return npm_workspaces_parser_1.processNpmWorkspaces; } })); const pnpm_workspaces_parser_1 = __webpack_require__(20922); Object.defineProperty(exports, "processPnpmWorkspaces", ({ enumerable: true, get: function () { return pnpm_workspaces_parser_1.processPnpmWorkspaces; } })); const yarn_workspaces_parser_1 = __webpack_require__(18664); Object.defineProperty(exports, "processYarnWorkspaces", ({ enumerable: true, get: function () { return yarn_workspaces_parser_1.processYarnWorkspaces; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 59823: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getWorkspacesMap = getWorkspacesMap; exports.packageJsonBelongsToWorkspace = packageJsonBelongsToWorkspace; exports.processNpmWorkspaces = processNpmWorkspaces; const baseDebug = __webpack_require__(15158); const pathUtil = __webpack_require__(71017); const lodash_1 = __webpack_require__(96486); const micromatch = __webpack_require__(70850); const debug = baseDebug('snyk-npm-workspaces'); const lockFileParser = __webpack_require__(79790); const utils_1 = __webpack_require__(12992); const errors_1 = __webpack_require__(35786); function getWorkspacesMap(file) { const workspacesMap = {}; if (!file) { return workspacesMap; } try { const rootFileWorkspacesDefinitions = JSON.parse(file.content).workspaces || false; if (rootFileWorkspacesDefinitions && rootFileWorkspacesDefinitions.length) { workspacesMap[file.fileName] = { workspaces: rootFileWorkspacesDefinitions, }; } } catch (e) { debug('Failed to process a workspace', e.message); } return workspacesMap; } function packageJsonBelongsToWorkspace(packageJsonFileName, workspacesMap, workspaceRoot) { const workspaceRootFolder = pathUtil.dirname(workspaceRoot.replace(/\\/g, '/')); const workspacesGlobs = (workspacesMap[workspaceRoot].workspaces || []).map((workspace) => pathUtil.join(workspaceRootFolder, workspace)); const match = micromatch.isMatch(packageJsonFileName.replace(/\\/g, '/'), workspacesGlobs.map((p) => pathUtil.normalize(pathUtil.join(p, 'package.json')).replace(/\\/g, '/'))); return match; } async function processNpmWorkspaces(root, settings, targetFiles) { // the order of npmTargetFiles folders is important // must have the root level most folders at the top const mappedAndFiltered = targetFiles .map((p) => ({ path: p, ...pathUtil.parse(p) })) .filter((res) => ['package.json', 'package-lock.json'].includes(res.base)); const sorted = (0, lodash_1.sortBy)(mappedAndFiltered, 'dir'); const npmTargetFiles = (0, lodash_1.groupBy)(sorted, 'dir'); debug(`Processing potential Npm workspaces (${targetFiles.length})`); if (settings.yarnWorkspaces && Object.keys(npmTargetFiles).length === 0) { throw (0, errors_1.NoSupportedManifestsFoundError)([root]); } let npmWorkspacesMap = {}; const workspacesFilesMap = {}; const result = { plugin: { name: 'snyk-nodejs-npm-workspaces', runtime: process.version, }, scannedProjects: [], }; // the folders must be ordered highest first for (const directory of Object.keys(npmTargetFiles)) { debug(`Processing ${directory} as a potential npm workspace`); let isWorkspacePackage = false; let isRootPackageJson = false; const packageJsonFileName = pathUtil.join(directory, 'package.json'); const packageJson = (0, utils_1.getFileContents)(root, packageJsonFileName); npmWorkspacesMap = { ...npmWorkspacesMap, ...getWorkspacesMap(packageJson), }; for (const workspaceRoot of Object.keys(npmWorkspacesMap)) { const match = packageJsonBelongsToWorkspace(packageJsonFileName, npmWorkspacesMap, workspaceRoot); if (match) { debug(`${packageJsonFileName} matches an existing workspace pattern`); workspacesFilesMap[packageJsonFileName] = { root: workspaceRoot, }; isWorkspacePackage = true; } if (packageJsonFileName === workspaceRoot) { isRootPackageJson = true; } } if (!(isWorkspacePackage || isRootPackageJson)) { debug(`${packageJsonFileName} is not part of any detected workspace, skipping`); continue; } try { const rootDir = isWorkspacePackage ? pathUtil.dirname(workspacesFilesMap[packageJsonFileName].root) : pathUtil.dirname(packageJsonFileName); const rootLockfileName = pathUtil.join(rootDir, 'package-lock.json'); const lockContent = (0, utils_1.getFileContents)(root, rootLockfileName); const res = await lockFileParser.parseNpmLockV2Project(packageJson.content, lockContent.content, { includeDevDeps: settings.dev || false, strictOutOfSync: settings.strictOutOfSync || false, includeOptionalDeps: false, pruneCycles: true, }); const project = { packageManager: 'npm', targetFile: pathUtil.relative(root, packageJson.fileName), depGraph: res, plugin: { name: 'snyk-nodejs-lockfile-parser', runtime: process.version, }, }; result.scannedProjects.push(project); } catch (e) { if (settings.yarnWorkspaces) { throw e; } debug(`Error process workspace: ${packageJsonFileName}. ERROR: ${e}`); } } if (!result.scannedProjects.length) { debug(`No npm workspaces detected in any of the ${targetFiles.length} target files.`); } return result; } //# sourceMappingURL=npm-workspaces-parser.js.map /***/ }), /***/ 20922: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.processPnpmWorkspaces = processPnpmWorkspaces; const debugModule = __webpack_require__(15158); const pathUtil = __webpack_require__(71017); const fs = __webpack_require__(57147); const debug = debugModule('snyk-pnpm-workspaces'); const lockFileParser = __webpack_require__(79790); const workspace_utils_1 = __webpack_require__(24729); async function processPnpmWorkspaces(root, settings, targetFiles) { const pnpmWorkspaceDirs = (0, workspace_utils_1.sortTargetFiles)(targetFiles, ['pnpm-lock.yaml']); debug(`Processing potential Pnpm workspaces (${targetFiles.length})`); const result = { plugin: { name: 'snyk-nodejs-pnpm-workspaces', runtime: process.version, }, scannedProjects: [], }; // the folders must be ordered highest first for (const directory of Object.keys(pnpmWorkspaceDirs)) { debug(`Processing ${directory} as a potential Pnpm workspace`); const pnpmWorkspacePath = pathUtil.join(directory, 'pnpm-workspace.yaml'); if (!fs.existsSync(pnpmWorkspacePath)) { debug(`Workspace file not found at ${directory}. Can't be a pnpm workspace root.`); continue; } const scannedProjects = await lockFileParser.parsePnpmWorkspace(root, directory, { includeDevDeps: settings.dev || false, includeOptionalDeps: settings.optional || true, includePeerDeps: true, pruneWithinTopLevelDeps: true, strictOutOfSync: settings.strictOutOfSync === undefined ? true : settings.strictOutOfSync, }); result.scannedProjects = result.scannedProjects.concat(scannedProjects); } if (!result.scannedProjects.length) { debug(`No pnpm workspaces detected in any of the ${targetFiles.length} target files.`); } return result; } //# sourceMappingURL=pnpm-workspaces-parser.js.map /***/ }), /***/ 24729: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.sortTargetFiles = sortTargetFiles; exports.getWorkspacesMap = getWorkspacesMap; exports.packageJsonBelongsToWorkspace = packageJsonBelongsToWorkspace; const debugModule = __webpack_require__(15158); const pathUtil = __webpack_require__(71017); const lockFileParser = __webpack_require__(79790); const micromatch = __webpack_require__(70850); const lodash_1 = __webpack_require__(96486); const utils_1 = __webpack_require__(12992); const debug = debugModule('snyk-workspaces'); function sortTargetFiles(targetFiles, rootFiles) { // the order of targetFiles folders is important // must have the root level most folders at the top const mappedAndFiltered = targetFiles .map((p) => ({ path: p, ...pathUtil.parse(p) })) .filter((res) => rootFiles.includes(res.base)); const sorted = (0, lodash_1.sortBy)(mappedAndFiltered, 'dir'); const groupedTargetFiles = (0, lodash_1.groupBy)(sorted, 'dir'); return groupedTargetFiles; } function getWorkspacesMap(root, directory, packageJson) { const pnpmWorkspacesMap = {}; const pnpmWorkspacesPath = pathUtil.join(directory, 'pnpm-workspace.yaml'); if (!(0, utils_1.fileExists)(root, pnpmWorkspacesPath)) { return pnpmWorkspacesMap; } const file = (0, utils_1.getFileContents)(root, pnpmWorkspacesPath); if (!file) { return pnpmWorkspacesMap; } try { const rootFileWorkspacesDefinitions = lockFileParser.getPnpmWorkspaces(file.content); if (rootFileWorkspacesDefinitions && rootFileWorkspacesDefinitions.length) { pnpmWorkspacesMap[packageJson.fileName] = { workspaces: rootFileWorkspacesDefinitions, }; } } catch (e) { debug('Failed to process a workspace', e.message); } return pnpmWorkspacesMap; } function packageJsonBelongsToWorkspace(packageJsonFileName, pnpmWorkspacesMap, workspaceRoot) { const workspaceRootFolder = pathUtil.dirname((0, utils_1.normalizeFilePath)(workspaceRoot)); const workspacesGlobs = (pnpmWorkspacesMap[workspaceRoot].workspaces || []).map((workspace) => pathUtil.join(workspaceRootFolder, workspace)); const match = micromatch.isMatch((0, utils_1.normalizeFilePath)(packageJsonFileName), workspacesGlobs.map((p) => (0, utils_1.normalizeFilePath)(pathUtil.join(p, '**')))); return match; } //# sourceMappingURL=workspace-utils.js.map /***/ }), /***/ 18664: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getWorkspacesMap = getWorkspacesMap; exports.packageJsonBelongsToWorkspace = packageJsonBelongsToWorkspace; exports.processYarnWorkspaces = processYarnWorkspaces; const baseDebug = __webpack_require__(15158); const pathUtil = __webpack_require__(71017); const lodash_1 = __webpack_require__(96486); const micromatch = __webpack_require__(70850); const debug = baseDebug('snyk-yarn-workspaces'); const lockFileParser = __webpack_require__(79790); const utils_1 = __webpack_require__(12992); const errors_1 = __webpack_require__(35786); function getWorkspacesMap(file) { const yarnWorkspacesMap = {}; if (!file) { return yarnWorkspacesMap; } try { const rootFileWorkspacesDefinitions = lockFileParser.getYarnWorkspaces(file.content); if (rootFileWorkspacesDefinitions && rootFileWorkspacesDefinitions.length) { yarnWorkspacesMap[file.fileName] = { workspaces: rootFileWorkspacesDefinitions, }; } } catch (e) { debug('Failed to process a workspace', e.message); } return yarnWorkspacesMap; } function packageJsonBelongsToWorkspace(packageJsonFileName, yarnWorkspacesMap, workspaceRoot) { const workspaceRootFolder = pathUtil.dirname(workspaceRoot.replace(/\\/g, '/')); const workspacesGlobs = (yarnWorkspacesMap[workspaceRoot].workspaces || []).map((workspace) => pathUtil.join(workspaceRootFolder, workspace)); const match = micromatch.isMatch(packageJsonFileName.replace(/\\/g, '/'), workspacesGlobs.map((p) => pathUtil.normalize(pathUtil.join(p, '**')).replace(/\\/g, '/'))); return match; } async function processYarnWorkspaces(root, settings, targetFiles) { // the order of yarnTargetFiles folders is important // must have the root level most folders at the top const mappedAndFiltered = targetFiles .map((p) => ({ path: p, ...pathUtil.parse(p) })) .filter((res) => ['package.json', 'yarn.lock'].includes(res.base)); const sorted = (0, lodash_1.sortBy)(mappedAndFiltered, 'dir'); const yarnTargetFiles = (0, lodash_1.groupBy)(sorted, 'dir'); debug(`Processing potential Yarn workspaces (${targetFiles.length})`); if (settings.yarnWorkspaces && Object.keys(yarnTargetFiles).length === 0) { throw (0, errors_1.NoSupportedManifestsFoundError)([root]); } let yarnWorkspacesMap = {}; const yarnWorkspacesFilesMap = {}; const result = { plugin: { name: 'snyk-nodejs-yarn-workspaces', runtime: process.version, }, scannedProjects: [], }; let rootWorkspaceManifestContent = {}; // the folders must be ordered highest first for (const directory of Object.keys(yarnTargetFiles)) { debug(`Processing ${directory} as a potential Yarn workspace`); let isYarnWorkspacePackage = false; let isRootPackageJson = false; const packageJsonFileName = pathUtil.join(directory, 'package.json'); const packageJson = (0, utils_1.getFileContents)(root, packageJsonFileName); yarnWorkspacesMap = { ...yarnWorkspacesMap, ...getWorkspacesMap(packageJson), }; for (const workspaceRoot of Object.keys(yarnWorkspacesMap)) { const match = packageJsonBelongsToWorkspace(packageJsonFileName, yarnWorkspacesMap, workspaceRoot); if (match) { debug(`${packageJsonFileName} matches an existing workspace pattern`); yarnWorkspacesFilesMap[packageJsonFileName] = { root: workspaceRoot, }; isYarnWorkspacePackage = true; } if (packageJsonFileName === workspaceRoot) { isRootPackageJson = true; rootWorkspaceManifestContent = JSON.parse(packageJson.content); } } if (!(isYarnWorkspacePackage || isRootPackageJson)) { debug(`${packageJsonFileName} is not part of any detected workspace, skipping`); continue; } try { const rootDir = isYarnWorkspacePackage ? pathUtil.dirname(yarnWorkspacesFilesMap[packageJsonFileName].root) : pathUtil.dirname(packageJsonFileName); const rootYarnLockfileName = pathUtil.join(rootDir, 'yarn.lock'); const yarnLock = (0, utils_1.getFileContents)(root, rootYarnLockfileName); const lockfileVersion = lockFileParser.getYarnLockfileVersion(yarnLock.content); let res; switch (lockfileVersion) { case lockFileParser.NodeLockfileVersion.YarnLockV1: res = await lockFileParser.parseYarnLockV1Project(packageJson.content, yarnLock.content, { includeDevDeps: settings.dev || false, includeOptionalDeps: false, includePeerDeps: false, pruneLevel: 'withinTopLevelDeps', strictOutOfSync: settings.strictOutOfSync === undefined ? true : settings.strictOutOfSync, }); break; case lockFileParser.NodeLockfileVersion.YarnLockV2: res = await lockFileParser.parseYarnLockV2Project(packageJson.content, yarnLock.content, { includeDevDeps: settings.dev || false, includeOptionalDeps: false, pruneWithinTopLevelDeps: true, strictOutOfSync: settings.strictOutOfSync === undefined ? true : settings.strictOutOfSync, }, { isWorkspacePkg: true, isRoot: isRootPackageJson, rootResolutions: (rootWorkspaceManifestContent === null || rootWorkspaceManifestContent === void 0 ? void 0 : rootWorkspaceManifestContent['resolutions']) || {}, }); break; default: throw new Error('Failed to build dep graph from current project'); } const project = { packageManager: 'yarn', targetFile: pathUtil.relative(root, packageJson.fileName), depGraph: res, plugin: { name: 'snyk-nodejs-lockfile-parser', runtime: process.version, }, }; result.scannedProjects.push(project); } catch (e) { if (settings.yarnWorkspaces) { throw e; } debug(`Error process workspace: ${packageJsonFileName}. ERROR: ${e}`); } } if (!result.scannedProjects.length) { debug(`No yarn workspaces detected in any of the ${targetFiles.length} target files.`); } return result; } //# sourceMappingURL=yarn-workspaces-parser.js.map /***/ }), /***/ 80474: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var loader = __webpack_require__(54747); var dumper = __webpack_require__(8665); function renamed(from, to) { return function () { throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' + 'Use yaml.' + to + ' instead, which is now safe by default.'); }; } module.exports.Type = __webpack_require__(85460); module.exports.Schema = __webpack_require__(13646); module.exports.FAILSAFE_SCHEMA = __webpack_require__(34246); module.exports.JSON_SCHEMA = __webpack_require__(85965); module.exports.CORE_SCHEMA = __webpack_require__(73303); module.exports.DEFAULT_SCHEMA = __webpack_require__(24138); module.exports.load = loader.load; module.exports.loadAll = loader.loadAll; module.exports.dump = dumper.dump; module.exports.YAMLException = __webpack_require__(5548); // Re-export all types in case user wants to create custom schema module.exports.types = { binary: __webpack_require__(50180), float: __webpack_require__(98118), map: __webpack_require__(31559), null: __webpack_require__(62116), pairs: __webpack_require__(62089), set: __webpack_require__(5292), timestamp: __webpack_require__(78301), bool: __webpack_require__(62246), int: __webpack_require__(63014), merge: __webpack_require__(76222), omap: __webpack_require__(15887), seq: __webpack_require__(3832), str: __webpack_require__(54473) }; // Removed functions from JS-YAML 3.0.x module.exports.safeLoad = renamed('safeLoad', 'load'); module.exports.safeLoadAll = renamed('safeLoadAll', 'loadAll'); module.exports.safeDump = renamed('safeDump', 'dump'); /***/ }), /***/ 69381: /***/ ((module) => { "use strict"; function isNothing(subject) { return (typeof subject === 'undefined') || (subject === null); } function isObject(subject) { return (typeof subject === 'object') && (subject !== null); } function toArray(sequence) { if (Array.isArray(sequence)) return sequence; else if (isNothing(sequence)) return []; return [ sequence ]; } function extend(target, source) { var index, length, key, sourceKeys; if (source) { sourceKeys = Object.keys(source); for (index = 0, length = sourceKeys.length; index < length; index += 1) { key = sourceKeys[index]; target[key] = source[key]; } } return target; } function repeat(string, count) { var result = '', cycle; for (cycle = 0; cycle < count; cycle += 1) { result += string; } return result; } function isNegativeZero(number) { return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); } module.exports.isNothing = isNothing; module.exports.isObject = isObject; module.exports.toArray = toArray; module.exports.repeat = repeat; module.exports.isNegativeZero = isNegativeZero; module.exports.extend = extend; /***/ }), /***/ 8665: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*eslint-disable no-use-before-define*/ var common = __webpack_require__(69381); var YAMLException = __webpack_require__(5548); var DEFAULT_SCHEMA = __webpack_require__(24138); var _toString = Object.prototype.toString; var _hasOwnProperty = Object.prototype.hasOwnProperty; var CHAR_BOM = 0xFEFF; var CHAR_TAB = 0x09; /* Tab */ var CHAR_LINE_FEED = 0x0A; /* LF */ var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ var CHAR_SPACE = 0x20; /* Space */ var CHAR_EXCLAMATION = 0x21; /* ! */ var CHAR_DOUBLE_QUOTE = 0x22; /* " */ var CHAR_SHARP = 0x23; /* # */ var CHAR_PERCENT = 0x25; /* % */ var CHAR_AMPERSAND = 0x26; /* & */ var CHAR_SINGLE_QUOTE = 0x27; /* ' */ var CHAR_ASTERISK = 0x2A; /* * */ var CHAR_COMMA = 0x2C; /* , */ var CHAR_MINUS = 0x2D; /* - */ var CHAR_COLON = 0x3A; /* : */ var CHAR_EQUALS = 0x3D; /* = */ var CHAR_GREATER_THAN = 0x3E; /* > */ var CHAR_QUESTION = 0x3F; /* ? */ var CHAR_COMMERCIAL_AT = 0x40; /* @ */ var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ var CHAR_GRAVE_ACCENT = 0x60; /* ` */ var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ var CHAR_VERTICAL_LINE = 0x7C; /* | */ var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ var ESCAPE_SEQUENCES = {}; ESCAPE_SEQUENCES[0x00] = '\\0'; ESCAPE_SEQUENCES[0x07] = '\\a'; ESCAPE_SEQUENCES[0x08] = '\\b'; ESCAPE_SEQUENCES[0x09] = '\\t'; ESCAPE_SEQUENCES[0x0A] = '\\n'; ESCAPE_SEQUENCES[0x0B] = '\\v'; ESCAPE_SEQUENCES[0x0C] = '\\f'; ESCAPE_SEQUENCES[0x0D] = '\\r'; ESCAPE_SEQUENCES[0x1B] = '\\e'; ESCAPE_SEQUENCES[0x22] = '\\"'; ESCAPE_SEQUENCES[0x5C] = '\\\\'; ESCAPE_SEQUENCES[0x85] = '\\N'; ESCAPE_SEQUENCES[0xA0] = '\\_'; ESCAPE_SEQUENCES[0x2028] = '\\L'; ESCAPE_SEQUENCES[0x2029] = '\\P'; var DEPRECATED_BOOLEANS_SYNTAX = [ 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' ]; var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; function compileStyleMap(schema, map) { var result, keys, index, length, tag, style, type; if (map === null) return {}; result = {}; keys = Object.keys(map); for (index = 0, length = keys.length; index < length; index += 1) { tag = keys[index]; style = String(map[tag]); if (tag.slice(0, 2) === '!!') { tag = 'tag:yaml.org,2002:' + tag.slice(2); } type = schema.compiledTypeMap['fallback'][tag]; if (type && _hasOwnProperty.call(type.styleAliases, style)) { style = type.styleAliases[style]; } result[tag] = style; } return result; } function encodeHex(character) { var string, handle, length; string = character.toString(16).toUpperCase(); if (character <= 0xFF) { handle = 'x'; length = 2; } else if (character <= 0xFFFF) { handle = 'u'; length = 4; } else if (character <= 0xFFFFFFFF) { handle = 'U'; length = 8; } else { throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); } return '\\' + handle + common.repeat('0', length - string.length) + string; } var QUOTING_TYPE_SINGLE = 1, QUOTING_TYPE_DOUBLE = 2; function State(options) { this.schema = options['schema'] || DEFAULT_SCHEMA; this.indent = Math.max(1, (options['indent'] || 2)); this.noArrayIndent = options['noArrayIndent'] || false; this.skipInvalid = options['skipInvalid'] || false; this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); this.styleMap = compileStyleMap(this.schema, options['styles'] || null); this.sortKeys = options['sortKeys'] || false; this.lineWidth = options['lineWidth'] || 80; this.noRefs = options['noRefs'] || false; this.noCompatMode = options['noCompatMode'] || false; this.condenseFlow = options['condenseFlow'] || false; this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; this.forceQuotes = options['forceQuotes'] || false; this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null; this.implicitTypes = this.schema.compiledImplicit; this.explicitTypes = this.schema.compiledExplicit; this.tag = null; this.result = ''; this.duplicates = []; this.usedDuplicates = null; } // Indents every line in a string. Empty lines (\n only) are not indented. function indentString(string, spaces) { var ind = common.repeat(' ', spaces), position = 0, next = -1, result = '', line, length = string.length; while (position < length) { next = string.indexOf('\n', position); if (next === -1) { line = string.slice(position); position = length; } else { line = string.slice(position, next + 1); position = next + 1; } if (line.length && line !== '\n') result += ind; result += line; } return result; } function generateNextLine(state, level) { return '\n' + common.repeat(' ', state.indent * level); } function testImplicitResolving(state, str) { var index, length, type; for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { type = state.implicitTypes[index]; if (type.resolve(str)) { return true; } } return false; } // [33] s-white ::= s-space | s-tab function isWhitespace(c) { return c === CHAR_SPACE || c === CHAR_TAB; } // Returns true if the character can be printed without escaping. // From YAML 1.2: "any allowed characters known to be non-printable // should also be escaped. [However,] This isn’t mandatory" // Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. function isPrintable(c) { return (0x00020 <= c && c <= 0x00007E) || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM) || (0x10000 <= c && c <= 0x10FFFF); } // [34] ns-char ::= nb-char - s-white // [27] nb-char ::= c-printable - b-char - c-byte-order-mark // [26] b-char ::= b-line-feed | b-carriage-return // Including s-white (for some reason, examples doesn't match specs in this aspect) // ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark function isNsCharOrWhitespace(c) { return isPrintable(c) && c !== CHAR_BOM // - b-char && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED; } // [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out // c = flow-in ⇒ ns-plain-safe-in // c = block-key ⇒ ns-plain-safe-out // c = flow-key ⇒ ns-plain-safe-in // [128] ns-plain-safe-out ::= ns-char // [129] ns-plain-safe-in ::= ns-char - c-flow-indicator // [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” ) // | ( /* An ns-char preceding */ “#” ) // | ( “:” /* Followed by an ns-plain-safe(c) */ ) function isPlainSafe(c, prev, inblock) { var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); return ( // ns-plain-safe inblock ? // c = flow-in cIsNsCharOrWhitespace : cIsNsCharOrWhitespace // - c-flow-indicator && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET ) // ns-plain-char && c !== CHAR_SHARP // false on '#' && !(prev === CHAR_COLON && !cIsNsChar) // false on ': ' || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#' || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]' } // Simplified test for values allowed as the first character in plain style. function isPlainSafeFirst(c) { // Uses a subset of ns-char - c-indicator // where ns-char = nb-char - s-white. // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part return isPrintable(c) && c !== CHAR_BOM && !isWhitespace(c) // - s-white // - (c-indicator ::= // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE // | “%” | “@” | “`”) && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT; } // Simplified test for values allowed as the last character in plain style. function isPlainSafeLast(c) { // just not whitespace or colon, it will be checked to be plain character later return !isWhitespace(c) && c !== CHAR_COLON; } // Same as 'string'.codePointAt(pos), but works in older browsers. function codePointAt(string, pos) { var first = string.charCodeAt(pos), second; if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) { second = string.charCodeAt(pos + 1); if (second >= 0xDC00 && second <= 0xDFFF) { // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; } } return first; } // Determines whether block indentation indicator is required. function needIndentIndicator(string) { var leadingSpaceRe = /^\n* /; return leadingSpaceRe.test(string); } var STYLE_PLAIN = 1, STYLE_SINGLE = 2, STYLE_LITERAL = 3, STYLE_FOLDED = 4, STYLE_DOUBLE = 5; // Determines which scalar styles are possible and returns the preferred style. // lineWidth = -1 => no limit. // Pre-conditions: str.length > 0. // Post-conditions: // STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. // STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). // STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) { var i; var char = 0; var prevChar = null; var hasLineBreak = false; var hasFoldableLine = false; // only checked if shouldTrackWidth var shouldTrackWidth = lineWidth !== -1; var previousLineBreak = -1; // count the first line correctly var plain = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1)); if (singleLineOnly || forceQuotes) { // Case: no block styles. // Check for disallowed characters to rule out plain and single. for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { char = codePointAt(string, i); if (!isPrintable(char)) { return STYLE_DOUBLE; } plain = plain && isPlainSafe(char, prevChar, inblock); prevChar = char; } } else { // Case: block styles permitted. for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { char = codePointAt(string, i); if (char === CHAR_LINE_FEED) { hasLineBreak = true; // Check if any line can be folded. if (shouldTrackWidth) { hasFoldableLine = hasFoldableLine || // Foldable line = too long, and not more-indented. (i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== ' '); previousLineBreak = i; } } else if (!isPrintable(char)) { return STYLE_DOUBLE; } plain = plain && isPlainSafe(char, prevChar, inblock); prevChar = char; } // in case the end is missing a \n hasFoldableLine = hasFoldableLine || (shouldTrackWidth && (i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== ' ')); } // Although every style can represent \n without escaping, prefer block styles // for multiline, since they're more readable and they don't add empty lines. // Also prefer folding a super-long line. if (!hasLineBreak && !hasFoldableLine) { // Strings interpretable as another type have to be quoted; // e.g. the string 'true' vs. the boolean true. if (plain && !forceQuotes && !testAmbiguousType(string)) { return STYLE_PLAIN; } return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; } // Edge case: block indentation indicator can only have one digit. if (indentPerLevel > 9 && needIndentIndicator(string)) { return STYLE_DOUBLE; } // At this point we know block styles are valid. // Prefer literal style unless we want to fold. if (!forceQuotes) { return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; } return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; } // Note: line breaking/folding is implemented for only the folded style. // NB. We drop the last trailing newline (if any) of a returned block scalar // since the dumper adds its own newline. This always works: // • No ending newline => unaffected; already using strip "-" chomping. // • Ending newline => removed then restored. // Importantly, this keeps the "+" chomp indicator from gaining an extra line. function writeScalar(state, string, level, iskey, inblock) { state.dump = (function () { if (string.length === 0) { return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''"; } if (!state.noCompatMode) { if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) { return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'"); } } var indent = state.indent * Math.max(1, level); // no 0-indent scalars // As indentation gets deeper, let the width decrease monotonically // to the lower bound min(state.lineWidth, 40). // Note that this implies // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. // state.lineWidth > 40 + state.indent: width decreases until the lower bound. // This behaves better than a constant minimum width which disallows narrower options, // or an indent threshold which causes the width to suddenly increase. var lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); // Without knowing if keys are implicit/explicit, assume implicit for safety. var singleLineOnly = iskey // No block styles in flow mode. || (state.flowLevel > -1 && level >= state.flowLevel); function testAmbiguity(string) { return testImplicitResolving(state, string); } switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { case STYLE_PLAIN: return string; case STYLE_SINGLE: return "'" + string.replace(/'/g, "''") + "'"; case STYLE_LITERAL: return '|' + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent)); case STYLE_FOLDED: return '>' + blockHeader(string, state.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); case STYLE_DOUBLE: return '"' + escapeString(string, lineWidth) + '"'; default: throw new YAMLException('impossible error: invalid scalar style'); } }()); } // Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. function blockHeader(string, indentPerLevel) { var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; // note the special case: the string '\n' counts as a "trailing" empty line. var clip = string[string.length - 1] === '\n'; var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); var chomp = keep ? '+' : (clip ? '' : '-'); return indentIndicator + chomp + '\n'; } // (See the note for writeScalar.) function dropEndingNewline(string) { return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; } // Note: a long line without a suitable break point will exceed the width limit. // Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. function foldString(string, width) { // In folded style, $k$ consecutive newlines output as $k+1$ newlines— // unless they're before or after a more-indented line, or at the very // beginning or end, in which case $k$ maps to $k$. // Therefore, parse each chunk as newline(s) followed by a content line. var lineRe = /(\n+)([^\n]*)/g; // first line (possibly an empty line) var result = (function () { var nextLF = string.indexOf('\n'); nextLF = nextLF !== -1 ? nextLF : string.length; lineRe.lastIndex = nextLF; return foldLine(string.slice(0, nextLF), width); }()); // If we haven't reached the first content line yet, don't add an extra \n. var prevMoreIndented = string[0] === '\n' || string[0] === ' '; var moreIndented; // rest of the lines var match; while ((match = lineRe.exec(string))) { var prefix = match[1], line = match[2]; moreIndented = (line[0] === ' '); result += prefix + (!prevMoreIndented && !moreIndented && line !== '' ? '\n' : '') + foldLine(line, width); prevMoreIndented = moreIndented; } return result; } // Greedy line breaking. // Picks the longest line under the limit each time, // otherwise settles for the shortest line over the limit. // NB. More-indented lines *cannot* be folded, as that would add an extra \n. function foldLine(line, width) { if (line === '' || line[0] === ' ') return line; // Since a more-indented line adds a \n, breaks can't be followed by a space. var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. var match; // start is an inclusive index. end, curr, and next are exclusive. var start = 0, end, curr = 0, next = 0; var result = ''; // Invariants: 0 <= start <= length-1. // 0 <= curr <= next <= max(0, length-2). curr - start <= width. // Inside the loop: // A match implies length >= 2, so curr and next are <= length-2. while ((match = breakRe.exec(line))) { next = match.index; // maintain invariant: curr - start <= width if (next - start > width) { end = (curr > start) ? curr : next; // derive end <= length-2 result += '\n' + line.slice(start, end); // skip the space that was output as \n start = end + 1; // derive start <= length-1 } curr = next; } // By the invariants, start <= length-1, so there is something left over. // It is either the whole string or a part starting from non-whitespace. result += '\n'; // Insert a break if the remainder is too long and there is a break available. if (line.length - start > width && curr > start) { result += line.slice(start, curr) + '\n' + line.slice(curr + 1); } else { result += line.slice(start); } return result.slice(1); // drop extra \n joiner } // Escapes a double-quoted string. function escapeString(string) { var result = ''; var char = 0; var escapeSeq; for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { char = codePointAt(string, i); escapeSeq = ESCAPE_SEQUENCES[char]; if (!escapeSeq && isPrintable(char)) { result += string[i]; if (char >= 0x10000) result += string[i + 1]; } else { result += escapeSeq || encodeHex(char); } } return result; } function writeFlowSequence(state, level, object) { var _result = '', _tag = state.tag, index, length, value; for (index = 0, length = object.length; index < length; index += 1) { value = object[index]; if (state.replacer) { value = state.replacer.call(object, String(index), value); } // Write only valid elements, put null instead of invalid elements. if (writeNode(state, level, value, false, false) || (typeof value === 'undefined' && writeNode(state, level, null, false, false))) { if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : ''); _result += state.dump; } } state.tag = _tag; state.dump = '[' + _result + ']'; } function writeBlockSequence(state, level, object, compact) { var _result = '', _tag = state.tag, index, length, value; for (index = 0, length = object.length; index < length; index += 1) { value = object[index]; if (state.replacer) { value = state.replacer.call(object, String(index), value); } // Write only valid elements, put null instead of invalid elements. if (writeNode(state, level + 1, value, true, true, false, true) || (typeof value === 'undefined' && writeNode(state, level + 1, null, true, true, false, true))) { if (!compact || _result !== '') { _result += generateNextLine(state, level); } if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { _result += '-'; } else { _result += '- '; } _result += state.dump; } } state.tag = _tag; state.dump = _result || '[]'; // Empty sequence if no valid values. } function writeFlowMapping(state, level, object) { var _result = '', _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, pairBuffer; for (index = 0, length = objectKeyList.length; index < length; index += 1) { pairBuffer = ''; if (_result !== '') pairBuffer += ', '; if (state.condenseFlow) pairBuffer += '"'; objectKey = objectKeyList[index]; objectValue = object[objectKey]; if (state.replacer) { objectValue = state.replacer.call(object, objectKey, objectValue); } if (!writeNode(state, level, objectKey, false, false)) { continue; // Skip this pair because of invalid key; } if (state.dump.length > 1024) pairBuffer += '? '; pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); if (!writeNode(state, level, objectValue, false, false)) { continue; // Skip this pair because of invalid value. } pairBuffer += state.dump; // Both key and value are valid. _result += pairBuffer; } state.tag = _tag; state.dump = '{' + _result + '}'; } function writeBlockMapping(state, level, object, compact) { var _result = '', _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, explicitPair, pairBuffer; // Allow sorting keys so that the output file is deterministic if (state.sortKeys === true) { // Default sorting objectKeyList.sort(); } else if (typeof state.sortKeys === 'function') { // Custom sort function objectKeyList.sort(state.sortKeys); } else if (state.sortKeys) { // Something is wrong throw new YAMLException('sortKeys must be a boolean or a function'); } for (index = 0, length = objectKeyList.length; index < length; index += 1) { pairBuffer = ''; if (!compact || _result !== '') { pairBuffer += generateNextLine(state, level); } objectKey = objectKeyList[index]; objectValue = object[objectKey]; if (state.replacer) { objectValue = state.replacer.call(object, objectKey, objectValue); } if (!writeNode(state, level + 1, objectKey, true, true, true)) { continue; // Skip this pair because of invalid key. } explicitPair = (state.tag !== null && state.tag !== '?') || (state.dump && state.dump.length > 1024); if (explicitPair) { if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { pairBuffer += '?'; } else { pairBuffer += '? '; } } pairBuffer += state.dump; if (explicitPair) { pairBuffer += generateNextLine(state, level); } if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { continue; // Skip this pair because of invalid value. } if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { pairBuffer += ':'; } else { pairBuffer += ': '; } pairBuffer += state.dump; // Both key and value are valid. _result += pairBuffer; } state.tag = _tag; state.dump = _result || '{}'; // Empty mapping if no valid pairs. } function detectType(state, object, explicit) { var _result, typeList, index, length, type, style; typeList = explicit ? state.explicitTypes : state.implicitTypes; for (index = 0, length = typeList.length; index < length; index += 1) { type = typeList[index]; if ((type.instanceOf || type.predicate) && (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && (!type.predicate || type.predicate(object))) { if (explicit) { if (type.multi && type.representName) { state.tag = type.representName(object); } else { state.tag = type.tag; } } else { state.tag = '?'; } if (type.represent) { style = state.styleMap[type.tag] || type.defaultStyle; if (_toString.call(type.represent) === '[object Function]') { _result = type.represent(object, style); } else if (_hasOwnProperty.call(type.represent, style)) { _result = type.represent[style](object, style); } else { throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); } state.dump = _result; } return true; } } return false; } // Serializes `object` and writes it to global `result`. // Returns true on success, or false on invalid object. // function writeNode(state, level, object, block, compact, iskey, isblockseq) { state.tag = null; state.dump = object; if (!detectType(state, object, false)) { detectType(state, object, true); } var type = _toString.call(state.dump); var inblock = block; var tagStr; if (block) { block = (state.flowLevel < 0 || state.flowLevel > level); } var objectOrArray = type === '[object Object]' || type === '[object Array]', duplicateIndex, duplicate; if (objectOrArray) { duplicateIndex = state.duplicates.indexOf(object); duplicate = duplicateIndex !== -1; } if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { compact = false; } if (duplicate && state.usedDuplicates[duplicateIndex]) { state.dump = '*ref_' + duplicateIndex; } else { if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { state.usedDuplicates[duplicateIndex] = true; } if (type === '[object Object]') { if (block && (Object.keys(state.dump).length !== 0)) { writeBlockMapping(state, level, state.dump, compact); if (duplicate) { state.dump = '&ref_' + duplicateIndex + state.dump; } } else { writeFlowMapping(state, level, state.dump); if (duplicate) { state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; } } } else if (type === '[object Array]') { if (block && (state.dump.length !== 0)) { if (state.noArrayIndent && !isblockseq && level > 0) { writeBlockSequence(state, level - 1, state.dump, compact); } else { writeBlockSequence(state, level, state.dump, compact); } if (duplicate) { state.dump = '&ref_' + duplicateIndex + state.dump; } } else { writeFlowSequence(state, level, state.dump); if (duplicate) { state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; } } } else if (type === '[object String]') { if (state.tag !== '?') { writeScalar(state, state.dump, level, iskey, inblock); } } else if (type === '[object Undefined]') { return false; } else { if (state.skipInvalid) return false; throw new YAMLException('unacceptable kind of an object to dump ' + type); } if (state.tag !== null && state.tag !== '?') { // Need to encode all characters except those allowed by the spec: // // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */ // [36] ns-hex-digit ::= ns-dec-digit // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */ // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */ // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-” // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#” // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,” // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]” // // Also need to encode '!' because it has special meaning (end of tag prefix). // tagStr = encodeURI( state.tag[0] === '!' ? state.tag.slice(1) : state.tag ).replace(/!/g, '%21'); if (state.tag[0] === '!') { tagStr = '!' + tagStr; } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') { tagStr = '!!' + tagStr.slice(18); } else { tagStr = '!<' + tagStr + '>'; } state.dump = tagStr + ' ' + state.dump; } } return true; } function getDuplicateReferences(object, state) { var objects = [], duplicatesIndexes = [], index, length; inspectNode(object, objects, duplicatesIndexes); for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { state.duplicates.push(objects[duplicatesIndexes[index]]); } state.usedDuplicates = new Array(length); } function inspectNode(object, objects, duplicatesIndexes) { var objectKeyList, index, length; if (object !== null && typeof object === 'object') { index = objects.indexOf(object); if (index !== -1) { if (duplicatesIndexes.indexOf(index) === -1) { duplicatesIndexes.push(index); } } else { objects.push(object); if (Array.isArray(object)) { for (index = 0, length = object.length; index < length; index += 1) { inspectNode(object[index], objects, duplicatesIndexes); } } else { objectKeyList = Object.keys(object); for (index = 0, length = objectKeyList.length; index < length; index += 1) { inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); } } } } } function dump(input, options) { options = options || {}; var state = new State(options); if (!state.noRefs) getDuplicateReferences(input, state); var value = input; if (state.replacer) { value = state.replacer.call({ '': value }, '', value); } if (writeNode(state, 0, value, true, true)) return state.dump + '\n'; return ''; } module.exports.dump = dump; /***/ }), /***/ 5548: /***/ ((module) => { "use strict"; // YAML error class. http://stackoverflow.com/questions/8458984 // function formatError(exception, compact) { var where = '', message = exception.reason || '(unknown reason)'; if (!exception.mark) return message; if (exception.mark.name) { where += 'in "' + exception.mark.name + '" '; } where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'; if (!compact && exception.mark.snippet) { where += '\n\n' + exception.mark.snippet; } return message + ' ' + where; } function YAMLException(reason, mark) { // Super constructor Error.call(this); this.name = 'YAMLException'; this.reason = reason; this.mark = mark; this.message = formatError(this, false); // Include stack trace in error object if (Error.captureStackTrace) { // Chrome and NodeJS Error.captureStackTrace(this, this.constructor); } else { // FF, IE 10+ and Safari 6+. Fallback for others this.stack = (new Error()).stack || ''; } } // Inherit from Error YAMLException.prototype = Object.create(Error.prototype); YAMLException.prototype.constructor = YAMLException; YAMLException.prototype.toString = function toString(compact) { return this.name + ': ' + formatError(this, compact); }; module.exports = YAMLException; /***/ }), /***/ 54747: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*eslint-disable max-len,no-use-before-define*/ var common = __webpack_require__(69381); var YAMLException = __webpack_require__(5548); var makeSnippet = __webpack_require__(32564); var DEFAULT_SCHEMA = __webpack_require__(24138); var _hasOwnProperty = Object.prototype.hasOwnProperty; var CONTEXT_FLOW_IN = 1; var CONTEXT_FLOW_OUT = 2; var CONTEXT_BLOCK_IN = 3; var CONTEXT_BLOCK_OUT = 4; var CHOMPING_CLIP = 1; var CHOMPING_STRIP = 2; var CHOMPING_KEEP = 3; var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; function _class(obj) { return Object.prototype.toString.call(obj); } function is_EOL(c) { return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); } function is_WHITE_SPACE(c) { return (c === 0x09/* Tab */) || (c === 0x20/* Space */); } function is_WS_OR_EOL(c) { return (c === 0x09/* Tab */) || (c === 0x20/* Space */) || (c === 0x0A/* LF */) || (c === 0x0D/* CR */); } function is_FLOW_INDICATOR(c) { return c === 0x2C/* , */ || c === 0x5B/* [ */ || c === 0x5D/* ] */ || c === 0x7B/* { */ || c === 0x7D/* } */; } function fromHexCode(c) { var lc; if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { return c - 0x30; } /*eslint-disable no-bitwise*/ lc = c | 0x20; if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { return lc - 0x61 + 10; } return -1; } function escapedHexLen(c) { if (c === 0x78/* x */) { return 2; } if (c === 0x75/* u */) { return 4; } if (c === 0x55/* U */) { return 8; } return 0; } function fromDecimalCode(c) { if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { return c - 0x30; } return -1; } function simpleEscapeSequence(c) { /* eslint-disable indent */ return (c === 0x30/* 0 */) ? '\x00' : (c === 0x61/* a */) ? '\x07' : (c === 0x62/* b */) ? '\x08' : (c === 0x74/* t */) ? '\x09' : (c === 0x09/* Tab */) ? '\x09' : (c === 0x6E/* n */) ? '\x0A' : (c === 0x76/* v */) ? '\x0B' : (c === 0x66/* f */) ? '\x0C' : (c === 0x72/* r */) ? '\x0D' : (c === 0x65/* e */) ? '\x1B' : (c === 0x20/* Space */) ? ' ' : (c === 0x22/* " */) ? '\x22' : (c === 0x2F/* / */) ? '/' : (c === 0x5C/* \ */) ? '\x5C' : (c === 0x4E/* N */) ? '\x85' : (c === 0x5F/* _ */) ? '\xA0' : (c === 0x4C/* L */) ? '\u2028' : (c === 0x50/* P */) ? '\u2029' : ''; } function charFromCodepoint(c) { if (c <= 0xFFFF) { return String.fromCharCode(c); } // Encode UTF-16 surrogate pair // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF return String.fromCharCode( ((c - 0x010000) >> 10) + 0xD800, ((c - 0x010000) & 0x03FF) + 0xDC00 ); } var simpleEscapeCheck = new Array(256); // integer, for fast access var simpleEscapeMap = new Array(256); for (var i = 0; i < 256; i++) { simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; simpleEscapeMap[i] = simpleEscapeSequence(i); } function State(input, options) { this.input = input; this.filename = options['filename'] || null; this.schema = options['schema'] || DEFAULT_SCHEMA; this.onWarning = options['onWarning'] || null; // (Hidden) Remove? makes the loader to expect YAML 1.1 documents // if such documents have no explicit %YAML directive this.legacy = options['legacy'] || false; this.json = options['json'] || false; this.listener = options['listener'] || null; this.implicitTypes = this.schema.compiledImplicit; this.typeMap = this.schema.compiledTypeMap; this.length = input.length; this.position = 0; this.line = 0; this.lineStart = 0; this.lineIndent = 0; // position of first leading tab in the current line, // used to make sure there are no tabs in the indentation this.firstTabInLine = -1; this.documents = []; /* this.version; this.checkLineBreaks; this.tagMap; this.anchorMap; this.tag; this.anchor; this.kind; this.result;*/ } function generateError(state, message) { var mark = { name: state.filename, buffer: state.input.slice(0, -1), // omit trailing \0 position: state.position, line: state.line, column: state.position - state.lineStart }; mark.snippet = makeSnippet(mark); return new YAMLException(message, mark); } function throwError(state, message) { throw generateError(state, message); } function throwWarning(state, message) { if (state.onWarning) { state.onWarning.call(null, generateError(state, message)); } } var directiveHandlers = { YAML: function handleYamlDirective(state, name, args) { var match, major, minor; if (state.version !== null) { throwError(state, 'duplication of %YAML directive'); } if (args.length !== 1) { throwError(state, 'YAML directive accepts exactly one argument'); } match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); if (match === null) { throwError(state, 'ill-formed argument of the YAML directive'); } major = parseInt(match[1], 10); minor = parseInt(match[2], 10); if (major !== 1) { throwError(state, 'unacceptable YAML version of the document'); } state.version = args[0]; state.checkLineBreaks = (minor < 2); if (minor !== 1 && minor !== 2) { throwWarning(state, 'unsupported YAML version of the document'); } }, TAG: function handleTagDirective(state, name, args) { var handle, prefix; if (args.length !== 2) { throwError(state, 'TAG directive accepts exactly two arguments'); } handle = args[0]; prefix = args[1]; if (!PATTERN_TAG_HANDLE.test(handle)) { throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); } if (_hasOwnProperty.call(state.tagMap, handle)) { throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); } if (!PATTERN_TAG_URI.test(prefix)) { throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); } try { prefix = decodeURIComponent(prefix); } catch (err) { throwError(state, 'tag prefix is malformed: ' + prefix); } state.tagMap[handle] = prefix; } }; function captureSegment(state, start, end, checkJson) { var _position, _length, _character, _result; if (start < end) { _result = state.input.slice(start, end); if (checkJson) { for (_position = 0, _length = _result.length; _position < _length; _position += 1) { _character = _result.charCodeAt(_position); if (!(_character === 0x09 || (0x20 <= _character && _character <= 0x10FFFF))) { throwError(state, 'expected valid JSON character'); } } } else if (PATTERN_NON_PRINTABLE.test(_result)) { throwError(state, 'the stream contains non-printable characters'); } state.result += _result; } } function mergeMappings(state, destination, source, overridableKeys) { var sourceKeys, key, index, quantity; if (!common.isObject(source)) { throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); } sourceKeys = Object.keys(source); for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { key = sourceKeys[index]; if (!_hasOwnProperty.call(destination, key)) { destination[key] = source[key]; overridableKeys[key] = true; } } } function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) { var index, quantity; // The output is a plain object here, so keys can only be strings. // We need to convert keyNode to a string, but doing so can hang the process // (deeply nested arrays that explode exponentially using aliases). if (Array.isArray(keyNode)) { keyNode = Array.prototype.slice.call(keyNode); for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { if (Array.isArray(keyNode[index])) { throwError(state, 'nested arrays are not supported inside keys'); } if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { keyNode[index] = '[object Object]'; } } } // Avoid code execution in load() via toString property // (still use its own toString for arrays, timestamps, // and whatever user schema extensions happen to have @@toStringTag) if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { keyNode = '[object Object]'; } keyNode = String(keyNode); if (_result === null) { _result = {}; } if (keyTag === 'tag:yaml.org,2002:merge') { if (Array.isArray(valueNode)) { for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { mergeMappings(state, _result, valueNode[index], overridableKeys); } } else { mergeMappings(state, _result, valueNode, overridableKeys); } } else { if (!state.json && !_hasOwnProperty.call(overridableKeys, keyNode) && _hasOwnProperty.call(_result, keyNode)) { state.line = startLine || state.line; state.lineStart = startLineStart || state.lineStart; state.position = startPos || state.position; throwError(state, 'duplicated mapping key'); } // used for this specific key only because Object.defineProperty is slow if (keyNode === '__proto__') { Object.defineProperty(_result, keyNode, { configurable: true, enumerable: true, writable: true, value: valueNode }); } else { _result[keyNode] = valueNode; } delete overridableKeys[keyNode]; } return _result; } function readLineBreak(state) { var ch; ch = state.input.charCodeAt(state.position); if (ch === 0x0A/* LF */) { state.position++; } else if (ch === 0x0D/* CR */) { state.position++; if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { state.position++; } } else { throwError(state, 'a line break is expected'); } state.line += 1; state.lineStart = state.position; state.firstTabInLine = -1; } function skipSeparationSpace(state, allowComments, checkIndent) { var lineBreaks = 0, ch = state.input.charCodeAt(state.position); while (ch !== 0) { while (is_WHITE_SPACE(ch)) { if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) { state.firstTabInLine = state.position; } ch = state.input.charCodeAt(++state.position); } if (allowComments && ch === 0x23/* # */) { do { ch = state.input.charCodeAt(++state.position); } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); } if (is_EOL(ch)) { readLineBreak(state); ch = state.input.charCodeAt(state.position); lineBreaks++; state.lineIndent = 0; while (ch === 0x20/* Space */) { state.lineIndent++; ch = state.input.charCodeAt(++state.position); } } else { break; } } if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { throwWarning(state, 'deficient indentation'); } return lineBreaks; } function testDocumentSeparator(state) { var _position = state.position, ch; ch = state.input.charCodeAt(_position); // Condition state.position === state.lineStart is tested // in parent on each call, for efficiency. No needs to test here again. if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) { _position += 3; ch = state.input.charCodeAt(_position); if (ch === 0 || is_WS_OR_EOL(ch)) { return true; } } return false; } function writeFoldedLines(state, count) { if (count === 1) { state.result += ' '; } else if (count > 1) { state.result += common.repeat('\n', count - 1); } } function readPlainScalar(state, nodeIndent, withinFlowCollection) { var preceding, following, captureStart, captureEnd, hasPendingContent, _line, _lineStart, _lineIndent, _kind = state.kind, _result = state.result, ch; ch = state.input.charCodeAt(state.position); if (is_WS_OR_EOL(ch) || is_FLOW_INDICATOR(ch) || ch === 0x23/* # */ || ch === 0x26/* & */ || ch === 0x2A/* * */ || ch === 0x21/* ! */ || ch === 0x7C/* | */ || ch === 0x3E/* > */ || ch === 0x27/* ' */ || ch === 0x22/* " */ || ch === 0x25/* % */ || ch === 0x40/* @ */ || ch === 0x60/* ` */) { return false; } if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) { return false; } } state.kind = 'scalar'; state.result = ''; captureStart = captureEnd = state.position; hasPendingContent = false; while (ch !== 0) { if (ch === 0x3A/* : */) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) { break; } } else if (ch === 0x23/* # */) { preceding = state.input.charCodeAt(state.position - 1); if (is_WS_OR_EOL(preceding)) { break; } } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || withinFlowCollection && is_FLOW_INDICATOR(ch)) { break; } else if (is_EOL(ch)) { _line = state.line; _lineStart = state.lineStart; _lineIndent = state.lineIndent; skipSeparationSpace(state, false, -1); if (state.lineIndent >= nodeIndent) { hasPendingContent = true; ch = state.input.charCodeAt(state.position); continue; } else { state.position = captureEnd; state.line = _line; state.lineStart = _lineStart; state.lineIndent = _lineIndent; break; } } if (hasPendingContent) { captureSegment(state, captureStart, captureEnd, false); writeFoldedLines(state, state.line - _line); captureStart = captureEnd = state.position; hasPendingContent = false; } if (!is_WHITE_SPACE(ch)) { captureEnd = state.position + 1; } ch = state.input.charCodeAt(++state.position); } captureSegment(state, captureStart, captureEnd, false); if (state.result) { return true; } state.kind = _kind; state.result = _result; return false; } function readSingleQuotedScalar(state, nodeIndent) { var ch, captureStart, captureEnd; ch = state.input.charCodeAt(state.position); if (ch !== 0x27/* ' */) { return false; } state.kind = 'scalar'; state.result = ''; state.position++; captureStart = captureEnd = state.position; while ((ch = state.input.charCodeAt(state.position)) !== 0) { if (ch === 0x27/* ' */) { captureSegment(state, captureStart, state.position, true); ch = state.input.charCodeAt(++state.position); if (ch === 0x27/* ' */) { captureStart = state.position; state.position++; captureEnd = state.position; } else { return true; } } else if (is_EOL(ch)) { captureSegment(state, captureStart, captureEnd, true); writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); captureStart = captureEnd = state.position; } else if (state.position === state.lineStart && testDocumentSeparator(state)) { throwError(state, 'unexpected end of the document within a single quoted scalar'); } else { state.position++; captureEnd = state.position; } } throwError(state, 'unexpected end of the stream within a single quoted scalar'); } function readDoubleQuotedScalar(state, nodeIndent) { var captureStart, captureEnd, hexLength, hexResult, tmp, ch; ch = state.input.charCodeAt(state.position); if (ch !== 0x22/* " */) { return false; } state.kind = 'scalar'; state.result = ''; state.position++; captureStart = captureEnd = state.position; while ((ch = state.input.charCodeAt(state.position)) !== 0) { if (ch === 0x22/* " */) { captureSegment(state, captureStart, state.position, true); state.position++; return true; } else if (ch === 0x5C/* \ */) { captureSegment(state, captureStart, state.position, true); ch = state.input.charCodeAt(++state.position); if (is_EOL(ch)) { skipSeparationSpace(state, false, nodeIndent); // TODO: rework to inline fn with no type cast? } else if (ch < 256 && simpleEscapeCheck[ch]) { state.result += simpleEscapeMap[ch]; state.position++; } else if ((tmp = escapedHexLen(ch)) > 0) { hexLength = tmp; hexResult = 0; for (; hexLength > 0; hexLength--) { ch = state.input.charCodeAt(++state.position); if ((tmp = fromHexCode(ch)) >= 0) { hexResult = (hexResult << 4) + tmp; } else { throwError(state, 'expected hexadecimal character'); } } state.result += charFromCodepoint(hexResult); state.position++; } else { throwError(state, 'unknown escape sequence'); } captureStart = captureEnd = state.position; } else if (is_EOL(ch)) { captureSegment(state, captureStart, captureEnd, true); writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); captureStart = captureEnd = state.position; } else if (state.position === state.lineStart && testDocumentSeparator(state)) { throwError(state, 'unexpected end of the document within a double quoted scalar'); } else { state.position++; captureEnd = state.position; } } throwError(state, 'unexpected end of the stream within a double quoted scalar'); } function readFlowCollection(state, nodeIndent) { var readNext = true, _line, _lineStart, _pos, _tag = state.tag, _result, _anchor = state.anchor, following, terminator, isPair, isExplicitPair, isMapping, overridableKeys = Object.create(null), keyNode, keyTag, valueNode, ch; ch = state.input.charCodeAt(state.position); if (ch === 0x5B/* [ */) { terminator = 0x5D;/* ] */ isMapping = false; _result = []; } else if (ch === 0x7B/* { */) { terminator = 0x7D;/* } */ isMapping = true; _result = {}; } else { return false; } if (state.anchor !== null) { state.anchorMap[state.anchor] = _result; } ch = state.input.charCodeAt(++state.position); while (ch !== 0) { skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if (ch === terminator) { state.position++; state.tag = _tag; state.anchor = _anchor; state.kind = isMapping ? 'mapping' : 'sequence'; state.result = _result; return true; } else if (!readNext) { throwError(state, 'missed comma between flow collection entries'); } else if (ch === 0x2C/* , */) { // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4 throwError(state, "expected the node content, but found ','"); } keyTag = keyNode = valueNode = null; isPair = isExplicitPair = false; if (ch === 0x3F/* ? */) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following)) { isPair = isExplicitPair = true; state.position++; skipSeparationSpace(state, true, nodeIndent); } } _line = state.line; // Save the current line. _lineStart = state.lineStart; _pos = state.position; composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); keyTag = state.tag; keyNode = state.result; skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { isPair = true; ch = state.input.charCodeAt(++state.position); skipSeparationSpace(state, true, nodeIndent); composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); valueNode = state.result; } if (isMapping) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); } else if (isPair) { _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); } else { _result.push(keyNode); } skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if (ch === 0x2C/* , */) { readNext = true; ch = state.input.charCodeAt(++state.position); } else { readNext = false; } } throwError(state, 'unexpected end of the stream within a flow collection'); } function readBlockScalar(state, nodeIndent) { var captureStart, folding, chomping = CHOMPING_CLIP, didReadContent = false, detectedIndent = false, textIndent = nodeIndent, emptyLines = 0, atMoreIndented = false, tmp, ch; ch = state.input.charCodeAt(state.position); if (ch === 0x7C/* | */) { folding = false; } else if (ch === 0x3E/* > */) { folding = true; } else { return false; } state.kind = 'scalar'; state.result = ''; while (ch !== 0) { ch = state.input.charCodeAt(++state.position); if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { if (CHOMPING_CLIP === chomping) { chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; } else { throwError(state, 'repeat of a chomping mode identifier'); } } else if ((tmp = fromDecimalCode(ch)) >= 0) { if (tmp === 0) { throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); } else if (!detectedIndent) { textIndent = nodeIndent + tmp - 1; detectedIndent = true; } else { throwError(state, 'repeat of an indentation width identifier'); } } else { break; } } if (is_WHITE_SPACE(ch)) { do { ch = state.input.charCodeAt(++state.position); } while (is_WHITE_SPACE(ch)); if (ch === 0x23/* # */) { do { ch = state.input.charCodeAt(++state.position); } while (!is_EOL(ch) && (ch !== 0)); } } while (ch !== 0) { readLineBreak(state); state.lineIndent = 0; ch = state.input.charCodeAt(state.position); while ((!detectedIndent || state.lineIndent < textIndent) && (ch === 0x20/* Space */)) { state.lineIndent++; ch = state.input.charCodeAt(++state.position); } if (!detectedIndent && state.lineIndent > textIndent) { textIndent = state.lineIndent; } if (is_EOL(ch)) { emptyLines++; continue; } // End of the scalar. if (state.lineIndent < textIndent) { // Perform the chomping. if (chomping === CHOMPING_KEEP) { state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); } else if (chomping === CHOMPING_CLIP) { if (didReadContent) { // i.e. only if the scalar is not empty. state.result += '\n'; } } // Break this `while` cycle and go to the funciton's epilogue. break; } // Folded style: use fancy rules to handle line breaks. if (folding) { // Lines starting with white space characters (more-indented lines) are not folded. if (is_WHITE_SPACE(ch)) { atMoreIndented = true; // except for the first content line (cf. Example 8.1) state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); // End of more-indented block. } else if (atMoreIndented) { atMoreIndented = false; state.result += common.repeat('\n', emptyLines + 1); // Just one line break - perceive as the same line. } else if (emptyLines === 0) { if (didReadContent) { // i.e. only if we have already read some scalar content. state.result += ' '; } // Several line breaks - perceive as different lines. } else { state.result += common.repeat('\n', emptyLines); } // Literal style: just add exact number of line breaks between content lines. } else { // Keep all line breaks except the header line break. state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); } didReadContent = true; detectedIndent = true; emptyLines = 0; captureStart = state.position; while (!is_EOL(ch) && (ch !== 0)) { ch = state.input.charCodeAt(++state.position); } captureSegment(state, captureStart, state.position, false); } return true; } function readBlockSequence(state, nodeIndent) { var _line, _tag = state.tag, _anchor = state.anchor, _result = [], following, detected = false, ch; // there is a leading tab before this token, so it can't be a block sequence/mapping; // it can still be flow sequence/mapping or a scalar if (state.firstTabInLine !== -1) return false; if (state.anchor !== null) { state.anchorMap[state.anchor] = _result; } ch = state.input.charCodeAt(state.position); while (ch !== 0) { if (state.firstTabInLine !== -1) { state.position = state.firstTabInLine; throwError(state, 'tab characters must not be used in indentation'); } if (ch !== 0x2D/* - */) { break; } following = state.input.charCodeAt(state.position + 1); if (!is_WS_OR_EOL(following)) { break; } detected = true; state.position++; if (skipSeparationSpace(state, true, -1)) { if (state.lineIndent <= nodeIndent) { _result.push(null); ch = state.input.charCodeAt(state.position); continue; } } _line = state.line; composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); _result.push(state.result); skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { throwError(state, 'bad indentation of a sequence entry'); } else if (state.lineIndent < nodeIndent) { break; } } if (detected) { state.tag = _tag; state.anchor = _anchor; state.kind = 'sequence'; state.result = _result; return true; } return false; } function readBlockMapping(state, nodeIndent, flowIndent) { var following, allowCompact, _line, _keyLine, _keyLineStart, _keyPos, _tag = state.tag, _anchor = state.anchor, _result = {}, overridableKeys = Object.create(null), keyTag = null, keyNode = null, valueNode = null, atExplicitKey = false, detected = false, ch; // there is a leading tab before this token, so it can't be a block sequence/mapping; // it can still be flow sequence/mapping or a scalar if (state.firstTabInLine !== -1) return false; if (state.anchor !== null) { state.anchorMap[state.anchor] = _result; } ch = state.input.charCodeAt(state.position); while (ch !== 0) { if (!atExplicitKey && state.firstTabInLine !== -1) { state.position = state.firstTabInLine; throwError(state, 'tab characters must not be used in indentation'); } following = state.input.charCodeAt(state.position + 1); _line = state.line; // Save the current line. // // Explicit notation case. There are two separate blocks: // first for the key (denoted by "?") and second for the value (denoted by ":") // if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { if (ch === 0x3F/* ? */) { if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } detected = true; atExplicitKey = true; allowCompact = true; } else if (atExplicitKey) { // i.e. 0x3A/* : */ === character after the explicit key. atExplicitKey = false; allowCompact = true; } else { throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); } state.position += 1; ch = following; // // Implicit notation case. Flow-style node as the key first, then ":", and the value. // } else { _keyLine = state.line; _keyLineStart = state.lineStart; _keyPos = state.position; if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { // Neither implicit nor explicit notation. // Reading is done. Go to the epilogue. break; } if (state.line === _line) { ch = state.input.charCodeAt(state.position); while (is_WHITE_SPACE(ch)) { ch = state.input.charCodeAt(++state.position); } if (ch === 0x3A/* : */) { ch = state.input.charCodeAt(++state.position); if (!is_WS_OR_EOL(ch)) { throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); } if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } detected = true; atExplicitKey = false; allowCompact = false; keyTag = state.tag; keyNode = state.result; } else if (detected) { throwError(state, 'can not read an implicit mapping pair; a colon is missed'); } else { state.tag = _tag; state.anchor = _anchor; return true; // Keep the result of `composeNode`. } } else if (detected) { throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); } else { state.tag = _tag; state.anchor = _anchor; return true; // Keep the result of `composeNode`. } } // // Common reading code for both explicit and implicit notations. // if (state.line === _line || state.lineIndent > nodeIndent) { if (atExplicitKey) { _keyLine = state.line; _keyLineStart = state.lineStart; _keyPos = state.position; } if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { if (atExplicitKey) { keyNode = state.result; } else { valueNode = state.result; } } if (!atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); } if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { throwError(state, 'bad indentation of a mapping entry'); } else if (state.lineIndent < nodeIndent) { break; } } // // Epilogue. // // Special case: last mapping's node contains only the key in explicit notation. if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); } // Expose the resulting mapping. if (detected) { state.tag = _tag; state.anchor = _anchor; state.kind = 'mapping'; state.result = _result; } return detected; } function readTagProperty(state) { var _position, isVerbatim = false, isNamed = false, tagHandle, tagName, ch; ch = state.input.charCodeAt(state.position); if (ch !== 0x21/* ! */) return false; if (state.tag !== null) { throwError(state, 'duplication of a tag property'); } ch = state.input.charCodeAt(++state.position); if (ch === 0x3C/* < */) { isVerbatim = true; ch = state.input.charCodeAt(++state.position); } else if (ch === 0x21/* ! */) { isNamed = true; tagHandle = '!!'; ch = state.input.charCodeAt(++state.position); } else { tagHandle = '!'; } _position = state.position; if (isVerbatim) { do { ch = state.input.charCodeAt(++state.position); } while (ch !== 0 && ch !== 0x3E/* > */); if (state.position < state.length) { tagName = state.input.slice(_position, state.position); ch = state.input.charCodeAt(++state.position); } else { throwError(state, 'unexpected end of the stream within a verbatim tag'); } } else { while (ch !== 0 && !is_WS_OR_EOL(ch)) { if (ch === 0x21/* ! */) { if (!isNamed) { tagHandle = state.input.slice(_position - 1, state.position + 1); if (!PATTERN_TAG_HANDLE.test(tagHandle)) { throwError(state, 'named tag handle cannot contain such characters'); } isNamed = true; _position = state.position + 1; } else { throwError(state, 'tag suffix cannot contain exclamation marks'); } } ch = state.input.charCodeAt(++state.position); } tagName = state.input.slice(_position, state.position); if (PATTERN_FLOW_INDICATORS.test(tagName)) { throwError(state, 'tag suffix cannot contain flow indicator characters'); } } if (tagName && !PATTERN_TAG_URI.test(tagName)) { throwError(state, 'tag name cannot contain such characters: ' + tagName); } try { tagName = decodeURIComponent(tagName); } catch (err) { throwError(state, 'tag name is malformed: ' + tagName); } if (isVerbatim) { state.tag = tagName; } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { state.tag = state.tagMap[tagHandle] + tagName; } else if (tagHandle === '!') { state.tag = '!' + tagName; } else if (tagHandle === '!!') { state.tag = 'tag:yaml.org,2002:' + tagName; } else { throwError(state, 'undeclared tag handle "' + tagHandle + '"'); } return true; } function readAnchorProperty(state) { var _position, ch; ch = state.input.charCodeAt(state.position); if (ch !== 0x26/* & */) return false; if (state.anchor !== null) { throwError(state, 'duplication of an anchor property'); } ch = state.input.charCodeAt(++state.position); _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { ch = state.input.charCodeAt(++state.position); } if (state.position === _position) { throwError(state, 'name of an anchor node must contain at least one character'); } state.anchor = state.input.slice(_position, state.position); return true; } function readAlias(state) { var _position, alias, ch; ch = state.input.charCodeAt(state.position); if (ch !== 0x2A/* * */) return false; ch = state.input.charCodeAt(++state.position); _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { ch = state.input.charCodeAt(++state.position); } if (state.position === _position) { throwError(state, 'name of an alias node must contain at least one character'); } alias = state.input.slice(_position, state.position); if (!_hasOwnProperty.call(state.anchorMap, alias)) { throwError(state, 'unidentified alias "' + alias + '"'); } state.result = state.anchorMap[alias]; skipSeparationSpace(state, true, -1); return true; } function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { var allowBlockStyles, allowBlockScalars, allowBlockCollections, indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { indentStatus = 1; } else if (state.lineIndent === parentIndent) { indentStatus = 0; } else if (state.lineIndent < parentIndent) { indentStatus = -1; } } } if (indentStatus === 1) { while (readTagProperty(state) || readAnchorProperty(state)) { if (skipSeparationSpace(state, true, -1)) { atNewLine = true; allowBlockCollections = allowBlockStyles; if (state.lineIndent > parentIndent) { indentStatus = 1; } else if (state.lineIndent === parentIndent) { indentStatus = 0; } else if (state.lineIndent < parentIndent) { indentStatus = -1; } } else { allowBlockCollections = false; } } } if (allowBlockCollections) { allowBlockCollections = atNewLine || allowCompact; } if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { flowIndent = parentIndent; } else { flowIndent = parentIndent + 1; } blockIndent = state.position - state.lineStart; if (indentStatus === 1) { if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) { hasContent = true; } else { if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) { hasContent = true; } else if (readAlias(state)) { hasContent = true; if (state.tag !== null || state.anchor !== null) { throwError(state, 'alias node should not have any properties'); } } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { hasContent = true; if (state.tag === null) { state.tag = '?'; } } if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } } } else if (indentStatus === 0) { // Special case: block sequences are allowed to have same indentation level as the parent. // http://www.yaml.org/spec/1.2/spec.html#id2799784 hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); } } if (state.tag === null) { if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } } else if (state.tag === '?') { // Implicit resolving is not allowed for non-scalar types, and '?' // non-specific tag is only automatically assigned to plain scalars. // // We only need to check kind conformity in case user explicitly assigns '?' // tag, for example like this: "! [0]" // if (state.result !== null && state.kind !== 'scalar') { throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); } for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { type = state.implicitTypes[typeIndex]; if (type.resolve(state.result)) { // `state.result` updated in resolver if matched state.result = type.construct(state.result); state.tag = type.tag; if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } break; } } } else if (state.tag !== '!') { if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { type = state.typeMap[state.kind || 'fallback'][state.tag]; } else { // looking for multi type type = null; typeList = state.typeMap.multi[state.kind || 'fallback']; for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { type = typeList[typeIndex]; break; } } } if (!type) { throwError(state, 'unknown tag !<' + state.tag + '>'); } if (state.result !== null && type.kind !== state.kind) { throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); } if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); } else { state.result = type.construct(state.result, state.tag); if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } } } if (state.listener !== null) { state.listener('close', state); } return state.tag !== null || state.anchor !== null || hasContent; } function readDocument(state) { var documentStart = state.position, _position, directiveName, directiveArgs, hasDirectives = false, ch; state.version = null; state.checkLineBreaks = state.legacy; state.tagMap = Object.create(null); state.anchorMap = Object.create(null); while ((ch = state.input.charCodeAt(state.position)) !== 0) { skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); if (state.lineIndent > 0 || ch !== 0x25/* % */) { break; } hasDirectives = true; ch = state.input.charCodeAt(++state.position); _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch)) { ch = state.input.charCodeAt(++state.position); } directiveName = state.input.slice(_position, state.position); directiveArgs = []; if (directiveName.length < 1) { throwError(state, 'directive name must not be less than one character in length'); } while (ch !== 0) { while (is_WHITE_SPACE(ch)) { ch = state.input.charCodeAt(++state.position); } if (ch === 0x23/* # */) { do { ch = state.input.charCodeAt(++state.position); } while (ch !== 0 && !is_EOL(ch)); break; } if (is_EOL(ch)) break; _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch)) { ch = state.input.charCodeAt(++state.position); } directiveArgs.push(state.input.slice(_position, state.position)); } if (ch !== 0) readLineBreak(state); if (_hasOwnProperty.call(directiveHandlers, directiveName)) { directiveHandlers[directiveName](state, directiveName, directiveArgs); } else { throwWarning(state, 'unknown document directive "' + directiveName + '"'); } } skipSeparationSpace(state, true, -1); if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 0x2D/* - */ && state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { state.position += 3; skipSeparationSpace(state, true, -1); } else if (hasDirectives) { throwError(state, 'directives end mark is expected'); } composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); skipSeparationSpace(state, true, -1); if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { throwWarning(state, 'non-ASCII line breaks are interpreted as content'); } state.documents.push(state.result); if (state.position === state.lineStart && testDocumentSeparator(state)) { if (state.input.charCodeAt(state.position) === 0x2E/* . */) { state.position += 3; skipSeparationSpace(state, true, -1); } return; } if (state.position < (state.length - 1)) { throwError(state, 'end of the stream or a document separator is expected'); } else { return; } } function loadDocuments(input, options) { input = String(input); options = options || {}; if (input.length !== 0) { // Add tailing `\n` if not exists if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { input += '\n'; } // Strip BOM if (input.charCodeAt(0) === 0xFEFF) { input = input.slice(1); } } var state = new State(input, options); var nullpos = input.indexOf('\0'); if (nullpos !== -1) { state.position = nullpos; throwError(state, 'null byte is not allowed in input'); } // Use 0 as string terminator. That significantly simplifies bounds check. state.input += '\0'; while (state.input.charCodeAt(state.position) === 0x20/* Space */) { state.lineIndent += 1; state.position += 1; } while (state.position < (state.length - 1)) { readDocument(state); } return state.documents; } function loadAll(input, iterator, options) { if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { options = iterator; iterator = null; } var documents = loadDocuments(input, options); if (typeof iterator !== 'function') { return documents; } for (var index = 0, length = documents.length; index < length; index += 1) { iterator(documents[index]); } } function load(input, options) { var documents = loadDocuments(input, options); if (documents.length === 0) { /*eslint-disable no-undefined*/ return undefined; } else if (documents.length === 1) { return documents[0]; } throw new YAMLException('expected a single document in the stream, but found more'); } module.exports.loadAll = loadAll; module.exports.load = load; /***/ }), /***/ 13646: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*eslint-disable max-len*/ var YAMLException = __webpack_require__(5548); var Type = __webpack_require__(85460); function compileList(schema, name) { var result = []; schema[name].forEach(function (currentType) { var newIndex = result.length; result.forEach(function (previousType, previousIndex) { if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) { newIndex = previousIndex; } }); result[newIndex] = currentType; }); return result; } function compileMap(/* lists... */) { var result = { scalar: {}, sequence: {}, mapping: {}, fallback: {}, multi: { scalar: [], sequence: [], mapping: [], fallback: [] } }, index, length; function collectType(type) { if (type.multi) { result.multi[type.kind].push(type); result.multi['fallback'].push(type); } else { result[type.kind][type.tag] = result['fallback'][type.tag] = type; } } for (index = 0, length = arguments.length; index < length; index += 1) { arguments[index].forEach(collectType); } return result; } function Schema(definition) { return this.extend(definition); } Schema.prototype.extend = function extend(definition) { var implicit = []; var explicit = []; if (definition instanceof Type) { // Schema.extend(type) explicit.push(definition); } else if (Array.isArray(definition)) { // Schema.extend([ type1, type2, ... ]) explicit = explicit.concat(definition); } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] }) if (definition.implicit) implicit = implicit.concat(definition.implicit); if (definition.explicit) explicit = explicit.concat(definition.explicit); } else { throw new YAMLException('Schema.extend argument should be a Type, [ Type ], ' + 'or a schema definition ({ implicit: [...], explicit: [...] })'); } implicit.forEach(function (type) { if (!(type instanceof Type)) { throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); } if (type.loadKind && type.loadKind !== 'scalar') { throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); } if (type.multi) { throw new YAMLException('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.'); } }); explicit.forEach(function (type) { if (!(type instanceof Type)) { throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); } }); var result = Object.create(Schema.prototype); result.implicit = (this.implicit || []).concat(implicit); result.explicit = (this.explicit || []).concat(explicit); result.compiledImplicit = compileList(result, 'implicit'); result.compiledExplicit = compileList(result, 'explicit'); result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); return result; }; module.exports = Schema; /***/ }), /***/ 73303: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Standard YAML's Core schema. // http://www.yaml.org/spec/1.2/spec.html#id2804923 // // NOTE: JS-YAML does not support schema-specific tag resolution restrictions. // So, Core schema has no distinctions from JSON schema is JS-YAML. module.exports = __webpack_require__(85965); /***/ }), /***/ 24138: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // JS-YAML's default schema for `safeLoad` function. // It is not described in the YAML specification. // // This schema is based on standard YAML's Core schema and includes most of // extra types described at YAML tag repository. (http://yaml.org/type/) module.exports = __webpack_require__(73303).extend({ implicit: [ __webpack_require__(78301), __webpack_require__(76222) ], explicit: [ __webpack_require__(50180), __webpack_require__(15887), __webpack_require__(62089), __webpack_require__(5292) ] }); /***/ }), /***/ 34246: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Standard YAML's Failsafe schema. // http://www.yaml.org/spec/1.2/spec.html#id2802346 var Schema = __webpack_require__(13646); module.exports = new Schema({ explicit: [ __webpack_require__(54473), __webpack_require__(3832), __webpack_require__(31559) ] }); /***/ }), /***/ 85965: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Standard YAML's JSON schema. // http://www.yaml.org/spec/1.2/spec.html#id2803231 // // NOTE: JS-YAML does not support schema-specific tag resolution restrictions. // So, this schema is not such strict as defined in the YAML specification. // It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. module.exports = __webpack_require__(34246).extend({ implicit: [ __webpack_require__(62116), __webpack_require__(62246), __webpack_require__(63014), __webpack_require__(98118) ] }); /***/ }), /***/ 32564: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var common = __webpack_require__(69381); // get snippet for a single line, respecting maxLength function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { var head = ''; var tail = ''; var maxHalfLength = Math.floor(maxLineLength / 2) - 1; if (position - lineStart > maxHalfLength) { head = ' ... '; lineStart = position - maxHalfLength + head.length; } if (lineEnd - position > maxHalfLength) { tail = ' ...'; lineEnd = position + maxHalfLength - tail.length; } return { str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, pos: position - lineStart + head.length // relative position }; } function padStart(string, max) { return common.repeat(' ', max - string.length) + string; } function makeSnippet(mark, options) { options = Object.create(options || null); if (!mark.buffer) return null; if (!options.maxLength) options.maxLength = 79; if (typeof options.indent !== 'number') options.indent = 1; if (typeof options.linesBefore !== 'number') options.linesBefore = 3; if (typeof options.linesAfter !== 'number') options.linesAfter = 2; var re = /\r?\n|\r|\0/g; var lineStarts = [ 0 ]; var lineEnds = []; var match; var foundLineNo = -1; while ((match = re.exec(mark.buffer))) { lineEnds.push(match.index); lineStarts.push(match.index + match[0].length); if (mark.position <= match.index && foundLineNo < 0) { foundLineNo = lineStarts.length - 2; } } if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; var result = '', i, line; var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); for (i = 1; i <= options.linesBefore; i++) { if (foundLineNo - i < 0) break; line = getLine( mark.buffer, lineStarts[foundLineNo - i], lineEnds[foundLineNo - i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), maxLineLength ); result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + ' | ' + line.str + '\n' + result; } line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + ' | ' + line.str + '\n'; result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; for (i = 1; i <= options.linesAfter; i++) { if (foundLineNo + i >= lineEnds.length) break; line = getLine( mark.buffer, lineStarts[foundLineNo + i], lineEnds[foundLineNo + i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), maxLineLength ); result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + ' | ' + line.str + '\n'; } return result.replace(/\n$/, ''); } module.exports = makeSnippet; /***/ }), /***/ 85460: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var YAMLException = __webpack_require__(5548); var TYPE_CONSTRUCTOR_OPTIONS = [ 'kind', 'multi', 'resolve', 'construct', 'instanceOf', 'predicate', 'represent', 'representName', 'defaultStyle', 'styleAliases' ]; var YAML_NODE_KINDS = [ 'scalar', 'sequence', 'mapping' ]; function compileStyleAliases(map) { var result = {}; if (map !== null) { Object.keys(map).forEach(function (style) { map[style].forEach(function (alias) { result[String(alias)] = style; }); }); } return result; } function Type(tag, options) { options = options || {}; Object.keys(options).forEach(function (name) { if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); } }); // TODO: Add tag format check. this.options = options; // keep original options in case user wants to extend this type later this.tag = tag; this.kind = options['kind'] || null; this.resolve = options['resolve'] || function () { return true; }; this.construct = options['construct'] || function (data) { return data; }; this.instanceOf = options['instanceOf'] || null; this.predicate = options['predicate'] || null; this.represent = options['represent'] || null; this.representName = options['representName'] || null; this.defaultStyle = options['defaultStyle'] || null; this.multi = options['multi'] || false; this.styleAliases = compileStyleAliases(options['styleAliases'] || null); if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); } } module.exports = Type; /***/ }), /***/ 50180: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*eslint-disable no-bitwise*/ var Type = __webpack_require__(85460); // [ 64, 65, 66 ] -> [ padding, CR, LF ] var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; function resolveYamlBinary(data) { if (data === null) return false; var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; // Convert one by one. for (idx = 0; idx < max; idx++) { code = map.indexOf(data.charAt(idx)); // Skip CR/LF if (code > 64) continue; // Fail on illegal characters if (code < 0) return false; bitlen += 6; } // If there are any bits left, source was corrupted return (bitlen % 8) === 0; } function constructYamlBinary(data) { var idx, tailbits, input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan max = input.length, map = BASE64_MAP, bits = 0, result = []; // Collect by 6*4 bits (3 bytes) for (idx = 0; idx < max; idx++) { if ((idx % 4 === 0) && idx) { result.push((bits >> 16) & 0xFF); result.push((bits >> 8) & 0xFF); result.push(bits & 0xFF); } bits = (bits << 6) | map.indexOf(input.charAt(idx)); } // Dump tail tailbits = (max % 4) * 6; if (tailbits === 0) { result.push((bits >> 16) & 0xFF); result.push((bits >> 8) & 0xFF); result.push(bits & 0xFF); } else if (tailbits === 18) { result.push((bits >> 10) & 0xFF); result.push((bits >> 2) & 0xFF); } else if (tailbits === 12) { result.push((bits >> 4) & 0xFF); } return new Uint8Array(result); } function representYamlBinary(object /*, style*/) { var result = '', bits = 0, idx, tail, max = object.length, map = BASE64_MAP; // Convert every three bytes to 4 ASCII characters. for (idx = 0; idx < max; idx++) { if ((idx % 3 === 0) && idx) { result += map[(bits >> 18) & 0x3F]; result += map[(bits >> 12) & 0x3F]; result += map[(bits >> 6) & 0x3F]; result += map[bits & 0x3F]; } bits = (bits << 8) + object[idx]; } // Dump tail tail = max % 3; if (tail === 0) { result += map[(bits >> 18) & 0x3F]; result += map[(bits >> 12) & 0x3F]; result += map[(bits >> 6) & 0x3F]; result += map[bits & 0x3F]; } else if (tail === 2) { result += map[(bits >> 10) & 0x3F]; result += map[(bits >> 4) & 0x3F]; result += map[(bits << 2) & 0x3F]; result += map[64]; } else if (tail === 1) { result += map[(bits >> 2) & 0x3F]; result += map[(bits << 4) & 0x3F]; result += map[64]; result += map[64]; } return result; } function isBinary(obj) { return Object.prototype.toString.call(obj) === '[object Uint8Array]'; } module.exports = new Type('tag:yaml.org,2002:binary', { kind: 'scalar', resolve: resolveYamlBinary, construct: constructYamlBinary, predicate: isBinary, represent: representYamlBinary }); /***/ }), /***/ 62246: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Type = __webpack_require__(85460); function resolveYamlBoolean(data) { if (data === null) return false; var max = data.length; return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); } function constructYamlBoolean(data) { return data === 'true' || data === 'True' || data === 'TRUE'; } function isBoolean(object) { return Object.prototype.toString.call(object) === '[object Boolean]'; } module.exports = new Type('tag:yaml.org,2002:bool', { kind: 'scalar', resolve: resolveYamlBoolean, construct: constructYamlBoolean, predicate: isBoolean, represent: { lowercase: function (object) { return object ? 'true' : 'false'; }, uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, camelcase: function (object) { return object ? 'True' : 'False'; } }, defaultStyle: 'lowercase' }); /***/ }), /***/ 98118: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var common = __webpack_require__(69381); var Type = __webpack_require__(85460); var YAML_FLOAT_PATTERN = new RegExp( // 2.5e4, 2.5 and integers '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + // .2e4, .2 // special case, seems not from spec '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + // .inf '|[-+]?\\.(?:inf|Inf|INF)' + // .nan '|\\.(?:nan|NaN|NAN))$'); function resolveYamlFloat(data) { if (data === null) return false; if (!YAML_FLOAT_PATTERN.test(data) || // Quick hack to not allow integers end with `_` // Probably should update regexp & check speed data[data.length - 1] === '_') { return false; } return true; } function constructYamlFloat(data) { var value, sign; value = data.replace(/_/g, '').toLowerCase(); sign = value[0] === '-' ? -1 : 1; if ('+-'.indexOf(value[0]) >= 0) { value = value.slice(1); } if (value === '.inf') { return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; } else if (value === '.nan') { return NaN; } return sign * parseFloat(value, 10); } var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; function representYamlFloat(object, style) { var res; if (isNaN(object)) { switch (style) { case 'lowercase': return '.nan'; case 'uppercase': return '.NAN'; case 'camelcase': return '.NaN'; } } else if (Number.POSITIVE_INFINITY === object) { switch (style) { case 'lowercase': return '.inf'; case 'uppercase': return '.INF'; case 'camelcase': return '.Inf'; } } else if (Number.NEGATIVE_INFINITY === object) { switch (style) { case 'lowercase': return '-.inf'; case 'uppercase': return '-.INF'; case 'camelcase': return '-.Inf'; } } else if (common.isNegativeZero(object)) { return '-0.0'; } res = object.toString(10); // JS stringifier can build scientific format without dots: 5e-100, // while YAML requres dot: 5.e-100. Fix it with simple hack return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; } function isFloat(object) { return (Object.prototype.toString.call(object) === '[object Number]') && (object % 1 !== 0 || common.isNegativeZero(object)); } module.exports = new Type('tag:yaml.org,2002:float', { kind: 'scalar', resolve: resolveYamlFloat, construct: constructYamlFloat, predicate: isFloat, represent: representYamlFloat, defaultStyle: 'lowercase' }); /***/ }), /***/ 63014: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var common = __webpack_require__(69381); var Type = __webpack_require__(85460); function isHexCode(c) { return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || ((0x61/* a */ <= c) && (c <= 0x66/* f */)); } function isOctCode(c) { return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); } function isDecCode(c) { return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); } function resolveYamlInteger(data) { if (data === null) return false; var max = data.length, index = 0, hasDigits = false, ch; if (!max) return false; ch = data[index]; // sign if (ch === '-' || ch === '+') { ch = data[++index]; } if (ch === '0') { // 0 if (index + 1 === max) return true; ch = data[++index]; // base 2, base 8, base 16 if (ch === 'b') { // base 2 index++; for (; index < max; index++) { ch = data[index]; if (ch === '_') continue; if (ch !== '0' && ch !== '1') return false; hasDigits = true; } return hasDigits && ch !== '_'; } if (ch === 'x') { // base 16 index++; for (; index < max; index++) { ch = data[index]; if (ch === '_') continue; if (!isHexCode(data.charCodeAt(index))) return false; hasDigits = true; } return hasDigits && ch !== '_'; } if (ch === 'o') { // base 8 index++; for (; index < max; index++) { ch = data[index]; if (ch === '_') continue; if (!isOctCode(data.charCodeAt(index))) return false; hasDigits = true; } return hasDigits && ch !== '_'; } } // base 10 (except 0) // value should not start with `_`; if (ch === '_') return false; for (; index < max; index++) { ch = data[index]; if (ch === '_') continue; if (!isDecCode(data.charCodeAt(index))) { return false; } hasDigits = true; } // Should have digits and should not end with `_` if (!hasDigits || ch === '_') return false; return true; } function constructYamlInteger(data) { var value = data, sign = 1, ch; if (value.indexOf('_') !== -1) { value = value.replace(/_/g, ''); } ch = value[0]; if (ch === '-' || ch === '+') { if (ch === '-') sign = -1; value = value.slice(1); ch = value[0]; } if (value === '0') return 0; if (ch === '0') { if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); if (value[1] === 'x') return sign * parseInt(value.slice(2), 16); if (value[1] === 'o') return sign * parseInt(value.slice(2), 8); } return sign * parseInt(value, 10); } function isInteger(object) { return (Object.prototype.toString.call(object)) === '[object Number]' && (object % 1 === 0 && !common.isNegativeZero(object)); } module.exports = new Type('tag:yaml.org,2002:int', { kind: 'scalar', resolve: resolveYamlInteger, construct: constructYamlInteger, predicate: isInteger, represent: { binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); }, decimal: function (obj) { return obj.toString(10); }, /* eslint-disable max-len */ hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } }, defaultStyle: 'decimal', styleAliases: { binary: [ 2, 'bin' ], octal: [ 8, 'oct' ], decimal: [ 10, 'dec' ], hexadecimal: [ 16, 'hex' ] } }); /***/ }), /***/ 31559: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Type = __webpack_require__(85460); module.exports = new Type('tag:yaml.org,2002:map', { kind: 'mapping', construct: function (data) { return data !== null ? data : {}; } }); /***/ }), /***/ 76222: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Type = __webpack_require__(85460); function resolveYamlMerge(data) { return data === '<<' || data === null; } module.exports = new Type('tag:yaml.org,2002:merge', { kind: 'scalar', resolve: resolveYamlMerge }); /***/ }), /***/ 62116: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Type = __webpack_require__(85460); function resolveYamlNull(data) { if (data === null) return true; var max = data.length; return (max === 1 && data === '~') || (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); } function constructYamlNull() { return null; } function isNull(object) { return object === null; } module.exports = new Type('tag:yaml.org,2002:null', { kind: 'scalar', resolve: resolveYamlNull, construct: constructYamlNull, predicate: isNull, represent: { canonical: function () { return '~'; }, lowercase: function () { return 'null'; }, uppercase: function () { return 'NULL'; }, camelcase: function () { return 'Null'; }, empty: function () { return ''; } }, defaultStyle: 'lowercase' }); /***/ }), /***/ 15887: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Type = __webpack_require__(85460); var _hasOwnProperty = Object.prototype.hasOwnProperty; var _toString = Object.prototype.toString; function resolveYamlOmap(data) { if (data === null) return true; var objectKeys = [], index, length, pair, pairKey, pairHasKey, object = data; for (index = 0, length = object.length; index < length; index += 1) { pair = object[index]; pairHasKey = false; if (_toString.call(pair) !== '[object Object]') return false; for (pairKey in pair) { if (_hasOwnProperty.call(pair, pairKey)) { if (!pairHasKey) pairHasKey = true; else return false; } } if (!pairHasKey) return false; if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); else return false; } return true; } function constructYamlOmap(data) { return data !== null ? data : []; } module.exports = new Type('tag:yaml.org,2002:omap', { kind: 'sequence', resolve: resolveYamlOmap, construct: constructYamlOmap }); /***/ }), /***/ 62089: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Type = __webpack_require__(85460); var _toString = Object.prototype.toString; function resolveYamlPairs(data) { if (data === null) return true; var index, length, pair, keys, result, object = data; result = new Array(object.length); for (index = 0, length = object.length; index < length; index += 1) { pair = object[index]; if (_toString.call(pair) !== '[object Object]') return false; keys = Object.keys(pair); if (keys.length !== 1) return false; result[index] = [ keys[0], pair[keys[0]] ]; } return true; } function constructYamlPairs(data) { if (data === null) return []; var index, length, pair, keys, result, object = data; result = new Array(object.length); for (index = 0, length = object.length; index < length; index += 1) { pair = object[index]; keys = Object.keys(pair); result[index] = [ keys[0], pair[keys[0]] ]; } return result; } module.exports = new Type('tag:yaml.org,2002:pairs', { kind: 'sequence', resolve: resolveYamlPairs, construct: constructYamlPairs }); /***/ }), /***/ 3832: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Type = __webpack_require__(85460); module.exports = new Type('tag:yaml.org,2002:seq', { kind: 'sequence', construct: function (data) { return data !== null ? data : []; } }); /***/ }), /***/ 5292: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Type = __webpack_require__(85460); var _hasOwnProperty = Object.prototype.hasOwnProperty; function resolveYamlSet(data) { if (data === null) return true; var key, object = data; for (key in object) { if (_hasOwnProperty.call(object, key)) { if (object[key] !== null) return false; } } return true; } function constructYamlSet(data) { return data !== null ? data : {}; } module.exports = new Type('tag:yaml.org,2002:set', { kind: 'mapping', resolve: resolveYamlSet, construct: constructYamlSet }); /***/ }), /***/ 54473: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Type = __webpack_require__(85460); module.exports = new Type('tag:yaml.org,2002:str', { kind: 'scalar', construct: function (data) { return data !== null ? data : ''; } }); /***/ }), /***/ 78301: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Type = __webpack_require__(85460); var YAML_DATE_REGEXP = new RegExp( '^([0-9][0-9][0-9][0-9])' + // [1] year '-([0-9][0-9])' + // [2] month '-([0-9][0-9])$'); // [3] day var YAML_TIMESTAMP_REGEXP = new RegExp( '^([0-9][0-9][0-9][0-9])' + // [1] year '-([0-9][0-9]?)' + // [2] month '-([0-9][0-9]?)' + // [3] day '(?:[Tt]|[ \\t]+)' + // ... '([0-9][0-9]?)' + // [4] hour ':([0-9][0-9])' + // [5] minute ':([0-9][0-9])' + // [6] second '(?:\\.([0-9]*))?' + // [7] fraction '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour '(?::([0-9][0-9]))?))?$'); // [11] tz_minute function resolveYamlTimestamp(data) { if (data === null) return false; if (YAML_DATE_REGEXP.exec(data) !== null) return true; if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; return false; } function constructYamlTimestamp(data) { var match, year, month, day, hour, minute, second, fraction = 0, delta = null, tz_hour, tz_minute, date; match = YAML_DATE_REGEXP.exec(data); if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); if (match === null) throw new Error('Date resolve error'); // match: [1] year [2] month [3] day year = +(match[1]); month = +(match[2]) - 1; // JS month starts with 0 day = +(match[3]); if (!match[4]) { // no hour return new Date(Date.UTC(year, month, day)); } // match: [4] hour [5] minute [6] second [7] fraction hour = +(match[4]); minute = +(match[5]); second = +(match[6]); if (match[7]) { fraction = match[7].slice(0, 3); while (fraction.length < 3) { // milli-seconds fraction += '0'; } fraction = +fraction; } // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute if (match[9]) { tz_hour = +(match[10]); tz_minute = +(match[11] || 0); delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds if (match[9] === '-') delta = -delta; } date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); if (delta) date.setTime(date.getTime() - delta); return date; } function representYamlTimestamp(object /*, style*/) { return object.toISOString(); } module.exports = new Type('tag:yaml.org,2002:timestamp', { kind: 'scalar', resolve: resolveYamlTimestamp, construct: constructYamlTimestamp, instanceOf: Date, represent: representYamlTimestamp }); /***/ }), /***/ 23419: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const ANY = Symbol('SemVer ANY') // hoisted class for cyclic dependency class Comparator { static get ANY () { return ANY } constructor (comp, options) { options = parseOptions(options) if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } comp = comp.trim().split(/\s+/).join(' ') debug('comparator', comp, options) this.options = options this.loose = !!options.loose this.parse(comp) if (this.semver === ANY) { this.value = '' } else { this.value = this.operator + this.semver.version } debug('comp', this) } parse (comp) { const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] const m = comp.match(r) if (!m) { throw new TypeError(`Invalid comparator: ${comp}`) } this.operator = m[1] !== undefined ? m[1] : '' if (this.operator === '=') { this.operator = '' } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY } else { this.semver = new SemVer(m[2], this.options.loose) } } toString () { return this.value } test (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY || version === ANY) { return true } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } return cmp(version, this.operator, this.semver, this.options) } intersects (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (this.operator === '') { if (this.value === '') { return true } return new Range(comp.value, options).test(this.value) } else if (comp.operator === '') { if (comp.value === '') { return true } return new Range(this.value, options).test(comp.semver) } options = parseOptions(options) // Special cases where nothing can possibly be lower if (options.includePrerelease && (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { return false } if (!options.includePrerelease && (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { return false } // Same direction increasing (> or >=) if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { return true } // Same direction decreasing (< or <=) if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { return true } // same SemVer and both sides are inclusive (<= or >=) if ( (this.semver.version === comp.semver.version) && this.operator.includes('=') && comp.operator.includes('=')) { return true } // opposite directions less than if (cmp(this.semver, '<', comp.semver, options) && this.operator.startsWith('>') && comp.operator.startsWith('<')) { return true } // opposite directions greater than if (cmp(this.semver, '>', comp.semver, options) && this.operator.startsWith('<') && comp.operator.startsWith('>')) { return true } return false } } module.exports = Comparator const parseOptions = __webpack_require__(87603) const { safeRe: re, t } = __webpack_require__(96002) const cmp = __webpack_require__(47774) const debug = __webpack_require__(20517) const SemVer = __webpack_require__(36586) const Range = __webpack_require__(46461) /***/ }), /***/ 46461: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SPACE_CHARACTERS = /\s+/g // hoisted class for cyclic dependency class Range { constructor (range, options) { options = parseOptions(options) if (range instanceof Range) { if ( range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease ) { return range } else { return new Range(range.raw, options) } } if (range instanceof Comparator) { // just put it in the set and return this.raw = range.value this.set = [[range]] this.formatted = undefined return this } this.options = options this.loose = !!options.loose this.includePrerelease = !!options.includePrerelease // First reduce all whitespace as much as possible so we do not have to rely // on potentially slow regexes like \s*. This is then stored and used for // future error messages as well. this.raw = range.trim().replace(SPACE_CHARACTERS, ' ') // First, split on || this.set = this.raw .split('||') // map the range to a 2d array of comparators .map(r => this.parseRange(r.trim())) // throw out any comparator lists that are empty // this generally means that it was not a valid range, which is allowed // in loose mode, but will still throw if the WHOLE range is invalid. .filter(c => c.length) if (!this.set.length) { throw new TypeError(`Invalid SemVer Range: ${this.raw}`) } // if we have any that are not the null set, throw out null sets. if (this.set.length > 1) { // keep the first one, in case they're all null sets const first = this.set[0] this.set = this.set.filter(c => !isNullSet(c[0])) if (this.set.length === 0) { this.set = [first] } else if (this.set.length > 1) { // if we have any that are *, then the range is just * for (const c of this.set) { if (c.length === 1 && isAny(c[0])) { this.set = [c] break } } } } this.formatted = undefined } get range () { if (this.formatted === undefined) { this.formatted = '' for (let i = 0; i < this.set.length; i++) { if (i > 0) { this.formatted += '||' } const comps = this.set[i] for (let k = 0; k < comps.length; k++) { if (k > 0) { this.formatted += ' ' } this.formatted += comps[k].toString().trim() } } } return this.formatted } format () { return this.range } toString () { return this.range } parseRange (range) { // memoize range parsing for performance. // this is a very hot path, and fully deterministic. const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE) const memoKey = memoOpts + ':' + range const cached = cache.get(memoKey) if (cached) { return cached } const loose = this.options.loose // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range) // `~ 1.2.3` => `~1.2.3` range = range.replace(re[t.TILDETRIM], tildeTrimReplace) debug('tilde trim', range) // `^ 1.2.3` => `^1.2.3` range = range.replace(re[t.CARETTRIM], caretTrimReplace) debug('caret trim', range) // At this point, the range is completely trimmed and // ready to be split into comparators. let rangeList = range .split(' ') .map(comp => parseComparator(comp, this.options)) .join(' ') .split(/\s+/) // >=0.0.0 is equivalent to * .map(comp => replaceGTE0(comp, this.options)) if (loose) { // in loose mode, throw out any that are not valid comparators rangeList = rangeList.filter(comp => { debug('loose invalid filter', comp, this.options) return !!comp.match(re[t.COMPARATORLOOSE]) }) } debug('range list', rangeList) // if any comparators are the null set, then replace with JUST null set // if more than one comparator, remove any * comparators // also, don't include the same comparator more than once const rangeMap = new Map() const comparators = rangeList.map(comp => new Comparator(comp, this.options)) for (const comp of comparators) { if (isNullSet(comp)) { return [comp] } rangeMap.set(comp.value, comp) } if (rangeMap.size > 1 && rangeMap.has('')) { rangeMap.delete('') } const result = [...rangeMap.values()] cache.set(memoKey, result) return result } intersects (range, options) { if (!(range instanceof Range)) { throw new TypeError('a Range is required') } return this.set.some((thisComparators) => { return ( isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => { return ( isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { return rangeComparators.every((rangeComparator) => { return thisComparator.intersects(rangeComparator, options) }) }) ) }) ) }) } // if ANY of the sets match ALL of its comparators, then pass test (version) { if (!version) { return false } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } for (let i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true } } return false } } module.exports = Range const LRU = __webpack_require__(59317) const cache = new LRU() const parseOptions = __webpack_require__(87603) const Comparator = __webpack_require__(23419) const debug = __webpack_require__(20517) const SemVer = __webpack_require__(36586) const { safeRe: re, t, comparatorTrimReplace, tildeTrimReplace, caretTrimReplace, } = __webpack_require__(96002) const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __webpack_require__(87613) const isNullSet = c => c.value === '<0.0.0-0' const isAny = c => c.value === '' // take a set of comparators and determine whether there // exists a version which can satisfy it const isSatisfiable = (comparators, options) => { let result = true const remainingComparators = comparators.slice() let testComparator = remainingComparators.pop() while (result && remainingComparators.length) { result = remainingComparators.every((otherComparator) => { return testComparator.intersects(otherComparator, options) }) testComparator = remainingComparators.pop() } return result } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. const parseComparator = (comp, options) => { debug('comp', comp, options) comp = replaceCarets(comp, options) debug('caret', comp) comp = replaceTildes(comp, options) debug('tildes', comp) comp = replaceXRanges(comp, options) debug('xrange', comp) comp = replaceStars(comp, options) debug('stars', comp) return comp } const isX = id => !id || id.toLowerCase() === 'x' || id === '*' // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 // ~0.0.1 --> >=0.0.1 <0.1.0-0 const replaceTildes = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceTilde(c, options)) .join(' ') } const replaceTilde = (comp, options) => { const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] return comp.replace(r, (_, M, m, p, pr) => { debug('tilde', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0 <${+M + 1}.0.0-0` } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0-0 ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` } else if (pr) { debug('replaceTilde pr', pr) ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } else { // ~1.2.3 == >=1.2.3 <1.3.0-0 ret = `>=${M}.${m}.${p } <${M}.${+m + 1}.0-0` } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 // ^1.2.3 --> >=1.2.3 <2.0.0-0 // ^1.2.0 --> >=1.2.0 <2.0.0-0 // ^0.0.1 --> >=0.0.1 <0.0.2-0 // ^0.1.0 --> >=0.1.0 <0.2.0-0 const replaceCarets = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceCaret(c, options)) .join(' ') } const replaceCaret = (comp, options) => { debug('caret', comp, options) const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] const z = options.includePrerelease ? '-0' : '' return comp.replace(r, (_, M, m, p, pr) => { debug('caret', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` } else if (isX(p)) { if (M === '0') { ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` } else { ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p}-${pr } <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p}-${pr } <${+M + 1}.0.0-0` } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p }${z} <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p }${z} <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p } <${+M + 1}.0.0-0` } } debug('caret return', ret) return ret }) } const replaceXRanges = (comp, options) => { debug('replaceXRanges', comp, options) return comp .split(/\s+/) .map((c) => replaceXRange(c, options)) .join(' ') } const replaceXRange = (comp, options) => { comp = comp.trim() const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] return comp.replace(r, (ret, gtlt, M, m, p, pr) => { debug('xRange', comp, ret, gtlt, M, m, p, pr) const xM = isX(M) const xm = xM || isX(m) const xp = xm || isX(p) const anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } // if we're including prereleases in the match, then we need // to fix this to -0, the lowest possible prerelease value pr = options.includePrerelease ? '-0' : '' if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0-0' } else { // nothing is forbidden ret = '*' } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0 } p = 0 if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 gtlt = '>=' if (xm) { M = +M + 1 m = 0 p = 0 } else { m = +m + 1 p = 0 } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<' if (xm) { M = +M + 1 } else { m = +m + 1 } } if (gtlt === '<') { pr = '-0' } ret = `${gtlt + M}.${m}.${p}${pr}` } else if (xm) { ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` } else if (xp) { ret = `>=${M}.${m}.0${pr } <${M}.${+m + 1}.0-0` } debug('xRange return', ret) return ret }) } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. const replaceStars = (comp, options) => { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp .trim() .replace(re[t.STAR], '') } const replaceGTE0 = (comp, options) => { debug('replaceGTE0', comp, options) return comp .trim() .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') } // This function is passed to string.replace(re[t.HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 // TODO build? const hyphenReplace = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => { if (isX(fM)) { from = '' } else if (isX(fm)) { from = `>=${fM}.0.0${incPr ? '-0' : ''}` } else if (isX(fp)) { from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` } else if (fpr) { from = `>=${from}` } else { from = `>=${from}${incPr ? '-0' : ''}` } if (isX(tM)) { to = '' } else if (isX(tm)) { to = `<${+tM + 1}.0.0-0` } else if (isX(tp)) { to = `<${tM}.${+tm + 1}.0-0` } else if (tpr) { to = `<=${tM}.${tm}.${tp}-${tpr}` } else if (incPr) { to = `<${tM}.${tm}.${+tp + 1}-0` } else { to = `<=${to}` } return `${from} ${to}`.trim() } const testSet = (set, version, options) => { for (let i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (let i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === Comparator.ANY) { continue } if (set[i].semver.prerelease.length > 0) { const allowed = set[i].semver if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } /***/ }), /***/ 36586: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const debug = __webpack_require__(20517) const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(87613) const { safeRe: re, safeSrc: src, t } = __webpack_require__(96002) const parseOptions = __webpack_require__(87603) const { compareIdentifiers } = __webpack_require__(86541) class SemVer { constructor (version, options) { options = parseOptions(options) if (version instanceof SemVer) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) } if (version.length > MAX_LENGTH) { throw new TypeError( `version is longer than ${MAX_LENGTH} characters` ) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose // this isn't actually relevant for versions, but keep it so that we // don't run into trouble passing this.options around. this.includePrerelease = !!options.includePrerelease const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) if (!m) { throw new TypeError(`Invalid Version: ${version}`) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map((id) => { if (/^[0-9]+$/.test(id)) { const num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } format () { this.version = `${this.major}.${this.minor}.${this.patch}` if (this.prerelease.length) { this.version += `-${this.prerelease.join('.')}` } return this.version } toString () { return this.version } compare (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { if (typeof other === 'string' && other === this.version) { return 0 } other = new SemVer(other, this.options) } if (other.version === this.version) { return 0 } return this.compareMain(other) || this.comparePre(other) } compareMain (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return ( compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) ) } comparePre (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } let i = 0 do { const a = this.prerelease[i] const b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } compareBuild (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } let i = 0 do { const a = this.build[i] const b = other.build[i] debug('build compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc (release, identifier, identifierBase) { if (release.startsWith('pre')) { if (!identifier && identifierBase === false) { throw new Error('invalid increment argument: identifier is empty') } // Avoid an invalid semver results if (identifier) { const r = new RegExp(`^${this.options.loose ? src[t.PRERELEASELOOSE] : src[t.PRERELEASE]}$`) const match = `-${identifier}`.match(r) if (!match || match[1] !== identifier) { throw new Error(`invalid identifier: ${identifier}`) } } } switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier, identifierBase) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier, identifierBase) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier, identifierBase) this.inc('pre', identifier, identifierBase) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier, identifierBase) } this.inc('pre', identifier, identifierBase) break case 'release': if (this.prerelease.length === 0) { throw new Error(`version ${this.raw} is not a prerelease`) } this.prerelease.length = 0 break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if ( this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0 ) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. case 'pre': { const base = Number(identifierBase) ? 1 : 0 if (this.prerelease.length === 0) { this.prerelease = [base] } else { let i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything if (identifier === this.prerelease.join('.') && identifierBase === false) { throw new Error('invalid increment argument: identifier already exists') } this.prerelease.push(base) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 let prerelease = [identifier, base] if (identifierBase === false) { prerelease = [identifier] } if (compareIdentifiers(this.prerelease[0], identifier) === 0) { if (isNaN(this.prerelease[1])) { this.prerelease = prerelease } } else { this.prerelease = prerelease } } break } default: throw new Error(`invalid increment argument: ${release}`) } this.raw = this.format() if (this.build.length) { this.raw += `+${this.build.join('.')}` } return this } } module.exports = SemVer /***/ }), /***/ 3278: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(23915) const clean = (version, options) => { const s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } module.exports = clean /***/ }), /***/ 47774: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const eq = __webpack_require__(76325) const neq = __webpack_require__(90253) const gt = __webpack_require__(38554) const gte = __webpack_require__(90925) const lt = __webpack_require__(39677) const lte = __webpack_require__(18487) const cmp = (a, op, b, loose) => { switch (op) { case '===': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a === b case '!==': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError(`Invalid operator: ${op}`) } } module.exports = cmp /***/ }), /***/ 91459: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(36586) const parse = __webpack_require__(23915) const { safeRe: re, t } = __webpack_require__(96002) const coerce = (version, options) => { if (version instanceof SemVer) { return version } if (typeof version === 'number') { version = String(version) } if (typeof version !== 'string') { return null } options = options || {} let match = null if (!options.rtl) { match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]) } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4' // // Walk through the string checking with a /g regexp // Manually set the index so as to pick up overlapping matches. // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL] let next while ((next = coerceRtlRegex.exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next } coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length } // leave it in a clean state coerceRtlRegex.lastIndex = -1 } if (match === null) { return null } const major = match[2] const minor = match[3] || '0' const patch = match[4] || '0' const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '' const build = options.includePrerelease && match[6] ? `+${match[6]}` : '' return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options) } module.exports = coerce /***/ }), /***/ 32294: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(36586) const compareBuild = (a, b, loose) => { const versionA = new SemVer(a, loose) const versionB = new SemVer(b, loose) return versionA.compare(versionB) || versionA.compareBuild(versionB) } module.exports = compareBuild /***/ }), /***/ 6834: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(63513) const compareLoose = (a, b) => compare(a, b, true) module.exports = compareLoose /***/ }), /***/ 63513: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(36586) const compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)) module.exports = compare /***/ }), /***/ 29020: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(23915) const diff = (version1, version2) => { const v1 = parse(version1, null, true) const v2 = parse(version2, null, true) const comparison = v1.compare(v2) if (comparison === 0) { return null } const v1Higher = comparison > 0 const highVersion = v1Higher ? v1 : v2 const lowVersion = v1Higher ? v2 : v1 const highHasPre = !!highVersion.prerelease.length const lowHasPre = !!lowVersion.prerelease.length if (lowHasPre && !highHasPre) { // Going from prerelease -> no prerelease requires some special casing // If the low version has only a major, then it will always be a major // Some examples: // 1.0.0-1 -> 1.0.0 // 1.0.0-1 -> 1.1.1 // 1.0.0-1 -> 2.0.0 if (!lowVersion.patch && !lowVersion.minor) { return 'major' } // If the main part has no difference if (lowVersion.compareMain(highVersion) === 0) { if (lowVersion.minor && !lowVersion.patch) { return 'minor' } return 'patch' } } // add the `pre` prefix if we are going to a prerelease version const prefix = highHasPre ? 'pre' : '' if (v1.major !== v2.major) { return prefix + 'major' } if (v1.minor !== v2.minor) { return prefix + 'minor' } if (v1.patch !== v2.patch) { return prefix + 'patch' } // high and low are preleases return 'prerelease' } module.exports = diff /***/ }), /***/ 76325: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(63513) const eq = (a, b, loose) => compare(a, b, loose) === 0 module.exports = eq /***/ }), /***/ 38554: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(63513) const gt = (a, b, loose) => compare(a, b, loose) > 0 module.exports = gt /***/ }), /***/ 90925: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(63513) const gte = (a, b, loose) => compare(a, b, loose) >= 0 module.exports = gte /***/ }), /***/ 46539: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(36586) const inc = (version, release, options, identifier, identifierBase) => { if (typeof (options) === 'string') { identifierBase = identifier identifier = options options = undefined } try { return new SemVer( version instanceof SemVer ? version.version : version, options ).inc(release, identifier, identifierBase).version } catch (er) { return null } } module.exports = inc /***/ }), /***/ 39677: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(63513) const lt = (a, b, loose) => compare(a, b, loose) < 0 module.exports = lt /***/ }), /***/ 18487: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(63513) const lte = (a, b, loose) => compare(a, b, loose) <= 0 module.exports = lte /***/ }), /***/ 35915: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(36586) const major = (a, loose) => new SemVer(a, loose).major module.exports = major /***/ }), /***/ 99004: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(36586) const minor = (a, loose) => new SemVer(a, loose).minor module.exports = minor /***/ }), /***/ 90253: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(63513) const neq = (a, b, loose) => compare(a, b, loose) !== 0 module.exports = neq /***/ }), /***/ 23915: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(36586) const parse = (version, options, throwErrors = false) => { if (version instanceof SemVer) { return version } try { return new SemVer(version, options) } catch (er) { if (!throwErrors) { return null } throw er } } module.exports = parse /***/ }), /***/ 36032: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(36586) const patch = (a, loose) => new SemVer(a, loose).patch module.exports = patch /***/ }), /***/ 1003: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(23915) const prerelease = (version, options) => { const parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } module.exports = prerelease /***/ }), /***/ 840: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(63513) const rcompare = (a, b, loose) => compare(b, a, loose) module.exports = rcompare /***/ }), /***/ 61579: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(32294) const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) module.exports = rsort /***/ }), /***/ 14358: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(46461) const satisfies = (version, range, options) => { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } module.exports = satisfies /***/ }), /***/ 84883: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(32294) const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) module.exports = sort /***/ }), /***/ 71416: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(23915) const valid = (version, options) => { const v = parse(version, options) return v ? v.version : null } module.exports = valid /***/ }), /***/ 33516: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // just pre-load all the stuff that index.js lazily exports const internalRe = __webpack_require__(96002) const constants = __webpack_require__(87613) const SemVer = __webpack_require__(36586) const identifiers = __webpack_require__(86541) const parse = __webpack_require__(23915) const valid = __webpack_require__(71416) const clean = __webpack_require__(3278) const inc = __webpack_require__(46539) const diff = __webpack_require__(29020) const major = __webpack_require__(35915) const minor = __webpack_require__(99004) const patch = __webpack_require__(36032) const prerelease = __webpack_require__(1003) const compare = __webpack_require__(63513) const rcompare = __webpack_require__(840) const compareLoose = __webpack_require__(6834) const compareBuild = __webpack_require__(32294) const sort = __webpack_require__(84883) const rsort = __webpack_require__(61579) const gt = __webpack_require__(38554) const lt = __webpack_require__(39677) const eq = __webpack_require__(76325) const neq = __webpack_require__(90253) const gte = __webpack_require__(90925) const lte = __webpack_require__(18487) const cmp = __webpack_require__(47774) const coerce = __webpack_require__(91459) const Comparator = __webpack_require__(23419) const Range = __webpack_require__(46461) const satisfies = __webpack_require__(14358) const toComparators = __webpack_require__(53325) const maxSatisfying = __webpack_require__(98720) const minSatisfying = __webpack_require__(61186) const minVersion = __webpack_require__(29523) const validRange = __webpack_require__(40434) const outside = __webpack_require__(58894) const gtr = __webpack_require__(67108) const ltr = __webpack_require__(20918) const intersects = __webpack_require__(55109) const simplifyRange = __webpack_require__(77554) const subset = __webpack_require__(90746) module.exports = { parse, valid, clean, inc, diff, major, minor, patch, prerelease, compare, rcompare, compareLoose, compareBuild, sort, rsort, gt, lt, eq, neq, gte, lte, cmp, coerce, Comparator, Range, satisfies, toComparators, maxSatisfying, minSatisfying, minVersion, validRange, outside, gtr, ltr, intersects, simplifyRange, subset, SemVer, re: internalRe.re, src: internalRe.src, tokens: internalRe.t, SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, RELEASE_TYPES: constants.RELEASE_TYPES, compareIdentifiers: identifiers.compareIdentifiers, rcompareIdentifiers: identifiers.rcompareIdentifiers, } /***/ }), /***/ 87613: /***/ ((module) => { // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. const SEMVER_SPEC_VERSION = '2.0.0' const MAX_LENGTH = 256 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. const MAX_SAFE_COMPONENT_LENGTH = 16 // Max safe length for a build identifier. The max length minus 6 characters for // the shortest version with a build 0.0.0+BUILD. const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 const RELEASE_TYPES = [ 'major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease', ] module.exports = { MAX_LENGTH, MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_SAFE_INTEGER, RELEASE_TYPES, SEMVER_SPEC_VERSION, FLAG_INCLUDE_PRERELEASE: 0b001, FLAG_LOOSE: 0b010, } /***/ }), /***/ 20517: /***/ ((module) => { const debug = ( typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ) ? (...args) => console.error('SEMVER', ...args) : () => {} module.exports = debug /***/ }), /***/ 86541: /***/ ((module) => { const numeric = /^[0-9]+$/ const compareIdentifiers = (a, b) => { const anum = numeric.test(a) const bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) module.exports = { compareIdentifiers, rcompareIdentifiers, } /***/ }), /***/ 59317: /***/ ((module) => { class LRUCache { constructor () { this.max = 1000 this.map = new Map() } get (key) { const value = this.map.get(key) if (value === undefined) { return undefined } else { // Remove the key from the map and add it to the end this.map.delete(key) this.map.set(key, value) return value } } delete (key) { return this.map.delete(key) } set (key, value) { const deleted = this.delete(key) if (!deleted && value !== undefined) { // If cache is full, delete the least recently used item if (this.map.size >= this.max) { const firstKey = this.map.keys().next().value this.delete(firstKey) } this.map.set(key, value) } return this } } module.exports = LRUCache /***/ }), /***/ 87603: /***/ ((module) => { // parse out just the options we care about const looseOption = Object.freeze({ loose: true }) const emptyOpts = Object.freeze({ }) const parseOptions = options => { if (!options) { return emptyOpts } if (typeof options !== 'object') { return looseOption } return options } module.exports = parseOptions /***/ }), /***/ 96002: /***/ ((module, exports, __webpack_require__) => { const { MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_LENGTH, } = __webpack_require__(87613) const debug = __webpack_require__(20517) exports = module.exports = {} // The actual regexps go on exports.re const re = exports.re = [] const safeRe = exports.safeRe = [] const src = exports.src = [] const safeSrc = exports.safeSrc = [] const t = exports.t = {} let R = 0 const LETTERDASHNUMBER = '[a-zA-Z0-9-]' // Replace some greedy regex tokens to prevent regex dos issues. These regex are // used internally via the safeRe object since all inputs in this library get // normalized first to trim and collapse all extra whitespace. The original // regexes are exported for userland consumption and lower level usage. A // future breaking change could export the safer regex only with a note that // all input should have extra whitespace removed. const safeRegexReplacements = [ ['\\s', 1], ['\\d', MAX_LENGTH], [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], ] const makeSafeRegex = (value) => { for (const [token, max] of safeRegexReplacements) { value = value .split(`${token}*`).join(`${token}{0,${max}}`) .split(`${token}+`).join(`${token}{1,${max}}`) } return value } const createToken = (name, value, isGlobal) => { const safe = makeSafeRegex(value) const index = R++ debug(name, index, value) t[name] = index src[index] = value safeSrc[index] = safe re[index] = new RegExp(value, isGlobal ? 'g' : undefined) safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) } // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') createToken('NUMERICIDENTIFIERLOOSE', '\\d+') // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) // ## Main Version // Three dot-separated numeric identifiers. createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`) createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] }|${src[t.NONNUMERICIDENTIFIER]})`) createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] }|${src[t.NONNUMERICIDENTIFIER]})`) // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] }(?:\\.${src[t.BUILDIDENTIFIER]})*))`) // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. createToken('FULLPLAIN', `v?${src[t.MAINVERSION] }${src[t.PRERELEASE]}?${ src[t.BUILD]}?`) createToken('FULL', `^${src[t.FULLPLAIN]}$`) // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] }${src[t.PRERELEASELOOSE]}?${ src[t.BUILD]}?`) createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) createToken('GTLT', '((?:<|>)?=?)') // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) // Coercion. // Extract anything that could conceivably be a part of a valid semver createToken('COERCEPLAIN', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`) createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`) createToken('COERCEFULL', src[t.COERCEPLAIN] + `(?:${src[t.PRERELEASE]})?` + `(?:${src[t.BUILD]})?` + `(?:$|[^\\d])`) createToken('COERCERTL', src[t.COERCE], true) createToken('COERCERTLFULL', src[t.COERCEFULL], true) // Tilde ranges. // Meaning is "reasonably at or greater than" createToken('LONETILDE', '(?:~>?)') createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) exports.tildeTrimReplace = '$1~' createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) // Caret ranges. // Meaning is "at least and backwards compatible with" createToken('LONECARET', '(?:\\^)') createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) exports.caretTrimReplace = '$1^' createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) // A simple gt/lt/eq thing, or just "" to indicate "any version" createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) exports.comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`) createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`) // Star ranges basically just allow anything at all. createToken('STAR', '(<|>)?=?\\s*\\*') // >=0.0.0 is like a star createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') /***/ }), /***/ 67108: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Determine if version is greater than all the versions possible in the range. const outside = __webpack_require__(58894) const gtr = (version, range, options) => outside(version, range, '>', options) module.exports = gtr /***/ }), /***/ 55109: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(46461) const intersects = (r1, r2, options) => { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2, options) } module.exports = intersects /***/ }), /***/ 20918: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const outside = __webpack_require__(58894) // Determine if version is less than all the versions possible in the range const ltr = (version, range, options) => outside(version, range, '<', options) module.exports = ltr /***/ }), /***/ 98720: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(36586) const Range = __webpack_require__(46461) const maxSatisfying = (versions, range, options) => { let max = null let maxSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } module.exports = maxSatisfying /***/ }), /***/ 61186: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(36586) const Range = __webpack_require__(46461) const minSatisfying = (versions, range, options) => { let min = null let minSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } module.exports = minSatisfying /***/ }), /***/ 29523: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(36586) const Range = __webpack_require__(46461) const gt = __webpack_require__(38554) const minVersion = (range, loose) => { range = new Range(range, loose) let minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let setMin = null comparators.forEach((comparator) => { // Clone to avoid manipulating the comparator's semver object. const compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!setMin || gt(compver, setMin)) { setMin = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error(`Unexpected operation: ${comparator.operator}`) } }) if (setMin && (!minver || gt(minver, setMin))) { minver = setMin } } if (minver && range.test(minver)) { return minver } return null } module.exports = minVersion /***/ }), /***/ 58894: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(36586) const Comparator = __webpack_require__(23419) const { ANY } = Comparator const Range = __webpack_require__(46461) const satisfies = __webpack_require__(14358) const gt = __webpack_require__(38554) const lt = __webpack_require__(39677) const lte = __webpack_require__(18487) const gte = __webpack_require__(90925) const outside = (version, range, hilo, options) => { version = new SemVer(version, options) range = new Range(range, options) let gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisfies the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let high = null let low = null comparators.forEach((comparator) => { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } module.exports = outside /***/ }), /***/ 77554: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // given a set of versions and a range, create a "simplified" range // that includes the same versions that the original range does // If the original range is shorter than the simplified one, return that. const satisfies = __webpack_require__(14358) const compare = __webpack_require__(63513) module.exports = (versions, range, options) => { const set = [] let first = null let prev = null const v = versions.sort((a, b) => compare(a, b, options)) for (const version of v) { const included = satisfies(version, range, options) if (included) { prev = version if (!first) { first = version } } else { if (prev) { set.push([first, prev]) } prev = null first = null } } if (first) { set.push([first, null]) } const ranges = [] for (const [min, max] of set) { if (min === max) { ranges.push(min) } else if (!max && min === v[0]) { ranges.push('*') } else if (!max) { ranges.push(`>=${min}`) } else if (min === v[0]) { ranges.push(`<=${max}`) } else { ranges.push(`${min} - ${max}`) } } const simplified = ranges.join(' || ') const original = typeof range.raw === 'string' ? range.raw : String(range) return simplified.length < original.length ? simplified : range } /***/ }), /***/ 90746: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(46461) const Comparator = __webpack_require__(23419) const { ANY } = Comparator const satisfies = __webpack_require__(14358) const compare = __webpack_require__(63513) // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: // - Every simple range `r1, r2, ...` is a null set, OR // - Every simple range `r1, r2, ...` which is not a null set is a subset of // some `R1, R2, ...` // // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: // - If c is only the ANY comparator // - If C is only the ANY comparator, return true // - Else if in prerelease mode, return false // - else replace c with `[>=0.0.0]` // - If C is only the ANY comparator // - if in prerelease mode, return true // - else replace C with `[>=0.0.0]` // - Let EQ be the set of = comparators in c // - If EQ is more than one, return true (null set) // - Let GT be the highest > or >= comparator in c // - Let LT be the lowest < or <= comparator in c // - If GT and LT, and GT.semver > LT.semver, return true (null set) // - If any C is a = range, and GT or LT are set, return false // - If EQ // - If GT, and EQ does not satisfy GT, return true (null set) // - If LT, and EQ does not satisfy LT, return true (null set) // - If EQ satisfies every C, return true // - Else return false // - If GT // - If GT.semver is lower than any > or >= comp in C, return false // - If GT is >=, and GT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the GT.semver tuple, return false // - If LT // - If LT.semver is greater than any < or <= comp in C, return false // - If LT is <=, and LT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the LT.semver tuple, return false // - Else return true const subset = (sub, dom, options = {}) => { if (sub === dom) { return true } sub = new Range(sub, options) dom = new Range(dom, options) let sawNonNull = false OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { const isSub = simpleSubset(simpleSub, simpleDom, options) sawNonNull = sawNonNull || isSub !== null if (isSub) { continue OUTER } } // the null set is a subset of everything, but null simple ranges in // a complex range should be ignored. so if we saw a non-null range, // then we know this isn't a subset, but if EVERY simple range was null, // then it is a subset. if (sawNonNull) { return false } } return true } const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] const minimumVersion = [new Comparator('>=0.0.0')] const simpleSubset = (sub, dom, options) => { if (sub === dom) { return true } if (sub.length === 1 && sub[0].semver === ANY) { if (dom.length === 1 && dom[0].semver === ANY) { return true } else if (options.includePrerelease) { sub = minimumVersionWithPreRelease } else { sub = minimumVersion } } if (dom.length === 1 && dom[0].semver === ANY) { if (options.includePrerelease) { return true } else { dom = minimumVersion } } const eqSet = new Set() let gt, lt for (const c of sub) { if (c.operator === '>' || c.operator === '>=') { gt = higherGT(gt, c, options) } else if (c.operator === '<' || c.operator === '<=') { lt = lowerLT(lt, c, options) } else { eqSet.add(c.semver) } } if (eqSet.size > 1) { return null } let gtltComp if (gt && lt) { gtltComp = compare(gt.semver, lt.semver, options) if (gtltComp > 0) { return null } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { return null } } // will iterate one or zero times for (const eq of eqSet) { if (gt && !satisfies(eq, String(gt), options)) { return null } if (lt && !satisfies(eq, String(lt), options)) { return null } for (const c of dom) { if (!satisfies(eq, String(c), options)) { return false } } return true } let higher, lower let hasDomLT, hasDomGT // if the subset has a prerelease, we need a comparator in the superset // with the same tuple and a prerelease, or it's not a subset let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false // exception: <1.2.3-0 is the same as <1.2.3 if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { needDomLTPre = false } for (const c of dom) { hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' if (gt) { if (needDomGTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { needDomGTPre = false } } if (c.operator === '>' || c.operator === '>=') { higher = higherGT(gt, c, options) if (higher === c && higher !== gt) { return false } } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { return false } } if (lt) { if (needDomLTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { needDomLTPre = false } } if (c.operator === '<' || c.operator === '<=') { lower = lowerLT(lt, c, options) if (lower === c && lower !== lt) { return false } } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { return false } } if (!c.operator && (lt || gt) && gtltComp !== 0) { return false } } // if there was a < or >, and nothing in the dom, then must be false // UNLESS it was limited by another range in the other direction. // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 if (gt && hasDomLT && !lt && gtltComp !== 0) { return false } if (lt && hasDomGT && !gt && gtltComp !== 0) { return false } // we needed a prerelease range in a specific tuple, but didn't get one // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, // because it includes prereleases in the 1.2.3 tuple if (needDomGTPre || needDomLTPre) { return false } return true } // >=1.2.3 is lower than >1.2.3 const higherGT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp > 0 ? a : comp < 0 ? b : b.operator === '>' && a.operator === '>=' ? b : a } // <=1.2.3 is higher than <1.2.3 const lowerLT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp < 0 ? a : comp > 0 ? b : b.operator === '<' && a.operator === '<=' ? b : a } module.exports = subset /***/ }), /***/ 53325: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(46461) // Mostly just for testing and legacy API reasons const toComparators = (range, options) => new Range(range, options).set .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) module.exports = toComparators /***/ }), /***/ 40434: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(46461) const validRange = (range, options) => { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } module.exports = validRange /***/ }), /***/ 16141: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.cMap = void 0; const pMap = __webpack_require__(86301); const event_loop_spinner_1 = __webpack_require__(77158); /** Run a function each element in an array, with some level of concurrency. * * Defaults to a small, finite concurrency, so as to not to "overload" the database * connection pool or the http client, both of which have small, internal limits. * * Can be used with async functions that don't yield; will yield for you, if necessary. */ async function cMap(input, mapper, options) { var _a; const concurrency = (_a = options === null || options === void 0 ? void 0 : options.concurrency) !== null && _a !== void 0 ? _a : 6; return await pMap(input, async (from) => { if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } return await mapper(from); }, { concurrency }); } exports.cMap = cMap; //# sourceMappingURL=c-map.js.map /***/ }), /***/ 54717: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.extractCorrectIdentifierBySemver = exports.extractNameAndIdentifier = void 0; const semver = __webpack_require__(33516); const extractNameAndIdentifier = (candidate) => { let name, identifier; if (candidate.includes('@')) { const index = candidate.indexOf('@', 1); name = candidate.slice(0, index); identifier = candidate.slice(index + 1); } else { name = candidate; identifier = 'unknown'; } return { name, identifier }; }; exports.extractNameAndIdentifier = extractNameAndIdentifier; // This function will choose an item in a particular list that satisfies the semver provided // i.e. possibleMatches = [debug@1.2.0, debug@2.2.6] and versionToMatch = debug@~2.2.0 // will result in debug@2.2.6 - This is required as yarn list does not have the resolved semver // in dependencies. const extractCorrectIdentifierBySemver = (possibleMatches, versionToMatch) => { const { name: nameToMatch, identifier: identifierToMatch } = (0, exports.extractNameAndIdentifier)(versionToMatch); const hasQualifiers = isNaN(parseInt(identifierToMatch[0])); if (!hasQualifiers) { return versionToMatch; } // Check for matching name, if only one found shortcircuit const match = possibleMatches .filter((name) => name.startsWith(nameToMatch)) .filter((name) => semver.satisfies((0, exports.extractNameAndIdentifier)(name).identifier, identifierToMatch)) .map((name) => ({ name, identifier: (0, exports.extractNameAndIdentifier)(name).identifier, })) .reduce((acc, item) => semver.gt(item.identifier, acc.identifier) ? item : acc); return match.name; }; exports.extractCorrectIdentifierBySemver = extractCorrectIdentifierBySemver; //# sourceMappingURL=cli-parser-utils.js.map /***/ }), /***/ 2463: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildDepGraphFromCliOutput = void 0; const dep_graph_1 = __webpack_require__(71479); const __1 = __webpack_require__(79790); const parsers_1 = __webpack_require__(64645); const cli_parser_utils_1 = __webpack_require__(54717); const yarn_info_parser_1 = __webpack_require__(7422); const yarn_list_parser_1 = __webpack_require__(40414); const buildDepGraphFromCliOutput = (rawCliOutput, lockfileContent, manifestFileContent) => { const manifestDependencies = JSON.parse(manifestFileContent).dependencies || {}; const lockfileType = (0, __1.getYarnLockfileType)(lockfileContent); const { name: rootName, version: rootVersion } = JSON.parse(manifestFileContent); const pkgManagerVersion = lockfileType === parsers_1.LockfileType.yarn ? '1' : '2'; // Build depMap object from the cli output const formattedCliOutput = pkgManagerVersion === '1' ? (0, yarn_list_parser_1.parseYarnListOutput)(rawCliOutput, manifestDependencies) : (0, yarn_info_parser_1.parseYarnInfoOutput)(rawCliOutput); const rootPkgInfo = rootName ? Object.assign({ name: rootName }, (rootVersion && { version: rootVersion })) : undefined; const pkgManager = { name: 'yarn', version: pkgManagerVersion, }; const builder = new dep_graph_1.DepGraphBuilder(pkgManager, rootPkgInfo); const { topLevelDeps, dependencies: depMap } = formattedCliOutput; // Add all nodes [...depMap.keys()].forEach((name) => { const { name: pkgName, identifier: pkgVersion } = (0, cli_parser_utils_1.extractNameAndIdentifier)(name); builder.addPkgNode({ name: pkgName, version: pkgVersion.split(':').pop() }, name); }); // Deal with root special case first const rootNodeId = builder.rootNodeId; topLevelDeps.forEach((dep) => builder.connectDep(rootNodeId, dep)); // Now rest of deps [...depMap.entries()].forEach(([parent, deps]) => { deps.forEach((dep) => { builder.connectDep(parent, dep); }); }); return builder.build(); }; exports.buildDepGraphFromCliOutput = buildDepGraphFromCliOutput; //# sourceMappingURL=index.js.map /***/ }), /***/ 7422: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseYarnInfoOutput = void 0; const parseYarnInfoOutput = (rawYarnInfoOutput) => { const formattedYarnInfo = rawYarnInfoOutput .split('\n') .filter(Boolean) .map((el) => JSON.parse(el)); const formattedInfoOutput = formattedYarnInfo.reduce((result, { value, children }) => { var _a; const dependencies = ((_a = children.Dependencies) === null || _a === void 0 ? void 0 : _a.map((el) => el.locator.replace(/@virtual:.*#/, '@'))) || []; return result.set(value, dependencies); }, new Map()); const rootWorkspaceKey = [...formattedInfoOutput.keys()].find((el) => el.includes('@workspace:.')); const topLevelDeps = formattedInfoOutput.get(rootWorkspaceKey) || []; // Now we have rootdeps we delete the key formattedInfoOutput.delete(rootWorkspaceKey); return { topLevelDeps, dependencies: formattedInfoOutput }; }; exports.parseYarnInfoOutput = parseYarnInfoOutput; //# sourceMappingURL=yarn-info-parser.js.map /***/ }), /***/ 40414: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseYarnListOutput = void 0; const cli_parser_utils_1 = __webpack_require__(54717); const parseYarnListOutput = (rawYarnListOutput, manifestDependencies) => { const formattedYarnList = JSON.parse(rawYarnListOutput).data.trees; // Reference to all (resolved) dep names to help cleanup in next step const names = formattedYarnList.map((tree) => tree.name); const formattedListOutput = formattedYarnList.reduce((result, tree) => { const dependencies = tree.children.map((child) => (0, cli_parser_utils_1.extractCorrectIdentifierBySemver)(names, child.name)); return result.set(tree.name, dependencies); }, new Map()); const topLevelDeps = getTopLevelDependencies(formattedListOutput, manifestDependencies); return { topLevelDeps, dependencies: formattedListOutput }; }; exports.parseYarnListOutput = parseYarnListOutput; const getTopLevelDependencies = (formattedListOutput, topLevelDeps) => { // This logic is to construct an item for the rootPkg because // we are dealing with a flat map so far so can't tell const names = [...formattedListOutput.keys()]; return Object.entries(topLevelDeps).map(([name, version]) => (0, cli_parser_utils_1.extractCorrectIdentifierBySemver)(names, `${name}@${version}`)); }; //# sourceMappingURL=yarn-list-parser.js.map /***/ }), /***/ 76123: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.config = void 0; const snyk_config_1 = __webpack_require__(8658); exports.config = (0, snyk_config_1.loadConfig)(__dirname + '../..'); //# sourceMappingURL=config.js.map /***/ }), /***/ 11110: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parsePkgJson = exports.parsePnpmWorkspace = exports.parsePnpmProject = exports.extractPkgsFromYarnLockV2 = exports.parseYarnLockV2Project = exports.buildDepGraphYarnLockV2Simple = exports.extractPkgsFromYarnLockV1 = exports.parseYarnLockV1WorkspaceProject = exports.buildDepGraphYarnLockV1WorkspaceCyclesPruned = exports.buildDepGraphYarnLockV1Simple = exports.buildDepGraphYarnLockV1SimpleCyclesPruned = exports.buildDepGraphYarnLockV1Workspace = exports.parseYarnLockV1Project = exports.parseNpmLockV2Project = void 0; const yarn_lock_v1_1 = __webpack_require__(20960); Object.defineProperty(exports, "parseYarnLockV1Project", ({ enumerable: true, get: function () { return yarn_lock_v1_1.parseYarnLockV1Project; } })); Object.defineProperty(exports, "parseYarnLockV1WorkspaceProject", ({ enumerable: true, get: function () { return yarn_lock_v1_1.parseYarnLockV1WorkspaceProject; } })); Object.defineProperty(exports, "buildDepGraphYarnLockV1SimpleCyclesPruned", ({ enumerable: true, get: function () { return yarn_lock_v1_1.buildDepGraphYarnLockV1SimpleCyclesPruned; } })); Object.defineProperty(exports, "buildDepGraphYarnLockV1Simple", ({ enumerable: true, get: function () { return yarn_lock_v1_1.buildDepGraphYarnLockV1Simple; } })); Object.defineProperty(exports, "buildDepGraphYarnLockV1WorkspaceCyclesPruned", ({ enumerable: true, get: function () { return yarn_lock_v1_1.buildDepGraphYarnLockV1WorkspaceCyclesPruned; } })); Object.defineProperty(exports, "buildDepGraphYarnLockV1Workspace", ({ enumerable: true, get: function () { return yarn_lock_v1_1.buildDepGraphYarnLockV1Workspace; } })); Object.defineProperty(exports, "extractPkgsFromYarnLockV1", ({ enumerable: true, get: function () { return yarn_lock_v1_1.extractPkgsFromYarnLockV1; } })); const yarn_lock_v2_1 = __webpack_require__(96470); Object.defineProperty(exports, "buildDepGraphYarnLockV2Simple", ({ enumerable: true, get: function () { return yarn_lock_v2_1.buildDepGraphYarnLockV2Simple; } })); Object.defineProperty(exports, "parseYarnLockV2Project", ({ enumerable: true, get: function () { return yarn_lock_v2_1.parseYarnLockV2Project; } })); Object.defineProperty(exports, "extractPkgsFromYarnLockV2", ({ enumerable: true, get: function () { return yarn_lock_v2_1.extractPkgsFromYarnLockV2; } })); const npm_lock_v2_1 = __webpack_require__(29088); Object.defineProperty(exports, "parseNpmLockV2Project", ({ enumerable: true, get: function () { return npm_lock_v2_1.parseNpmLockV2Project; } })); const pnpm_1 = __webpack_require__(97894); Object.defineProperty(exports, "parsePnpmProject", ({ enumerable: true, get: function () { return pnpm_1.parsePnpmProject; } })); Object.defineProperty(exports, "parsePnpmWorkspace", ({ enumerable: true, get: function () { return pnpm_1.parsePnpmWorkspace; } })); const util_1 = __webpack_require__(30631); Object.defineProperty(exports, "parsePkgJson", ({ enumerable: true, get: function () { return util_1.parsePkgJson; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 95651: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.extractPkgsFromNpmLockV2 = void 0; const extractPkgsFromNpmLockV2 = (pkgLockContent) => { return JSON.parse(pkgLockContent).packages; }; exports.extractPkgsFromNpmLockV2 = extractPkgsFromNpmLockV2; //# sourceMappingURL=extract-npm-lock-v2-pkgs.js.map /***/ }), /***/ 29088: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.matchOverrideKey = exports.getChildNodeKey = exports.buildDepGraphNpmLockV2 = exports.parseNpmLockV2Project = exports.extractPkgsFromNpmLockV2 = void 0; const extract_npm_lock_v2_pkgs_1 = __webpack_require__(95651); Object.defineProperty(exports, "extractPkgsFromNpmLockV2", ({ enumerable: true, get: function () { return extract_npm_lock_v2_pkgs_1.extractPkgsFromNpmLockV2; } })); const dep_graph_1 = __webpack_require__(71479); const util_1 = __webpack_require__(30631); const errors_1 = __webpack_require__(55622); const parsers_1 = __webpack_require__(64645); const semver = __webpack_require__(33516); const micromatch = __webpack_require__(70850); const pathUtil = __webpack_require__(71017); const event_loop_spinner_1 = __webpack_require__(77158); const parseNpmLockV2Project = async (pkgJsonContent, pkgLockContent, options) => { const { includeDevDeps, strictOutOfSync, includeOptionalDeps } = options; const pkgJson = (0, util_1.parsePkgJson)(pkgJsonContent); const pkgs = (0, extract_npm_lock_v2_pkgs_1.extractPkgsFromNpmLockV2)(pkgLockContent); const depgraph = await (0, exports.buildDepGraphNpmLockV2)(pkgs, pkgJson, { includeDevDeps, includeOptionalDeps, strictOutOfSync, }); return depgraph; }; exports.parseNpmLockV2Project = parseNpmLockV2Project; const buildDepGraphNpmLockV2 = async (npmLockPkgs, pkgJson, options) => { const { includeDevDeps, strictOutOfSync, includeOptionalDeps } = options; const depGraphBuilder = new dep_graph_1.DepGraphBuilder({ name: 'npm' }, { name: pkgJson.name, version: pkgJson.version }); const topLevelDeps = (0, util_1.getTopLevelDeps)(pkgJson, { includeDevDeps, includeOptionalDeps, includePeerDeps: true, }); const rootNode = { id: 'root-node', name: pkgJson.name, version: pkgJson.version, dependencies: topLevelDeps, isDev: false, inBundle: false, key: '', }; const pkgKeysByName = Object.keys(npmLockPkgs).reduce((acc, key) => { const name = key.replace(/.*node_modules\//, ''); if (!name) { return acc; } if (!acc.has(name)) { acc.set(name, []); } acc.get(name).push(key); return acc; }, new Map()); const visitedMap = new Set(); await dfsVisit(depGraphBuilder, rootNode, visitedMap, npmLockPkgs, strictOutOfSync, includeDevDeps, includeOptionalDeps, [], pkgKeysByName, pkgJson.overrides); return depGraphBuilder.build(); }; exports.buildDepGraphNpmLockV2 = buildDepGraphNpmLockV2; const dfsVisit = async (depGraphBuilder, node, visitedMap, npmLockPkgs, strictOutOfSync, includeDevDeps, includeOptionalDeps, ancestry, pkgKeysByName, overrides) => { visitedMap.add(node.id); for (const [name, depInfo] of Object.entries(node.dependencies || {})) { if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } const childNode = getChildNode(name, depInfo, npmLockPkgs, strictOutOfSync, includeDevDeps, includeOptionalDeps, [ ...ancestry, { name: node.name, version: node.version, key: node.key || '', inBundle: node.inBundle || false, }, ], pkgKeysByName, overrides); if (!visitedMap.has(childNode.id)) { (0, util_1.addPkgNodeToGraph)(depGraphBuilder, childNode, {}); await dfsVisit(depGraphBuilder, childNode, visitedMap, npmLockPkgs, strictOutOfSync, includeDevDeps, includeOptionalDeps, [ ...ancestry, { name: node.name, version: node.version, key: node.key, inBundle: node.inBundle || false, }, ], pkgKeysByName, overrides); } depGraphBuilder.connectDep(node.id, childNode.id); } }; const getChildNode = (name, depInfo, pkgs, strictOutOfSync, includeDevDeps, includeOptionalDeps, ancestry, pkgKeysByName, overrides) => { let version = depInfo.version; const override = overrides && checkOverrides([...ancestry, { name, version }], overrides); if (override) { version = override; } if (version.startsWith('npm:')) { version = version.split('@').pop() || version; } let childNodeKey = (0, exports.getChildNodeKey)(name, version, ancestry, pkgs, pkgKeysByName); if (!childNodeKey) { if (strictOutOfSync) { throw new errors_1.OutOfSyncError(`${name}@${depInfo.version}`, parsers_1.LockfileType.npm); } else { return { id: `${name}@${depInfo.version}`, name: name, version: depInfo.version, dependencies: {}, isDev: depInfo.isDev, missingLockFileEntry: true, key: '', }; } } let depData = pkgs[childNodeKey]; const resolvedToWorkspace = () => { // Workspaces can be set as an array, or as an object // { packages: [] }, this can be checked in // https://github.com/npm/map-workspaces/blob/ff82968a3dbb78659fb7febfce4841bf58c514de/lib/index.js#L27-L41 if (pkgs['']['workspaces'] === undefined) { return false; } const workspacesDeclaration = Array.isArray(pkgs['']['workspaces']['packages']) ? pkgs['']['workspaces']['packages'] : pkgs['']['workspaces'] || []; const resolvedPath = depData.resolved || ''; const fixedResolvedPath = resolvedPath.replace(/\\/g, '/'); const normalizedWorkspacesDefn = workspacesDeclaration.map((p) => { return pathUtil.normalize(p).replace(/\\/g, '/'); }); return micromatch.isMatch(fixedResolvedPath, normalizedWorkspacesDefn); }; // Check for workspaces if (depData['link'] && resolvedToWorkspace()) { childNodeKey = depData.resolved; depData = pkgs[depData.resolved]; } const dependencies = (0, util_1.getGraphDependencies)(depData.dependencies || {}, depInfo.isDev); const devDependencies = includeDevDeps ? (0, util_1.getGraphDependencies)(depData.devDependencies || {}, depInfo.isDev) : {}; const optionalDependencies = includeOptionalDeps ? (0, util_1.getGraphDependencies)(depData.optionalDependencies || {}, depInfo.isDev) : {}; return { id: `${name}@${depData.version}`, name: name, version: depData.version, dependencies: Object.assign(Object.assign(Object.assign({}, dependencies), devDependencies), optionalDependencies), isDev: depInfo.isDev, inBundle: depData.inBundle, key: childNodeKey, }; }; const getChildNodeKey = (name, version, ancestry, pkgs, pkgKeysByName) => { // This is a list of all our possible options for the childKey const candidateKeys = pkgKeysByName.get(name); // Lockfile missing entry if (!candidateKeys) { return undefined; } // If we only have one candidate then we just take it if (candidateKeys.length === 1) { return candidateKeys[0]; } // If we are bundled we assume we are scoped by the bundle root at least // otherwise the ancestry root is the root ignoring the true root const isBundled = ancestry[ancestry.length - 1].inBundle; const rootOperatingIdx = isBundled ? ancestry.findIndex((el) => el.inBundle === true) - 1 : 1; const ancestryFromRootOperatingIdx = [ ...ancestry.slice(rootOperatingIdx).map((el) => el.name), name, ]; // We filter on a number of cases let filteredCandidates = candidateKeys.filter((candidate) => { // This is splitting the candidate that looks like // `node_modules/a/node_modules/b` into ["a", "b"] // To do this we remove the first node_modules substring // and then split on the rest const candidateAncestry = (candidate.startsWith('node_modules/') ? candidate.replace('node_modules/', '').split('/node_modules/') : candidate.split('/node_modules/')).map((el) => { if (pkgs[el]) { return pkgs[el].name || el; } return el; }); // Check the ancestry of the candidate is a subset of // the current pkg. If it is not then it can't be a // valid key. const isCandidateAncestryIsSubsetOfPkgAncestry = candidateAncestry.every((pkg) => { return ancestryFromRootOperatingIdx.includes(pkg); }); if (isCandidateAncestryIsSubsetOfPkgAncestry === false) { return false; } // If we are bundled we assume the bundle root is the first value // in the candidates scoping if (isBundled) { const doesBundledPkgShareBundleRoot = candidateAncestry[0] === ancestryFromRootOperatingIdx[0]; if (doesBundledPkgShareBundleRoot === false) { return false; } } // So now we can check semver to filter out some values // if our version is valid semver if (semver.validRange(version)) { const candidatePkgVersion = pkgs[candidate].version; const doesVersionSatisfySemver = semver.satisfies(candidatePkgVersion, version); return doesVersionSatisfySemver; } return true; }); if (filteredCandidates.length === 1) { return filteredCandidates[0]; } const ancestryNames = ancestry.map((el) => el.name).concat(name); while (ancestryNames.length > 0) { const possibleKey = `node_modules/${ancestryNames.join('/node_modules/')}`; if (filteredCandidates.includes(possibleKey)) { return possibleKey; } ancestryNames.shift(); } // Here we go through th eancestry backwards to find the nearest // ancestor package const reversedAncestry = ancestry.reverse(); for (let parentIndex = 0; parentIndex < reversedAncestry.length; parentIndex++) { const parentName = reversedAncestry[parentIndex].name; const possibleFilteredKeys = filteredCandidates.filter((key) => key.includes(parentName)); if (possibleFilteredKeys.length === 1) { return possibleFilteredKeys[0]; } if (possibleFilteredKeys.length === 0) { continue; } filteredCandidates = possibleFilteredKeys; } return undefined; }; exports.getChildNodeKey = getChildNodeKey; const checkOverrides = (ancestry, overrides) => { const ancestryWithoutRoot = ancestry.slice(1); // First traverse into overrides from root down for (const [idx, pkg] of ancestryWithoutRoot.entries()) { // Do we have this in overrides const override = (0, exports.matchOverrideKey)(overrides, pkg); // If we dont find current element move down the ancestry if (!override) { continue; } // If we find a string as override we know we found what we want *if* // we are at our root if (idx + 1 === ancestryWithoutRoot.length && typeof override === 'string') { return override; } // If we don't find a string we might have a dotted reference // we only care about this if we are the final element in the ancestry. if (idx + 1 === ancestryWithoutRoot.length && override['.']) { return override['.']; } // If we don't find a string or a dotted reference we need to recurse // to find the override const recursiveOverride = checkOverrides(ancestryWithoutRoot, override); // If we get a non-undefined result, it is our answer if (recursiveOverride) { return recursiveOverride; } } return; }; // Here we have to match our pkg to // possible keys in the overrides object const matchOverrideKey = (overrides, pkg) => { if (overrides[pkg.name]) { return overrides[pkg.name]; } const overrideKeysNameToVersions = Object.keys(overrides).reduce((acc, key) => { // Split the key to separate the package name from the version spec const atIndex = key.lastIndexOf('@'); const name = key.substring(0, atIndex); const versionSpec = key.substring(atIndex + 1); // Check if the package name already exists in the accumulator if (!acc[name]) { acc[name] = []; } // Add the version spec to the list of versions for this package name acc[name].push(versionSpec); return acc; }, {}); const computedOverrides = overrideKeysNameToVersions[pkg.name]; if (computedOverrides) { for (const versionSpec of computedOverrides) { const isPkgVersionSubsetOfOverrideSpec = semver.subset(pkg.version, semver.validRange(versionSpec)); if (isPkgVersionSubsetOfOverrideSpec) { return overrides[`${pkg.name}@${versionSpec}`]; } } } return null; }; exports.matchOverrideKey = matchOverrideKey; //# sourceMappingURL=index.js.map /***/ }), /***/ 30680: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildDepGraphPnpm = void 0; const dep_graph_1 = __webpack_require__(71479); const util_1 = __webpack_require__(30631); const utils_1 = __webpack_require__(4767); const event_loop_spinner_1 = __webpack_require__(77158); const error_catalog_nodejs_public_1 = __webpack_require__(88404); const out_of_sync_error_1 = __webpack_require__(49432); const __1 = __webpack_require__(79790); const debugModule = __webpack_require__(15158); const constants_1 = __webpack_require__(36222); const debug = debugModule('snyk-pnpm-workspaces'); const buildDepGraphPnpm = async (lockFileParser, pkgJson, options, importer) => { var _a; const { strictOutOfSync, includeOptionalDeps, includeDevDeps, pruneWithinTopLevelDeps, } = options; const depGraphBuilder = new dep_graph_1.DepGraphBuilder({ name: 'pnpm' }, { name: pkgJson.name, version: pkgJson.version || constants_1.UNDEFINED_VERSION }); lockFileParser.extractedPackages = lockFileParser.extractPackages(); const extractedPnpmPkgs = lockFileParser.extractedPackages; const topLevelDeps = (0, util_1.getTopLevelDeps)(pkgJson, options); const extractedTopLevelDeps = lockFileParser.extractTopLevelDependencies(options, importer) || {}; for (const name of Object.keys(topLevelDeps)) { if (!extractedTopLevelDeps[name]) { if (!strictOutOfSync) { continue; } const errMessage = `Dependency ${name} was not found in ` + `${out_of_sync_error_1.LOCK_FILE_NAME[__1.LockfileType.pnpm]}. Your package.json and ` + `${out_of_sync_error_1.LOCK_FILE_NAME[__1.LockfileType.pnpm]} are probably out of sync. Please run ` + `"${out_of_sync_error_1.INSTALL_COMMAND[__1.LockfileType.pnpm]}" and try again.`; debug(errMessage); throw new error_catalog_nodejs_public_1.OpenSourceEcosystems.PnpmOutOfSyncError(errMessage); } topLevelDeps[name].version = extractedTopLevelDeps[name].version; } const rootNode = { id: 'root-node', name: pkgJson.name, version: pkgJson.version, dependencies: topLevelDeps, isDev: false, }; const rootNodeId = `${pkgJson.name}@${pkgJson.version}`; await dfsVisit(depGraphBuilder, rootNodeId, rootNode, extractedPnpmPkgs, strictOutOfSync, includeOptionalDeps, includeDevDeps, ((_a = pkgJson.pnpm) === null || _a === void 0 ? void 0 : _a.overrides) || {}, pruneWithinTopLevelDeps, lockFileParser); return depGraphBuilder.build(); }; exports.buildDepGraphPnpm = buildDepGraphPnpm; /** * Use DFS to add all nodes and edges to the depGraphBuilder and prune cyclic nodes. * The visitedMap keep track of which nodes have already been discovered during traversal. * - If a node doesn't exist in the map, it means it hasn't been visited. * - If a node is already visited, simply connect the new node with this node. */ const dfsVisit = async (depGraphBuilder, rootNodeId, node, extractedPnpmPkgs, strictOutOfSync, includeOptionalDeps, includeDevDeps, overrides, pruneWithinTopLevel, lockFileParser, visited) => { for (const [name, depInfo] of Object.entries(node.dependencies || {})) { if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } const localVisited = visited || new Set(); const childNode = (0, utils_1.getPnpmChildNode)(name, depInfo, extractedPnpmPkgs, strictOutOfSync, includeOptionalDeps, includeDevDeps, lockFileParser); if (localVisited.has(childNode.id) || childNode.id == rootNodeId) { if (pruneWithinTopLevel) { const prunedId = `${childNode.id}:pruned`; depGraphBuilder.addPkgNode({ name: childNode.name, version: childNode.version }, prunedId, { labels: Object.assign({ scope: childNode.isDev ? 'dev' : 'prod', pruned: 'true' }, (node.missingLockFileEntry && { missingLockFileEntry: 'true', })), }); depGraphBuilder.connectDep(node.id, prunedId); } else { depGraphBuilder.connectDep(node.id, childNode.id); } continue; } depGraphBuilder.addPkgNode({ name: childNode.name, version: childNode.version }, childNode.id, { labels: Object.assign({ scope: childNode.isDev ? 'dev' : 'prod' }, (node.missingLockFileEntry && { missingLockFileEntry: 'true', })), }); depGraphBuilder.connectDep(node.id, childNode.id); localVisited.add(childNode.id); await dfsVisit(depGraphBuilder, rootNodeId, childNode, extractedPnpmPkgs, strictOutOfSync, includeOptionalDeps, includeDevDeps, overrides, pruneWithinTopLevel, lockFileParser, localVisited); } }; //# sourceMappingURL=build-dep-graph-pnpm.js.map /***/ }), /***/ 36222: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UNDEFINED_VERSION = void 0; exports.UNDEFINED_VERSION = 'undefined'; //# sourceMappingURL=constants.js.map /***/ }), /***/ 97894: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parsePnpmWorkspace = exports.parsePnpmProject = void 0; const parse_project_1 = __webpack_require__(21403); Object.defineProperty(exports, "parsePnpmProject", ({ enumerable: true, get: function () { return parse_project_1.parsePnpmProject; } })); const parse_workspace_1 = __webpack_require__(46410); Object.defineProperty(exports, "parsePnpmWorkspace", ({ enumerable: true, get: function () { return parse_workspace_1.parsePnpmWorkspace; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 31954: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getPnpmLockfileParser = void 0; const js_yaml_1 = __webpack_require__(80474); const lockfile_v6_1 = __webpack_require__(78279); const lockfile_v5_1 = __webpack_require__(30863); const lockfile_v9_1 = __webpack_require__(74656); const error_catalog_nodejs_public_1 = __webpack_require__(88404); const utils_1 = __webpack_require__(11184); function getPnpmLockfileParser(pnpmLockContent, lockfileVersion, workspaceArgs) { // In case of no dependencies, pnpm@7 (lokfile version 5) // does not create a lockfile at `pnpm install` // so if there is no lockfile content, default to lockfile version 5 if (!pnpmLockContent) { return new lockfile_v5_1.LockfileV5Parser(pnpmLockContent, workspaceArgs); } const rawPnpmLock = (0, js_yaml_1.load)(pnpmLockContent, { json: true, schema: js_yaml_1.FAILSAFE_SCHEMA, }); const version = rawPnpmLock.lockfileVersion; if (lockfileVersion === utils_1.NodeLockfileVersion.PnpmLockV5 || version.startsWith('5')) { return new lockfile_v5_1.LockfileV5Parser(rawPnpmLock, workspaceArgs); } if (lockfileVersion === utils_1.NodeLockfileVersion.PnpmLockV6 || version.startsWith('6')) { return new lockfile_v6_1.LockfileV6Parser(rawPnpmLock, workspaceArgs); } if (lockfileVersion === utils_1.NodeLockfileVersion.PnpmLockV9 || version.startsWith('9')) { return new lockfile_v9_1.LockfileV9Parser(rawPnpmLock, workspaceArgs); } throw new error_catalog_nodejs_public_1.OpenSourceEcosystems.PnpmUnsupportedLockfileVersionError(`The pnpm-lock.yaml lockfile version ${lockfileVersion} is not supported`); } exports.getPnpmLockfileParser = getPnpmLockfileParser; //# sourceMappingURL=index.js.map /***/ }), /***/ 15708: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PnpmLockfileParser = void 0; const semver_1 = __webpack_require__(33516); const pathUtil = __webpack_require__(71017); const lodash_1 = __webpack_require__(96486); const debugModule = __webpack_require__(15158); const constants_1 = __webpack_require__(36222); const debug = debugModule('snyk-pnpm-workspaces'); class PnpmLockfileParser { constructor(rawPnpmLock, workspaceArgs) { this.rawPnpmLock = rawPnpmLock; this.lockFileVersion = rawPnpmLock.lockfileVersion; this.workspaceArgs = workspaceArgs; this.packages = rawPnpmLock.packages || {}; this.extractedPackages = {}; this.resolvedPackages = {}; this.importers = this.normaliseImporters(rawPnpmLock); } isWorkspaceLockfile() { var _a; return (_a = this.workspaceArgs) === null || _a === void 0 ? void 0 : _a.isWorkspace; } extractPackages() { // Packages should be parsed only one time for a parser if (Object.keys(this.extractedPackages).length > 0) { return this.extractedPackages; } const packages = {}; Object.entries(this.packages).forEach(([depPath, versionData]) => { // name and version are optional in version data - if they don't show up in version data, they can be deducted from the dependency path const { name, version } = versionData; let parsedPath = {}; // Exclude transitive peer deps from depPath // e.g. '/cdktf-cli@0.20.3(ink@3.2.0)(react@17.0.2)' -> cdktf-cli@0.20.3 depPath = this.excludeTransPeerDepsVersions(depPath); if (!(version && name)) { parsedPath = this.parseDepPath(depPath); } const pkg = { id: depPath, name: name || parsedPath.name, version: version || parsedPath.version || depPath, isDev: versionData.dev == 'true', dependencies: versionData.dependencies || {}, devDependencies: versionData.devDependencies || {}, optionalDependencies: versionData.optionalDependencies || {}, }; packages[`${pkg.name}@${pkg.version}`] = pkg; this.resolvedPackages[depPath] = `${pkg.name}@${pkg.version}`; }); return packages; } extractTopLevelDependencies(options, importer) { var _a, _b; let root = this.rawPnpmLock; if (importer) { const { name, version } = (_a = this.workspaceArgs) === null || _a === void 0 ? void 0 : _a.projectsVersionMap[importer]; if ( // Return early because dependencies were already normalized for this importer // as part of another's importer dependency and stored in extractedPackages this.extractedPackages[`${name}@${version}`] && this.extractedPackages[`${name}@${version}`].localWorkspacePackage && !(0, lodash_1.isEmpty)(this.extractedPackages[`${name}@${version}`].dependencies)) { return this.normalizedPkgToTopLevel(this.extractedPackages[`${name}@${version}`]); } root = this.rawPnpmLock.importers[importer]; } const prodDeps = this.normalizeTopLevelDeps(root.dependencies || {}, false, importer); const devDeps = options.includeDevDeps ? this.normalizeTopLevelDeps(root.devDependencies || {}, true, importer) : {}; const optionalDeps = options.includeOptionalDeps ? this.normalizeTopLevelDeps(root.optionalDependencies || {}, false, importer) : {}; const peerDeps = options.includePeerDeps ? this.normalizeTopLevelDeps(root.peerDependencies || {}, false, importer) : {}; if (importer) { const { name, version } = (_b = this.workspaceArgs) === null || _b === void 0 ? void 0 : _b.projectsVersionMap[importer]; this.extractedPackages[`${name}@${version}`] = { id: `${name}@${version}`, name: name, version: version, dependencies: this.topLevelDepsToNormalizedPkgs(prodDeps), devDependencies: this.topLevelDepsToNormalizedPkgs(devDeps), optionalDependencies: this.topLevelDepsToNormalizedPkgs(optionalDeps), isDev: false, localWorkspacePackage: true, }; } return Object.assign(Object.assign(Object.assign(Object.assign({}, prodDeps), devDeps), optionalDeps), peerDeps); } normalizedPkgToTopLevel(pkg) { const topLevel = {}; Object.keys(pkg.dependencies).forEach((depName) => (topLevel[depName] = { name: depName, version: pkg.dependencies[depName], isDev: false, })); Object.keys(pkg.devDependencies).forEach((depName) => (topLevel[depName] = { name: depName, version: pkg.devDependencies[depName], isDev: true, })); return topLevel; } topLevelDepsToNormalizedPkgs(deps) { const normalizedPkgs = {}; Object.values(deps).forEach((dep) => (normalizedPkgs[dep.name] = dep.version)); return normalizedPkgs; } normalizeVersion(name, version, isDev, importerName) { if (this.isWorkspaceLockfile()) { version = this.resolveWorkspacesCrossReference(name, version, isDev, importerName); } if (!(0, semver_1.valid)(version)) { version = this.excludeTransPeerDepsVersions(version); if (!(0, semver_1.valid)(version)) { // for npm and git ref packages // they show up in packages with keys equal to the version in top level deps // e.g. body-parser with version github.com/expressjs/body-parser/263f602e6ae34add6332c1eb4caa808893b0b711 if (this.packages[version]) { return this.packages[version].version || version; } if (this.packages[`${name}@${version}`]) { return this.packages[`${name}@${version}`].version || version; } } } return version; } resolveWorkspacesCrossReference(name, version, isDev, importerName) { if (!this.workspaceArgs) { return version; } if (version.startsWith('link:')) { // In workspaces example: // package-b: // specifier: 1.0.0 // version: link:../pkg-b const depPath = version.split('link:')[1]; const resolvedPathDep = pathUtil .join(importerName || '.', depPath) .replace(/\\/g, '/'); // cross referenced package, we add it to the extracted packages const mappedProjInfo = this.workspaceArgs.projectsVersionMap[resolvedPathDep]; if (!mappedProjInfo) { debug(`Importer ${resolvedPathDep} discovered as a dependency of ${importerName} was not found in the lockfile`); version = constants_1.UNDEFINED_VERSION; } else { version = mappedProjInfo.version; } if (!version) { version = constants_1.UNDEFINED_VERSION; } // Stop recursion here if this package was already normalized and stored in extractedPackages if (this.extractedPackages[`${name}@${version}`]) { return version; } // Initialize this package before recursive calls to avoid inifinte recursion in cycles // We can avoid keeping a visited arrat this way this.extractedPackages[`${name}@${version}`] = { name, version, id: `${name}@${version}`, isDev, dependencies: {}, devDependencies: {}, localWorkspacePackage: true, }; const subDeps = this.rawPnpmLock.importers[resolvedPathDep] || { dependencies: {}, devDependencies: {}, optionalDependencies: {}, }; const resolvedDeps = this.normalizePackagesDeps(subDeps.dependencies || {}, isDev, resolvedPathDep); const resolvedDevDeps = this.normalizePackagesDeps(subDeps.devDependencies || {}, true, resolvedPathDep); const resolvedOptionalDeps = this.normalizePackagesDeps(subDeps.optionalDependencies || {}, true, resolvedPathDep); this.extractedPackages[`${name}@${version}`] = { name, version, id: `${name}@${version}`, isDev, dependencies: resolvedDeps, devDependencies: resolvedDevDeps, optionalDependencies: resolvedOptionalDeps, localWorkspacePackage: true, }; } return version; } } exports.PnpmLockfileParser = PnpmLockfileParser; //# sourceMappingURL=lockfile-parser.js.map /***/ }), /***/ 30863: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LockfileV5Parser = void 0; const dependency_path_1 = __webpack_require__(36577); const lockfile_parser_1 = __webpack_require__(15708); class LockfileV5Parser extends lockfile_parser_1.PnpmLockfileParser { constructor(rawPnpmLock, workspaceArgs) { // In case of no dependencies, pnpm@7 (lokfile version 5) // does not create a lockfile at `pnpm install` if (!rawPnpmLock) { rawPnpmLock = { lockfileVersion: '5', }; } super(rawPnpmLock, workspaceArgs); } parseDepPath(depPath) { // The 'dependency-path' parsing package only works for lockfiles v5 const { name, version } = (0, dependency_path_1.parse)(depPath); if (!version) { return { name }; } return { name, version: this.excludeTransPeerDepsVersions(version), }; } normalizeTopLevelDeps(dependencies, isDev, importerName) { return Object.entries(dependencies).reduce((pnpmDeps, [name, version]) => { version = this.normalizeVersion(name, version, isDev, importerName); pnpmDeps[name] = { name, version, isDev, }; return pnpmDeps; }, {}); } normalizePackagesDeps(dependencies, isDev, importerName) { return Object.entries(dependencies).reduce((pnpmDeps, [name, version]) => { version = this.normalizeVersion(name, version, isDev, importerName); pnpmDeps[name] = version; return pnpmDeps; }, {}); } // Dependency path and versions include transitive peer dependencies separated by '_' // e.g. in dependencies // dependencies: // acorn-jsx: 5.3.2_acorn@7.4.1 // OR in dependency path: // '/@babel/preset-typescript/7.12.13_@babel+core@7.12.13' // https://github.com/pnpm/spec/blob/master/dependency-path.md excludeTransPeerDepsVersions(fullVersionStr) { if (!fullVersionStr.includes('/')) { return fullVersionStr.split('_')[0]; } // When dealing with dependency paths, the dependency name can include '_' // so we need to make sure the '_' we split by is after '/' const splitSlashes = fullVersionStr.split('/'); const stringAfterLastSlash = splitSlashes[splitSlashes.length - 1]; const stringBeforeLastSlash = fullVersionStr.split(stringAfterLastSlash)[0]; const stringBetweenLastSlashAndUnderscore = stringAfterLastSlash.split('_')[0]; return `${stringBeforeLastSlash}${stringBetweenLastSlashAndUnderscore}`; } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types normaliseImporters(rawPnpmLock) { if (!('importers' in rawPnpmLock)) { return {}; } const rawImporters = rawPnpmLock.importers; return Object.entries(rawImporters).reduce( // eslint-disable-next-line @typescript-eslint/no-explicit-any (acc, [key, val]) => { // No deps case if (!('dependencies' in val)) { return Object.assign(Object.assign({}, acc), { [key]: {} }); } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const deps = val.dependencies; const depsNormalized = Object.fromEntries(Object.entries(deps).map(([depName, version]) => { return [depName, version]; })); return Object.assign(Object.assign({}, acc), { [key]: depsNormalized }); }, {}); } } exports.LockfileV5Parser = LockfileV5Parser; //# sourceMappingURL=lockfile-v5.js.map /***/ }), /***/ 78279: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LockfileV6Parser = void 0; const lockfile_parser_1 = __webpack_require__(15708); class LockfileV6Parser extends lockfile_parser_1.PnpmLockfileParser { constructor(rawPnpmLock, workspaceArgs) { super(rawPnpmLock, workspaceArgs); this.settings = rawPnpmLock.settings; } parseDepPath(depPath) { // Check if path is absolute (doesn't start with '/') // If it's not absolute, omit first '/' depPath = LockfileV6Parser.isAbsoluteDepenencyPath(depPath) ? depPath : depPath.substring(1); // This is the case for scoped packages, get version based on the last occurence of '@' separator // to include the '@' in the name if (depPath.startsWith('@')) { // e.g. @babel/code-frame@7.24.2 -> name: @babel/code-frame and version: 7.24.2 const sepIndex = depPath.lastIndexOf('@'); if (sepIndex === -1) { return {}; } const name = depPath.substring(0, sepIndex); const version = depPath.substring(sepIndex + 1); return { name, version, }; } // For non-scoped packages, the dependency specifier should contain only // one '@', separating the name and version const [name, version] = depPath.split('@'); return { name, version, }; } normalizeTopLevelDeps(dependencies, isDev, importerName) { return Object.entries(dependencies).reduce((pnpmDeps, [name, depInfo]) => { const version = this.normalizeVersion(name, depInfo.version, isDev, importerName); pnpmDeps[name] = { name, version, isDev, }; return pnpmDeps; }, {}); } normalizePackagesDeps(dependencies, isDev, importerName) { return Object.entries(dependencies).reduce((pnpmDeps, [name, depInfo]) => { const version = this.normalizeVersion(name, depInfo.version, isDev, importerName); pnpmDeps[name] = version; return pnpmDeps; }, {}); } // Dependency path and versions include transitive peer dependencies encapsulated in dependencies // e.g. '/cdktf-cli@0.20.3(ink@3.2.0)(react@17.0.2)' -> cdktf-cli@0.20.3 excludeTransPeerDepsVersions(fullVersionStr) { return fullVersionStr.split('(')[0]; } static isAbsoluteDepenencyPath(dependencyPath) { return dependencyPath[0] !== '/'; } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types normaliseImporters(rawPnpmLock) { if (!('importers' in rawPnpmLock)) { return {}; } const rawImporters = rawPnpmLock.importers; return Object.entries(rawImporters).reduce( // eslint-disable-next-line @typescript-eslint/no-explicit-any (acc, [key, val]) => { // No deps case if (!('dependencies' in val)) { return Object.assign(Object.assign({}, acc), { [key]: {} }); } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const deps = val.dependencies; const depsNormalized = Object.fromEntries(Object.entries(deps).map(([depName, depInfo]) => { return [depName, depInfo.version]; })); return Object.assign(Object.assign({}, acc), { [key]: depsNormalized }); }, {}); } } exports.LockfileV6Parser = LockfileV6Parser; //# sourceMappingURL=lockfile-v6.js.map /***/ }), /***/ 74656: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LockfileV9Parser = void 0; const lockfile_v6_1 = __webpack_require__(78279); const DEFAULT_WORKSPACE_ARGS = { isWorkspace: true, projectsVersionMap: {}, }; class LockfileV9Parser extends lockfile_v6_1.LockfileV6Parser { constructor(rawPnpmLock, workspaceArgs = DEFAULT_WORKSPACE_ARGS) { super(rawPnpmLock, workspaceArgs); this.settings = rawPnpmLock.settings; this.packages = {}; this.snapshots = rawPnpmLock.snapshots || {}; Object.entries(this.snapshots).forEach(([depPath, versionData]) => { const normalizedDepPath = this.excludeTransPeerDepsVersions(depPath); this.packages[normalizedDepPath] = Object.assign(Object.assign({}, rawPnpmLock.packages[normalizedDepPath]), versionData); }); } } exports.LockfileV9Parser = LockfileV9Parser; //# sourceMappingURL=lockfile-v9.js.map /***/ }), /***/ 21403: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parsePnpmProject = void 0; const util_1 = __webpack_require__(30631); const build_dep_graph_pnpm_1 = __webpack_require__(30680); const index_1 = __webpack_require__(31954); const parsePnpmProject = async (pkgJsonContent, pnpmLockContent, options, lockfileVersion) => { const { includeDevDeps, includePeerDeps, includeOptionalDeps, strictOutOfSync, pruneWithinTopLevelDeps, } = options; let importer = ''; const pkgJson = (0, util_1.parsePkgJson)(pkgJsonContent); const lockFileParser = (0, index_1.getPnpmLockfileParser)(pnpmLockContent, lockfileVersion); // Lockfile V9 simple project has the root importer if (lockFileParser.lockFileVersion.startsWith('9')) { importer = '.'; lockFileParser.workspaceArgs = { projectsVersionMap: { '.': { name: pkgJson.name, version: pkgJson.version }, }, isWorkspace: true, }; } const depgraph = await (0, build_dep_graph_pnpm_1.buildDepGraphPnpm)(lockFileParser, pkgJson, { includeDevDeps, strictOutOfSync, includePeerDeps, includeOptionalDeps, pruneWithinTopLevelDeps, }, importer); return depgraph; }; exports.parsePnpmProject = parsePnpmProject; //# sourceMappingURL=parse-project.js.map /***/ }), /***/ 46410: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parsePnpmWorkspace = void 0; const debugModule = __webpack_require__(15158); const path = __webpack_require__(71017); const util_1 = __webpack_require__(30631); const build_dep_graph_pnpm_1 = __webpack_require__(30680); const index_1 = __webpack_require__(31954); const utils_1 = __webpack_require__(11184); const utils_2 = __webpack_require__(4767); const constants_1 = __webpack_require__(36222); const debug = debugModule('snyk-pnpm-workspaces'); // Compute project versions map // This is needed because the lockfile doesn't present the version of // a project that's part of a workspace, we need to retrieve it from // its corresponding package.json function computeProjectVersionMaps(root, targets) { const projectsVersionMap = {}; for (const target of targets) { const directory = path.join(root, target); const packageJsonFileName = path.join(directory, 'package.json'); const packageJson = (0, utils_2.getFileContents)(root, packageJsonFileName); try { const parsedPkgJson = (0, util_1.parsePkgJson)(packageJson.content); projectsVersionMap[target] = { version: parsedPkgJson.version || constants_1.UNDEFINED_VERSION, name: parsedPkgJson.name, }; } catch (err) { debug(`Error getting version for project: ${packageJsonFileName}. ERROR: ${err}`); continue; } } return projectsVersionMap; } const parsePnpmWorkspace = async (root, workspaceDir, options) => { const scannedProjects = []; const { includeDevDeps, includePeerDeps, includeOptionalDeps, strictOutOfSync, pruneWithinTopLevelDeps, } = options; const pnpmLockfileContents = (0, utils_2.getFileContents)(root, path.join(workspaceDir, 'pnpm-lock.yaml')).content; const lockfileVersion = (0, utils_1.getPnpmLockfileVersion)(pnpmLockfileContents); const lockFileParser = (0, index_1.getPnpmLockfileParser)(pnpmLockfileContents, lockfileVersion); const projectVersionsMaps = computeProjectVersionMaps(workspaceDir, Object.keys(lockFileParser.importers)); for (const importer of Object.keys(lockFileParser.importers)) { const resolvedImporterPath = path.join(workspaceDir, importer); const packagePath = path.join(resolvedImporterPath, 'package.json'); debug(`Processing project ${packagePath} as part of a pnpm workspace`); const pkgJsonFile = (0, utils_2.getFileContents)(root, packagePath); const pkgJson = (0, util_1.parsePkgJson)(pkgJsonFile.content); lockFileParser.workspaceArgs = { isWorkspace: true, projectsVersionMap: projectVersionsMaps, }; try { const depGraph = await (0, build_dep_graph_pnpm_1.buildDepGraphPnpm)(lockFileParser, pkgJson, { includeDevDeps, includePeerDeps, strictOutOfSync, includeOptionalDeps, pruneWithinTopLevelDeps, }, importer); const project = { packageManager: 'pnpm', targetFile: path.relative(root, pkgJsonFile.fileName), depGraph, plugin: { name: 'snyk-nodejs-lockfile-parser', runtime: process.version, }, }; scannedProjects.push(project); } catch (e) { debug(`Error process workspace: ${pkgJsonFile.fileName}. ERROR: ${e}`); } } return scannedProjects; }; exports.parsePnpmWorkspace = parsePnpmWorkspace; //# sourceMappingURL=parse-workspace.js.map /***/ }), /***/ 4767: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getFileContents = exports.getPnpmChildNode = void 0; const path = __webpack_require__(71017); const fs = __webpack_require__(57147); const __1 = __webpack_require__(79790); const util_1 = __webpack_require__(30631); const error_catalog_nodejs_public_1 = __webpack_require__(88404); const out_of_sync_error_1 = __webpack_require__(49432); const debugModule = __webpack_require__(15158); const constants_1 = __webpack_require__(36222); const debug = debugModule('snyk-pnpm-workspaces'); const getPnpmChildNode = (name, depInfo, pkgs, strictOutOfSync, includeOptionalDeps, includeDevDeps, lockfileParser) => { const resolvedVersion = lockfileParser.excludeTransPeerDepsVersions(depInfo.version); let childNodeKey = `${name}@${resolvedVersion}`; // For aliases, the version is the dependency path that // shows up in the packages section of lockfiles if (lockfileParser.resolvedPackages[resolvedVersion]) { childNodeKey = lockfileParser.resolvedPackages[resolvedVersion]; } if (lockfileParser.resolvedPackages[childNodeKey]) { childNodeKey = lockfileParser.resolvedPackages[childNodeKey]; } if (!pkgs[childNodeKey]) { if (strictOutOfSync && !/^file:/.test(depInfo.version)) { const errMessage = `Dependency ${childNodeKey} was not found in ` + `${out_of_sync_error_1.LOCK_FILE_NAME[__1.LockfileType.pnpm]}. Your package.json and ` + `${out_of_sync_error_1.LOCK_FILE_NAME[__1.LockfileType.pnpm]} are probably out of sync. Please run ` + `"${out_of_sync_error_1.INSTALL_COMMAND[__1.LockfileType.pnpm]}" and try again.`; debug(errMessage); throw new error_catalog_nodejs_public_1.OpenSourceEcosystems.PnpmOutOfSyncError(errMessage); } else { return { id: childNodeKey, name: name, version: resolvedVersion || constants_1.UNDEFINED_VERSION, dependencies: {}, isDev: depInfo.isDev, missingLockFileEntry: true, }; } } else { const depData = pkgs[childNodeKey]; const dependencies = (0, util_1.getGraphDependencies)(depData.dependencies || {}, depInfo.isDev); const devDependencies = includeDevDeps ? (0, util_1.getGraphDependencies)(depData.devDependencies || {}, true) : {}; const optionalDependencies = includeOptionalDeps ? (0, util_1.getGraphDependencies)(depData.optionalDependencies || {}, depInfo.isDev) : {}; return { id: `${depData.name}@${depData.version}`, name: depData.name, version: depData.version || constants_1.UNDEFINED_VERSION, dependencies: Object.assign(Object.assign(Object.assign({}, dependencies), optionalDependencies), devDependencies), isDev: depInfo.isDev, }; } }; exports.getPnpmChildNode = getPnpmChildNode; function getFileContents(root, fileName) { const fullPath = path.resolve(root, fileName); if (!fs.existsSync(fullPath)) { throw new Error('Manifest ' + fileName + ' not found at location: ' + fileName); } const content = fs.readFileSync(fullPath, 'utf-8'); return { content, fileName, }; } exports.getFileContents = getFileContents; //# sourceMappingURL=utils.js.map /***/ }), /***/ 30631: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getChildNode = exports.parsePkgJson = exports.getGraphDependencies = exports.getTopLevelDeps = exports.addPkgNodeToGraph = void 0; const errors_1 = __webpack_require__(55622); const errors_2 = __webpack_require__(55622); const parsers_1 = __webpack_require__(64645); const addPkgNodeToGraph = (depGraphBuilder, node, options) => { return depGraphBuilder.addPkgNode({ name: node.name, version: node.version }, node.id, { labels: Object.assign(Object.assign(Object.assign({ scope: node.isDev ? 'dev' : 'prod' }, (options.isCyclic && { pruned: 'cyclic' })), (options.isWorkspacePkg && { pruned: 'true' })), (node.missingLockFileEntry && { missingLockFileEntry: 'true' })), }); }; exports.addPkgNodeToGraph = addPkgNodeToGraph; /** * Get top level dependencies from the given package json object which is parsed from a package.json file. * This includes both prod dependencies and dev dependencies supposing includeDevDeps is supported. */ const getTopLevelDeps = (pkgJson, options) => { const prodDeps = (0, exports.getGraphDependencies)(pkgJson.dependencies || {}, false); const devDeps = (0, exports.getGraphDependencies)(pkgJson.devDependencies || {}, true); const optionalDeps = options.includeOptionalDeps ? (0, exports.getGraphDependencies)(pkgJson.optionalDependencies || {}, false) : {}; const peerDeps = options.includePeerDeps ? (0, exports.getGraphDependencies)(pkgJson.peerDependencies || {}, false) : {}; const deps = Object.assign(Object.assign(Object.assign({}, prodDeps), optionalDeps), peerDeps); if (options.includeDevDeps) { // Ensure dev dependency 'isDev' flags are correctly set. // Dev dependencies are applied last to override shared keys with regular dependencies. return Object.assign(Object.assign({}, deps), devDeps); } // For includeDevDeps option set to false, simulate pnpm install --prod // by excluding all devDependencies, // ignoring potential duplicates in other dependency lists. // https://pnpm.io/cli/install#--prod--p return Object.keys(deps) .filter((packageName) => !devDeps.hasOwnProperty(packageName)) .reduce((result, packageName) => { result[packageName] = deps[packageName]; return result; }, {}); }; exports.getTopLevelDeps = getTopLevelDeps; /** * Converts dependencies parsed from the a lock file to a dependencies object required by the graph. * For example, { 'mime-db': '~1.12.0' } will be converted to { 'mime-db': { version: '~1.12.0', isDev: true/false } }. */ const getGraphDependencies = (dependencies, isDev) => { return Object.entries(dependencies).reduce((pnpmDeps, [name, semver]) => { pnpmDeps[name] = { version: semver, isDev: isDev }; return pnpmDeps; }, {}); }; exports.getGraphDependencies = getGraphDependencies; function parsePkgJson(pkgJsonContent) { try { const parsedPkgJson = JSON.parse(pkgJsonContent); if (!parsedPkgJson.name) { parsedPkgJson.name = 'package.json'; } return parsedPkgJson; } catch (e) { throw new errors_1.InvalidUserInputError('package.json parsing failed with error ' + e.message); } } exports.parsePkgJson = parsePkgJson; const getChildNode = (name, depInfo, pkgs, strictOutOfSync, includeOptionalDeps) => { const childNodeKey = `${name}@${depInfo.version}`; let childNode; if (!pkgs[childNodeKey]) { if (strictOutOfSync && !/^file:/.test(depInfo.version)) { throw new errors_2.OutOfSyncError(childNodeKey, parsers_1.LockfileType.yarn); } else { childNode = { id: childNodeKey, name: name, version: depInfo.version, dependencies: {}, isDev: depInfo.isDev, missingLockFileEntry: true, }; } } else { const depData = pkgs[childNodeKey]; const dependencies = (0, exports.getGraphDependencies)(depData.dependencies || {}, depInfo.isDev); const optionalDependencies = includeOptionalDeps ? (0, exports.getGraphDependencies)(depData.optionalDependencies || {}, depInfo.isDev) : {}; childNode = { id: `${name}@${depData.version}`, name: name, version: depData.version, dependencies: Object.assign(Object.assign({}, dependencies), optionalDependencies), isDev: depInfo.isDev, }; } return childNode; }; exports.getChildNode = getChildNode; //# sourceMappingURL=util.js.map /***/ }), /***/ 2525: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildDepGraphYarnLockV1SimpleCyclesPruned = void 0; const dep_graph_1 = __webpack_require__(71479); const util_1 = __webpack_require__(30631); const event_loop_spinner_1 = __webpack_require__(77158); var Color; (function (Color) { Color[Color["GRAY"] = 0] = "GRAY"; Color[Color["BLACK"] = 1] = "BLACK"; })(Color || (Color = {})); const buildDepGraphYarnLockV1SimpleCyclesPruned = async (extractedYarnLockV1Pkgs, pkgJson, options) => { const { includeDevDeps, strictOutOfSync, includeOptionalDeps } = options; const depGraphBuilder = new dep_graph_1.DepGraphBuilder({ name: 'yarn' }, { name: pkgJson.name, version: pkgJson.version }); const colorMap = {}; const topLevelDeps = (0, util_1.getTopLevelDeps)(pkgJson, { includeDevDeps }); const rootNode = { id: 'root-node', name: pkgJson.name, version: pkgJson.version, dependencies: topLevelDeps, isDev: false, }; await dfsVisit(depGraphBuilder, rootNode, colorMap, extractedYarnLockV1Pkgs, strictOutOfSync, includeOptionalDeps); return depGraphBuilder.build(); }; exports.buildDepGraphYarnLockV1SimpleCyclesPruned = buildDepGraphYarnLockV1SimpleCyclesPruned; /** * Use DFS to add all nodes and edges to the depGraphBuilder and prune cyclic nodes. * The colorMap keep track of the state of node during traversal. * - If a node doesn't exist in the map, it means it hasn't been visited. * - If a node is GRAY, it means it has already been discovered but its subtree hasn't been fully traversed. * - If a node is BLACK, it means its subtree has already been fully traversed. * - When first exploring an edge, if it points to a GRAY node, a cycle is found and the GRAY node is pruned. * - A pruned node has id `${originalId}|1` */ const dfsVisit = async (depGraphBuilder, node, colorMap, extractedYarnLockV1Pkgs, strictOutOfSync, includeOptionalDeps) => { colorMap[node.id] = Color.GRAY; for (const [name, depInfo] of Object.entries(node.dependencies || {})) { if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } const childNode = (0, util_1.getChildNode)(name, depInfo, extractedYarnLockV1Pkgs, strictOutOfSync, includeOptionalDeps); if (!colorMap.hasOwnProperty(childNode.id)) { (0, util_1.addPkgNodeToGraph)(depGraphBuilder, childNode, {}); await dfsVisit(depGraphBuilder, childNode, colorMap, extractedYarnLockV1Pkgs, strictOutOfSync, includeOptionalDeps); } else if (colorMap[childNode.id] === Color.GRAY) { // cycle detected childNode.id = `${childNode.id}:pruned`; (0, util_1.addPkgNodeToGraph)(depGraphBuilder, childNode, { isCyclic: true }); } depGraphBuilder.connectDep(node.id, childNode.id); } colorMap[node.id] = Color.BLACK; }; //# sourceMappingURL=build-depgraph-simple-pruned.js.map /***/ }), /***/ 20479: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildDepGraphYarnLockV1Simple = void 0; const dep_graph_1 = __webpack_require__(71479); const util_1 = __webpack_require__(30631); const event_loop_spinner_1 = __webpack_require__(77158); const buildDepGraphYarnLockV1Simple = async (extractedYarnLockV1Pkgs, pkgJson, options) => { const { includeDevDeps, includeOptionalDeps, includePeerDeps, strictOutOfSync, pruneWithinTopLevelDeps, } = options; const depGraphBuilder = new dep_graph_1.DepGraphBuilder({ name: 'yarn' }, { name: pkgJson.name, version: pkgJson.version }); const topLevelDeps = (0, util_1.getTopLevelDeps)(pkgJson, { includeDevDeps, includePeerDeps, includeOptionalDeps, }); const rootNode = { id: 'root-node', name: pkgJson.name, version: pkgJson.version, dependencies: topLevelDeps, isDev: false, }; await dfsVisit(depGraphBuilder, rootNode, extractedYarnLockV1Pkgs, strictOutOfSync, includeOptionalDeps, pruneWithinTopLevelDeps); return depGraphBuilder.build(); }; exports.buildDepGraphYarnLockV1Simple = buildDepGraphYarnLockV1Simple; /** * Use DFS to add all nodes and edges to the depGraphBuilder and prune cyclic nodes. * The visitedMap keep track of which nodes have already been discovered during traversal. * - If a node doesn't exist in the map, it means it hasn't been visited. * - If a node is already visited, simply connect the new node with this node. */ const dfsVisit = async (depGraphBuilder, node, extractedYarnLockV1Pkgs, strictOutOfSync, includeOptionalDeps, pruneWithinTopLevel, visited) => { for (const [name, depInfo] of Object.entries(node.dependencies || {})) { if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } const localVisited = visited || new Set(); const childNode = (0, util_1.getChildNode)(name, depInfo, extractedYarnLockV1Pkgs, strictOutOfSync, includeOptionalDeps); if (localVisited.has(childNode.id)) { if (pruneWithinTopLevel) { const prunedId = `${childNode.id}:pruned`; depGraphBuilder.addPkgNode({ name: childNode.name, version: childNode.version }, prunedId, { labels: Object.assign({ scope: node.isDev ? 'dev' : 'prod', pruned: 'true' }, (node.missingLockFileEntry && { missingLockFileEntry: 'true', })), }); depGraphBuilder.connectDep(node.id, prunedId); } else { depGraphBuilder.connectDep(node.id, childNode.id); } continue; } depGraphBuilder.addPkgNode({ name: childNode.name, version: childNode.version }, childNode.id, { labels: Object.assign({ scope: node.isDev ? 'dev' : 'prod' }, (node.missingLockFileEntry && { missingLockFileEntry: 'true', })), }); depGraphBuilder.connectDep(node.id, childNode.id); localVisited.add(childNode.id); await dfsVisit(depGraphBuilder, childNode, extractedYarnLockV1Pkgs, strictOutOfSync, includeOptionalDeps, pruneWithinTopLevel, localVisited); } }; //# sourceMappingURL=build-depgraph-simple.js.map /***/ }), /***/ 39617: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildDepGraphYarnLockV1WorkspaceCyclesPruned = void 0; const dep_graph_1 = __webpack_require__(71479); const util_1 = __webpack_require__(30631); const util_2 = __webpack_require__(46716); const event_loop_spinner_1 = __webpack_require__(77158); var Color; (function (Color) { Color[Color["GRAY"] = 0] = "GRAY"; Color[Color["BLACK"] = 1] = "BLACK"; })(Color || (Color = {})); // Parse a single workspace package using yarn.lock v1 // workspaces feature const buildDepGraphYarnLockV1WorkspaceCyclesPruned = async (extractedYarnLockV1Pkgs, pkgJson, workspacePkgNameToVersion, options) => { const { includeDevDeps, strictOutOfSync, includeOptionalDeps } = options; const depGraphBuilder = new dep_graph_1.DepGraphBuilder({ name: 'yarn' }, { name: pkgJson.name, version: pkgJson.version }); const colorMap = {}; const topLevelDeps = (0, util_1.getTopLevelDeps)(pkgJson, { includeDevDeps }); const rootNode = { id: 'root-node', name: pkgJson.name, version: pkgJson.version, dependencies: topLevelDeps, isDev: false, }; await dfsVisit(depGraphBuilder, rootNode, colorMap, extractedYarnLockV1Pkgs, workspacePkgNameToVersion, strictOutOfSync, includeOptionalDeps); return depGraphBuilder.build(); }; exports.buildDepGraphYarnLockV1WorkspaceCyclesPruned = buildDepGraphYarnLockV1WorkspaceCyclesPruned; /** * Use DFS to add all nodes and edges to the depGraphBuilder and prune cyclic nodes. * The colorMap keep track of the state of node during traversal. * - If a node doesn't exist in the map, it means it hasn't been visited. * - If a node is GRAY, it means it has already been discovered but its subtree hasn't been fully traversed. * - If a node is BLACK, it means its subtree has already been fully traversed. * - When first exploring an edge, if it points to a GRAY node, a cycle is found and the GRAY node is pruned. * - A pruned node has id `${originalId}|1` * When coming across another workspace package as child node, simply add the node and edge to the graph and mark it as BLACK. */ const dfsVisit = async (depGraphBuilder, node, colorMap, extractedYarnLockV1Pkgs, workspacePkgNameToVersion, strictOutOfSync, includeOptionalDeps) => { colorMap[node.id] = Color.GRAY; for (const [name, depInfo] of Object.entries(node.dependencies || {})) { if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } const isWorkspacePkg = !!workspacePkgNameToVersion[name]; const childNode = (0, util_2.getChildNodeYarnLockV1Workspace)(name, depInfo, workspacePkgNameToVersion, extractedYarnLockV1Pkgs, strictOutOfSync, includeOptionalDeps); if (!colorMap.hasOwnProperty(childNode.id)) { (0, util_1.addPkgNodeToGraph)(depGraphBuilder, childNode, { isCyclic: false, isWorkspacePkg, }); if (!isWorkspacePkg) { await dfsVisit(depGraphBuilder, childNode, colorMap, extractedYarnLockV1Pkgs, workspacePkgNameToVersion, strictOutOfSync, includeOptionalDeps); } else { colorMap[childNode.id] = Color.BLACK; } } else if (colorMap[childNode.id] === Color.GRAY) { // cycle detected childNode.id = `${childNode.id}|1`; (0, util_1.addPkgNodeToGraph)(depGraphBuilder, childNode, { isCyclic: true, isWorkspacePkg, }); } depGraphBuilder.connectDep(node.id, childNode.id); } colorMap[node.id] = Color.BLACK; }; //# sourceMappingURL=build-depgraph-workspace-package-pruned.js.map /***/ }), /***/ 48649: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildDepGraphYarnLockV1Workspace = void 0; const dep_graph_1 = __webpack_require__(71479); const util_1 = __webpack_require__(30631); const util_2 = __webpack_require__(46716); const event_loop_spinner_1 = __webpack_require__(77158); const buildDepGraphYarnLockV1Workspace = async (extractedYarnLockV1Pkgs, pkgJson, workspacePkgNameToVersion, options) => { const { includeDevDeps, strictOutOfSync, includeOptionalDeps } = options; const depGraphBuilder = new dep_graph_1.DepGraphBuilder({ name: 'yarn' }, { name: pkgJson.name, version: pkgJson.version }); const visitedMap = new Set(); const topLevelDeps = (0, util_1.getTopLevelDeps)(pkgJson, { includeDevDeps }); const rootNode = { id: 'root-node', name: pkgJson.name, version: pkgJson.version, dependencies: topLevelDeps, isDev: false, }; await dfsVisit(depGraphBuilder, rootNode, visitedMap, extractedYarnLockV1Pkgs, workspacePkgNameToVersion, strictOutOfSync, includeOptionalDeps); return depGraphBuilder.build(); }; exports.buildDepGraphYarnLockV1Workspace = buildDepGraphYarnLockV1Workspace; /** * Use DFS to add all nodes and edges to the depGraphBuilder and prune cyclic nodes. * The colorMap keep track of the state of node during traversal. * - If a node doesn't exist in the map, it means it hasn't been visited. * - If a node is GRAY, it means it has already been discovered but its subtree hasn't been fully traversed. * - If a node is BLACK, it means its subtree has already been fully traversed. * - When first exploring an edge, if it points to a GRAY node, a cycle is found and the GRAY node is pruned. * - A pruned node has id `${originalId}|1` * When coming across another workspace package as child node, simply add the node and edge to the graph and mark it as BLACK. */ const dfsVisit = async (depGraphBuilder, node, visitedMap, extractedYarnLockV1Pkgs, workspacePkgNameToVersion, strictOutOfSync, includeOptionalDeps) => { visitedMap.add(node.id); for (const [name, depInfo] of Object.entries(node.dependencies || {})) { if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } const isWorkspacePkg = !!workspacePkgNameToVersion[name]; const childNode = (0, util_2.getChildNodeYarnLockV1Workspace)(name, depInfo, workspacePkgNameToVersion, extractedYarnLockV1Pkgs, strictOutOfSync, includeOptionalDeps); if (!visitedMap.has(childNode.id)) { (0, util_1.addPkgNodeToGraph)(depGraphBuilder, childNode, { isCyclic: false, isWorkspacePkg, }); if (!isWorkspacePkg) { await dfsVisit(depGraphBuilder, childNode, visitedMap, extractedYarnLockV1Pkgs, workspacePkgNameToVersion, strictOutOfSync, includeOptionalDeps); } } depGraphBuilder.connectDep(node.id, childNode.id); } }; //# sourceMappingURL=build-depgraph-workspace-package.js.map /***/ }), /***/ 66684: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.extractPkgsFromYarnLockV1 = void 0; const yarnLockfileParser = __webpack_require__(7615); const extractPkgsFromYarnLockV1 = (yarnLockContent) => { return yarnLockfileParser.parse(yarnLockContent).object; }; exports.extractPkgsFromYarnLockV1 = extractPkgsFromYarnLockV1; //# sourceMappingURL=extract-yarnlock-v1-pkgs.js.map /***/ }), /***/ 20960: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildDepGraphYarnLockV1Simple = exports.buildDepGraphYarnLockV1SimpleCyclesPruned = exports.buildDepGraphYarnLockV1Workspace = exports.buildDepGraphYarnLockV1WorkspaceCyclesPruned = exports.extractPkgsFromYarnLockV1 = exports.parseYarnLockV1Project = exports.parseYarnLockV1WorkspaceProject = void 0; const build_depgraph_simple_pruned_1 = __webpack_require__(2525); Object.defineProperty(exports, "buildDepGraphYarnLockV1SimpleCyclesPruned", ({ enumerable: true, get: function () { return build_depgraph_simple_pruned_1.buildDepGraphYarnLockV1SimpleCyclesPruned; } })); const build_depgraph_simple_1 = __webpack_require__(20479); Object.defineProperty(exports, "buildDepGraphYarnLockV1Simple", ({ enumerable: true, get: function () { return build_depgraph_simple_1.buildDepGraphYarnLockV1Simple; } })); const build_depgraph_workspace_package_pruned_1 = __webpack_require__(39617); Object.defineProperty(exports, "buildDepGraphYarnLockV1WorkspaceCyclesPruned", ({ enumerable: true, get: function () { return build_depgraph_workspace_package_pruned_1.buildDepGraphYarnLockV1WorkspaceCyclesPruned; } })); const build_depgraph_workspace_package_1 = __webpack_require__(48649); Object.defineProperty(exports, "buildDepGraphYarnLockV1Workspace", ({ enumerable: true, get: function () { return build_depgraph_workspace_package_1.buildDepGraphYarnLockV1Workspace; } })); const extract_yarnlock_v1_pkgs_1 = __webpack_require__(66684); Object.defineProperty(exports, "extractPkgsFromYarnLockV1", ({ enumerable: true, get: function () { return extract_yarnlock_v1_pkgs_1.extractPkgsFromYarnLockV1; } })); const simple_1 = __webpack_require__(49912); Object.defineProperty(exports, "parseYarnLockV1Project", ({ enumerable: true, get: function () { return simple_1.parseYarnLockV1Project; } })); const workspaces_1 = __webpack_require__(59228); Object.defineProperty(exports, "parseYarnLockV1WorkspaceProject", ({ enumerable: true, get: function () { return workspaces_1.parseYarnLockV1WorkspaceProject; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 49912: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseYarnLockV1Project = void 0; const _1 = __webpack_require__(20960); const util_1 = __webpack_require__(30631); const build_depgraph_simple_pruned_1 = __webpack_require__(2525); const extract_yarnlock_v1_pkgs_1 = __webpack_require__(66684); const parseYarnLockV1Project = async (pkgJsonContent, yarnLockContent, options) => { const { includeDevDeps, includeOptionalDeps, includePeerDeps, pruneLevel, strictOutOfSync, } = options; const pkgs = (0, extract_yarnlock_v1_pkgs_1.extractPkgsFromYarnLockV1)(yarnLockContent); const pkgJson = (0, util_1.parsePkgJson)(pkgJsonContent); const depGraph = pruneLevel === 'cycles' ? await (0, build_depgraph_simple_pruned_1.buildDepGraphYarnLockV1SimpleCyclesPruned)(pkgs, pkgJson, { includeDevDeps, strictOutOfSync, includeOptionalDeps, }) : await (0, _1.buildDepGraphYarnLockV1Simple)(pkgs, pkgJson, { includeDevDeps, includeOptionalDeps, includePeerDeps, strictOutOfSync, pruneWithinTopLevelDeps: pruneLevel === 'withinTopLevelDeps', }); return depGraph; }; exports.parseYarnLockV1Project = parseYarnLockV1Project; //# sourceMappingURL=simple.js.map /***/ }), /***/ 46716: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getChildNodeYarnLockV1Workspace = void 0; const errors_1 = __webpack_require__(55622); const parsers_1 = __webpack_require__(64645); const util_1 = __webpack_require__(30631); const getChildNodeYarnLockV1Workspace = (name, depInfo, workspacePkgNameToVersion, pkgs, strictOutOfSync, includeOptionalDeps) => { let childNode; if (workspacePkgNameToVersion[name]) { const version = workspacePkgNameToVersion[name]; // This is just to mimic old behavior where when StrictOutOfSync is turned on, // any cross referencing between workspace packages will lead to a throw if (strictOutOfSync) { throw new errors_1.OutOfSyncError(`${name}@${version}`, parsers_1.LockfileType.yarn); } childNode = { id: `${name}@${version}`, name: name, version: version, dependencies: {}, isDev: depInfo.isDev, }; } else { childNode = (0, util_1.getChildNode)(name, depInfo, pkgs, strictOutOfSync, includeOptionalDeps); } return childNode; }; exports.getChildNodeYarnLockV1Workspace = getChildNodeYarnLockV1Workspace; //# sourceMappingURL=util.js.map /***/ }), /***/ 59228: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseYarnLockV1WorkspaceProject = void 0; const build_depgraph_workspace_package_pruned_1 = __webpack_require__(39617); const build_depgraph_workspace_package_1 = __webpack_require__(48649); const extract_yarnlock_v1_pkgs_1 = __webpack_require__(66684); const util_1 = __webpack_require__(30631); const c_map_1 = __webpack_require__(16141); const parseYarnLockV1WorkspaceProject = async (yarnLockContent, workspacePackagesPkgJsons, options) => { const { includeDevDeps, includeOptionalDeps, pruneCycles, strictOutOfSync } = options; const extractedYarnLockV1Pkgs = (0, extract_yarnlock_v1_pkgs_1.extractPkgsFromYarnLockV1)(yarnLockContent); // Parse all package.json files and also extract names cross referencing later const workspacePkgNameToVersion = {}; const parsedWorkspacePkgJsons = workspacePackagesPkgJsons.map((wsPkgJsonContent) => { const parsedPkgJson = (0, util_1.parsePkgJson)(wsPkgJsonContent); workspacePkgNameToVersion[parsedPkgJson.name] = parsedPkgJson.version; return parsedPkgJson; }); const depGraphs = (0, c_map_1.cMap)(parsedWorkspacePkgJsons, async (parsedPkgJson) => { return pruneCycles ? await (0, build_depgraph_workspace_package_pruned_1.buildDepGraphYarnLockV1WorkspaceCyclesPruned)(extractedYarnLockV1Pkgs, parsedPkgJson, workspacePkgNameToVersion, { includeDevDeps, strictOutOfSync, includeOptionalDeps, }) : await (0, build_depgraph_workspace_package_1.buildDepGraphYarnLockV1Workspace)(extractedYarnLockV1Pkgs, parsedPkgJson, workspacePkgNameToVersion, { includeDevDeps, strictOutOfSync, includeOptionalDeps, }); }); return depGraphs; }; exports.parseYarnLockV1WorkspaceProject = parseYarnLockV1WorkspaceProject; //# sourceMappingURL=workspaces.js.map /***/ }), /***/ 94710: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildDepGraphYarnLockV2Simple = void 0; const dep_graph_1 = __webpack_require__(71479); const util_1 = __webpack_require__(30631); const utils_1 = __webpack_require__(17651); const event_loop_spinner_1 = __webpack_require__(77158); const buildDepGraphYarnLockV2Simple = async (extractedYarnLockV2Pkgs, pkgJson, options, workspaceArgs) => { const { includeDevDeps, strictOutOfSync, includeOptionalDeps, pruneWithinTopLevelDeps, } = options; const depGraphBuilder = new dep_graph_1.DepGraphBuilder({ name: 'yarn' }, { name: pkgJson.name, version: pkgJson.version }); const topLevelDeps = (0, util_1.getTopLevelDeps)(pkgJson, { includeDevDeps, }); const rootNode = { id: 'root-node', name: pkgJson.name, version: pkgJson.version, dependencies: topLevelDeps, isDev: false, }; await dfsVisit(depGraphBuilder, rootNode, extractedYarnLockV2Pkgs, strictOutOfSync, includeOptionalDeps, // we have rootWorkspaceResolutions if this is workspace pkg with resolutions // at root - therefore it should take precedent (workspaceArgs === null || workspaceArgs === void 0 ? void 0 : workspaceArgs.rootResolutions) || pkgJson.resolutions || {}, pruneWithinTopLevelDeps); return depGraphBuilder.build(); }; exports.buildDepGraphYarnLockV2Simple = buildDepGraphYarnLockV2Simple; /** * Use DFS to add all nodes and edges to the depGraphBuilder and prune cyclic nodes. * The visitedMap keep track of which nodes have already been discovered during traversal. * - If a node doesn't exist in the map, it means it hasn't been visited. * - If a node is already visited, simply connect the new node with this node. */ const dfsVisit = async (depGraphBuilder, node, extractedYarnLockV2Pkgs, strictOutOfSync, includeOptionalDeps, resolutions, pruneWithinTopLevel, visited) => { for (const [name, depInfo] of Object.entries(node.dependencies || {})) { if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } const localVisited = visited || new Set(); const childNode = (0, utils_1.getYarnLockV2ChildNode)(name, depInfo, extractedYarnLockV2Pkgs, strictOutOfSync, includeOptionalDeps, resolutions, node); if (localVisited.has(childNode.id)) { if (pruneWithinTopLevel) { const prunedId = `${childNode.id}:pruned`; depGraphBuilder.addPkgNode({ name: childNode.name, version: childNode.version }, prunedId, { labels: Object.assign({ scope: node.isDev ? 'dev' : 'prod', pruned: 'true' }, (node.missingLockFileEntry && { missingLockFileEntry: 'true', })), }); depGraphBuilder.connectDep(node.id, prunedId); } else { depGraphBuilder.connectDep(node.id, childNode.id); } continue; } depGraphBuilder.addPkgNode({ name: childNode.name, version: childNode.version }, childNode.id, { labels: Object.assign({ scope: node.isDev ? 'dev' : 'prod' }, (node.missingLockFileEntry && { missingLockFileEntry: 'true', })), }); depGraphBuilder.connectDep(node.id, childNode.id); localVisited.add(childNode.id); await dfsVisit(depGraphBuilder, childNode, extractedYarnLockV2Pkgs, strictOutOfSync, includeOptionalDeps, resolutions, pruneWithinTopLevel, localVisited); } }; //# sourceMappingURL=build-depgraph-simple.js.map /***/ }), /***/ 32916: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.extractPkgsFromYarnLockV2 = void 0; const js_yaml_1 = __webpack_require__(80474); const yarnCore = __webpack_require__(74876); const utils_1 = __webpack_require__(17651); const structUtils = yarnCore.structUtils; const parseDescriptor = structUtils.parseDescriptor; const parseRange = structUtils.parseRange; const keyNormalizer = (0, utils_1.yarnLockFileKeyNormalizer)(parseDescriptor, parseRange); const extractPkgsFromYarnLockV2 = (yarnLockContent) => { const rawYarnLock = (0, js_yaml_1.load)(yarnLockContent, { json: true, schema: js_yaml_1.FAILSAFE_SCHEMA, }); delete rawYarnLock.__metadata; const dependencies = {}; Object.entries(rawYarnLock).forEach(([fullDescriptor, versionData]) => { keyNormalizer(fullDescriptor).forEach((descriptor) => { dependencies[descriptor] = versionData; }); }); return dependencies; }; exports.extractPkgsFromYarnLockV2 = extractPkgsFromYarnLockV2; //# sourceMappingURL=extract-yarnlock-v2-pkgs.js.map /***/ }), /***/ 96470: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.extractPkgsFromYarnLockV2 = exports.buildDepGraphYarnLockV2Simple = exports.parseYarnLockV2Project = void 0; const build_depgraph_simple_1 = __webpack_require__(94710); Object.defineProperty(exports, "buildDepGraphYarnLockV2Simple", ({ enumerable: true, get: function () { return build_depgraph_simple_1.buildDepGraphYarnLockV2Simple; } })); const extract_yarnlock_v2_pkgs_1 = __webpack_require__(32916); Object.defineProperty(exports, "extractPkgsFromYarnLockV2", ({ enumerable: true, get: function () { return extract_yarnlock_v2_pkgs_1.extractPkgsFromYarnLockV2; } })); const simple_1 = __webpack_require__(75933); Object.defineProperty(exports, "parseYarnLockV2Project", ({ enumerable: true, get: function () { return simple_1.parseYarnLockV2Project; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 75933: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseYarnLockV2Project = void 0; const extract_yarnlock_v2_pkgs_1 = __webpack_require__(32916); const util_1 = __webpack_require__(30631); const build_depgraph_simple_1 = __webpack_require__(94710); const parseYarnLockV2Project = async (pkgJsonContent, yarnLockContent, options, workspaceArgs) => { const { includeDevDeps, includeOptionalDeps, strictOutOfSync, pruneWithinTopLevelDeps, } = options; const pkgs = (0, extract_yarnlock_v2_pkgs_1.extractPkgsFromYarnLockV2)(yarnLockContent); const pkgJson = (0, util_1.parsePkgJson)(pkgJsonContent); const depgraph = await (0, build_depgraph_simple_1.buildDepGraphYarnLockV2Simple)(pkgs, pkgJson, { includeDevDeps, strictOutOfSync, includeOptionalDeps, pruneWithinTopLevelDeps, }, workspaceArgs); return depgraph; }; exports.parseYarnLockV2Project = parseYarnLockV2Project; //# sourceMappingURL=simple.js.map /***/ }), /***/ 17651: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getYarnLockV2ChildNode = exports.yarnLockFileKeyNormalizer = void 0; const _flatMap = __webpack_require__(78661); const errors_1 = __webpack_require__(55622); const parsers_1 = __webpack_require__(64645); const util_1 = __webpack_require__(30631); const BUILTIN_PLACEHOLDER = 'builtin'; const MULTIPLE_KEYS_REGEXP = / *, */g; const keyNormalizer = (parseDescriptor, parseRange) => (rawDescriptor) => { // See https://yarnpkg.com/features/protocols const descriptors = [rawDescriptor]; const descriptor = parseDescriptor(rawDescriptor); const name = `${descriptor.scope ? '@' + descriptor.scope + '/' : ''}${descriptor.name}`; const range = parseRange(descriptor.range); const protocol = range.protocol; switch (protocol) { case 'npm:': case 'file:': // This is space inneficient but will be kept for now, // Due to how we wish to index using the dependencies map // we want the keys to match name@version but this is handled different // for npm alias and normal install. descriptors.push(`${name}@${range.selector}`); descriptors.push(`${name}@${protocol}${range.selector}`); break; case 'git:': case 'git+ssh:': case 'git+http:': case 'git+https:': case 'github:': if (range.source) { descriptors.push(`${name}@${protocol}${range.source}${range.selector ? '#' + range.selector : ''}`); } else { descriptors.push(`${name}@${protocol}${range.selector}`); } break; case 'patch:': if (range.source && range.selector.indexOf(BUILTIN_PLACEHOLDER) === 0) { descriptors.push(range.source); } else { descriptors.push(`${name}@${protocol}${range.source}${range.selector ? '#' + range.selector : ''}`); } break; case null: case undefined: if (range.source) { descriptors.push(`${name}@${range.source}#${range.selector}`); } else { descriptors.push(`${name}@${range.selector}`); } break; case 'http:': case 'https:': case 'link:': case 'portal:': case 'exec:': case 'workspace:': case 'virtual:': default: // For user defined plugins descriptors.push(`${name}@${protocol}${range.selector}`); break; } return descriptors; }; const yarnLockFileKeyNormalizer = (parseDescriptor, parseRange) => (fullDescriptor) => { const allKeys = fullDescriptor .split(MULTIPLE_KEYS_REGEXP) .map(keyNormalizer(parseDescriptor, parseRange)); return new Set(_flatMap(allKeys)); }; exports.yarnLockFileKeyNormalizer = yarnLockFileKeyNormalizer; const getYarnLockV2ChildNode = (name, depInfo, pkgs, strictOutOfSync, includeOptionalDeps, resolutions, parentNode) => { // First check if a resolution would be used const resolvedVersionFromResolution = (() => { // First check for scoped then simple const scopedKey = `${parentNode.name}/${name}`; if (resolutions[scopedKey]) { return resolutions[scopedKey]; } else if (resolutions[name]) { return resolutions[name]; } return ''; })(); if (resolvedVersionFromResolution) { const childNodeKeyFromResolution = `${name}@${resolvedVersionFromResolution}`; const { version: versionFromResolution, dependencies, optionalDependencies, } = pkgs[childNodeKeyFromResolution]; const formattedDependencies = (0, util_1.getGraphDependencies)(dependencies || {}, depInfo.isDev); const formattedOptionalDependencies = includeOptionalDeps ? (0, util_1.getGraphDependencies)(optionalDependencies || {}, depInfo.isDev) : {}; return { id: childNodeKeyFromResolution, name: name, version: versionFromResolution, dependencies: Object.assign(Object.assign({}, formattedOptionalDependencies), formattedDependencies), isDev: depInfo.isDev, }; } // No resolutions const childNodeKey = `${name}@${depInfo.version}`; if (!pkgs[childNodeKey]) { if (strictOutOfSync && !/^file:/.test(depInfo.version)) { throw new errors_1.OutOfSyncError(childNodeKey, parsers_1.LockfileType.yarn2); } else { return { id: childNodeKey, name: name, version: depInfo.version, dependencies: {}, isDev: depInfo.isDev, missingLockFileEntry: true, }; } } else { const depData = pkgs[childNodeKey]; const dependencies = (0, util_1.getGraphDependencies)(depData.dependencies || {}, depInfo.isDev); const optionalDependencies = includeOptionalDeps ? (0, util_1.getGraphDependencies)(depData.optionalDependencies || {}, depInfo.isDev) : {}; return { id: `${name}@${depData.version}`, name: name, version: depData.version, dependencies: Object.assign(Object.assign({}, dependencies), optionalDependencies), isDev: depInfo.isDev, }; } }; exports.getYarnLockV2ChildNode = getYarnLockV2ChildNode; //# sourceMappingURL=utils.js.map /***/ }), /***/ 55622: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UnsupportedError = exports.TreeSizeLimitError = exports.OutOfSyncError = exports.UnsupportedRuntimeError = exports.InvalidUserInputError = void 0; var invalid_user_input_error_1 = __webpack_require__(87088); Object.defineProperty(exports, "InvalidUserInputError", ({ enumerable: true, get: function () { return invalid_user_input_error_1.InvalidUserInputError; } })); var unsupported_runtime_error_1 = __webpack_require__(3956); Object.defineProperty(exports, "UnsupportedRuntimeError", ({ enumerable: true, get: function () { return unsupported_runtime_error_1.UnsupportedRuntimeError; } })); var out_of_sync_error_1 = __webpack_require__(49432); Object.defineProperty(exports, "OutOfSyncError", ({ enumerable: true, get: function () { return out_of_sync_error_1.OutOfSyncError; } })); var tree_size_limit_error_1 = __webpack_require__(42229); Object.defineProperty(exports, "TreeSizeLimitError", ({ enumerable: true, get: function () { return tree_size_limit_error_1.TreeSizeLimitError; } })); var unsupported_error_1 = __webpack_require__(74878); Object.defineProperty(exports, "UnsupportedError", ({ enumerable: true, get: function () { return unsupported_error_1.UnsupportedError; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 87088: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.InvalidUserInputError = void 0; class InvalidUserInputError extends Error { constructor(...args) { super(...args); this.code = 422; this.name = 'InvalidUserInputError'; Error.captureStackTrace(this, InvalidUserInputError); } } exports.InvalidUserInputError = InvalidUserInputError; //# sourceMappingURL=invalid-user-input-error.js.map /***/ }), /***/ 49432: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.OutOfSyncError = exports.INSTALL_COMMAND = exports.LOCK_FILE_NAME = void 0; exports.LOCK_FILE_NAME = { npm: 'package-lock.json', npm7: 'package-lock.json', yarn: 'yarn.lock', yarn2: 'yarn.lock', pnpm: 'pnpm-lock.yaml', }; exports.INSTALL_COMMAND = { npm: 'npm install', npm7: 'npm install', yarn: 'yarn install', yarn2: 'yarn install', pnpm: 'pnpm install', }; class OutOfSyncError extends Error { constructor(dependencyName, lockFileType) { super(`Dependency ${dependencyName} was not found in ` + `${exports.LOCK_FILE_NAME[lockFileType]}. Your package.json and ` + `${exports.LOCK_FILE_NAME[lockFileType]} are probably out of sync. Please run ` + `"${exports.INSTALL_COMMAND[lockFileType]}" and try again.`); this.code = 422; this.name = 'OutOfSyncError'; this.dependencyName = dependencyName; this.lockFileType = lockFileType; Error.captureStackTrace(this, OutOfSyncError); } } exports.OutOfSyncError = OutOfSyncError; //# sourceMappingURL=out-of-sync-error.js.map /***/ }), /***/ 42229: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TreeSizeLimitError = void 0; class TreeSizeLimitError extends Error { constructor() { super('Tree size exceeds the allowed limit.'); this.code = 422; this.name = 'TreeSizeLimitError'; Error.captureStackTrace(this, TreeSizeLimitError); } } exports.TreeSizeLimitError = TreeSizeLimitError; //# sourceMappingURL=tree-size-limit-error.js.map /***/ }), /***/ 74878: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UnsupportedError = void 0; class UnsupportedError extends Error { constructor(...args) { super(...args); this.name = 'UnsupportedError'; this.code = 500; Error.captureStackTrace(this, UnsupportedError); } } exports.UnsupportedError = UnsupportedError; //# sourceMappingURL=unsupported-error.js.map /***/ }), /***/ 3956: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UnsupportedRuntimeError = void 0; class UnsupportedRuntimeError extends Error { constructor(...args) { super(...args); this.name = 'UnsupportedRuntimeError'; this.code = 500; Error.captureStackTrace(this, UnsupportedRuntimeError); } } exports.UnsupportedRuntimeError = UnsupportedRuntimeError; //# sourceMappingURL=unsupported-runtime-error.js.map /***/ }), /***/ 79790: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getYarnLockfileType = exports.NodeLockfileVersion = exports.getPnpmLockfileVersion = exports.getYarnLockfileVersion = exports.getNpmLockfileVersion = exports.getLockfileVersionFromFile = exports.parsePkgJson = exports.parsePnpmWorkspace = exports.parsePnpmProject = exports.getPnpmLockfileParser = exports.buildDepGraphYarnLockV2Simple = exports.parseYarnLockV2Project = exports.extractPkgsFromYarnLockV2 = exports.buildDepGraphYarnLockV1Workspace = exports.buildDepGraphYarnLockV1WorkspaceCyclesPruned = exports.buildDepGraphYarnLockV1Simple = exports.buildDepGraphYarnLockV1SimpleCyclesPruned = exports.parseYarnLockV1WorkspaceProject = exports.parseYarnLockV1Project = exports.extractPkgsFromYarnLockV1 = exports.parseNpmLockV2Project = exports.OutOfSyncError = exports.InvalidUserInputError = exports.UnsupportedRuntimeError = exports.LockfileType = exports.Scope = exports.getPnpmWorkspaces = exports.getYarnWorkspaces = exports.getYarnWorkspacesFromFiles = exports.buildDepGraphFromCliOutput = exports.buildDepTreeFromFiles = exports.buildDepTree = void 0; const fs = __webpack_require__(57147); const path = __webpack_require__(71017); const parsers_1 = __webpack_require__(64645); Object.defineProperty(exports, "Scope", ({ enumerable: true, get: function () { return parsers_1.Scope; } })); Object.defineProperty(exports, "LockfileType", ({ enumerable: true, get: function () { return parsers_1.LockfileType; } })); Object.defineProperty(exports, "getYarnWorkspaces", ({ enumerable: true, get: function () { return parsers_1.getYarnWorkspaces; } })); Object.defineProperty(exports, "getPnpmWorkspaces", ({ enumerable: true, get: function () { return parsers_1.getPnpmWorkspaces; } })); const package_lock_parser_1 = __webpack_require__(7725); const yarn_lock_parser_1 = __webpack_require__(29532); const yarn2_lock_parser_1 = __webpack_require__(49053); const errors_1 = __webpack_require__(55622); Object.defineProperty(exports, "UnsupportedRuntimeError", ({ enumerable: true, get: function () { return errors_1.UnsupportedRuntimeError; } })); Object.defineProperty(exports, "InvalidUserInputError", ({ enumerable: true, get: function () { return errors_1.InvalidUserInputError; } })); Object.defineProperty(exports, "OutOfSyncError", ({ enumerable: true, get: function () { return errors_1.OutOfSyncError; } })); const cli_parsers_1 = __webpack_require__(2463); Object.defineProperty(exports, "buildDepGraphFromCliOutput", ({ enumerable: true, get: function () { return cli_parsers_1.buildDepGraphFromCliOutput; } })); // Straight to Depgraph Functionality ************* // ************************************************ const dep_graph_builders_1 = __webpack_require__(11110); Object.defineProperty(exports, "parseNpmLockV2Project", ({ enumerable: true, get: function () { return dep_graph_builders_1.parseNpmLockV2Project; } })); Object.defineProperty(exports, "extractPkgsFromYarnLockV1", ({ enumerable: true, get: function () { return dep_graph_builders_1.extractPkgsFromYarnLockV1; } })); Object.defineProperty(exports, "parseYarnLockV1Project", ({ enumerable: true, get: function () { return dep_graph_builders_1.parseYarnLockV1Project; } })); Object.defineProperty(exports, "parseYarnLockV1WorkspaceProject", ({ enumerable: true, get: function () { return dep_graph_builders_1.parseYarnLockV1WorkspaceProject; } })); Object.defineProperty(exports, "buildDepGraphYarnLockV1SimpleCyclesPruned", ({ enumerable: true, get: function () { return dep_graph_builders_1.buildDepGraphYarnLockV1SimpleCyclesPruned; } })); Object.defineProperty(exports, "buildDepGraphYarnLockV1Simple", ({ enumerable: true, get: function () { return dep_graph_builders_1.buildDepGraphYarnLockV1Simple; } })); Object.defineProperty(exports, "buildDepGraphYarnLockV1WorkspaceCyclesPruned", ({ enumerable: true, get: function () { return dep_graph_builders_1.buildDepGraphYarnLockV1WorkspaceCyclesPruned; } })); Object.defineProperty(exports, "buildDepGraphYarnLockV1Workspace", ({ enumerable: true, get: function () { return dep_graph_builders_1.buildDepGraphYarnLockV1Workspace; } })); Object.defineProperty(exports, "extractPkgsFromYarnLockV2", ({ enumerable: true, get: function () { return dep_graph_builders_1.extractPkgsFromYarnLockV2; } })); Object.defineProperty(exports, "parseYarnLockV2Project", ({ enumerable: true, get: function () { return dep_graph_builders_1.parseYarnLockV2Project; } })); Object.defineProperty(exports, "buildDepGraphYarnLockV2Simple", ({ enumerable: true, get: function () { return dep_graph_builders_1.buildDepGraphYarnLockV2Simple; } })); Object.defineProperty(exports, "parsePnpmProject", ({ enumerable: true, get: function () { return dep_graph_builders_1.parsePnpmProject; } })); Object.defineProperty(exports, "parsePnpmWorkspace", ({ enumerable: true, get: function () { return dep_graph_builders_1.parsePnpmWorkspace; } })); Object.defineProperty(exports, "parsePkgJson", ({ enumerable: true, get: function () { return dep_graph_builders_1.parsePkgJson; } })); const lockfile_parser_1 = __webpack_require__(31954); Object.defineProperty(exports, "getPnpmLockfileParser", ({ enumerable: true, get: function () { return lockfile_parser_1.getPnpmLockfileParser; } })); const utils_1 = __webpack_require__(11184); Object.defineProperty(exports, "getLockfileVersionFromFile", ({ enumerable: true, get: function () { return utils_1.getLockfileVersionFromFile; } })); Object.defineProperty(exports, "getNpmLockfileVersion", ({ enumerable: true, get: function () { return utils_1.getNpmLockfileVersion; } })); Object.defineProperty(exports, "getYarnLockfileVersion", ({ enumerable: true, get: function () { return utils_1.getYarnLockfileVersion; } })); Object.defineProperty(exports, "getPnpmLockfileVersion", ({ enumerable: true, get: function () { return utils_1.getPnpmLockfileVersion; } })); Object.defineProperty(exports, "NodeLockfileVersion", ({ enumerable: true, get: function () { return utils_1.NodeLockfileVersion; } })); // ********************************** async function buildDepTree(manifestFileContents, lockFileContents, includeDev = false, lockfileType, strictOutOfSync = true, defaultManifestFileName = 'package.json') { if (!lockfileType) { lockfileType = parsers_1.LockfileType.npm; } else if (lockfileType === parsers_1.LockfileType.yarn) { lockfileType = getYarnLockfileType(lockFileContents); } let lockfileParser; switch (lockfileType) { case parsers_1.LockfileType.npm: lockfileParser = new package_lock_parser_1.PackageLockParser(); break; case parsers_1.LockfileType.yarn: lockfileParser = new yarn_lock_parser_1.YarnLockParser(); break; case parsers_1.LockfileType.yarn2: lockfileParser = new yarn2_lock_parser_1.Yarn2LockParser(); break; default: throw new errors_1.InvalidUserInputError('Unsupported lockfile type ' + `${lockfileType} provided. Only 'npm' or 'yarn' is currently ` + 'supported.'); } const manifestFile = (0, parsers_1.parseManifestFile)(manifestFileContents); if (!manifestFile.name) { manifestFile.name = path.isAbsolute(defaultManifestFileName) ? path.basename(defaultManifestFileName) : defaultManifestFileName; } const lockFile = lockfileParser.parseLockFile(lockFileContents); return lockfileParser.getDependencyTree(manifestFile, lockFile, includeDev, strictOutOfSync); } exports.buildDepTree = buildDepTree; async function buildDepTreeFromFiles(root, manifestFilePath, lockFilePath, includeDev = false, strictOutOfSync = true) { if (!root || !manifestFilePath || !lockFilePath) { throw new Error('Missing required parameters for buildDepTreeFromFiles()'); } const manifestFileFullPath = path.resolve(root, manifestFilePath); const lockFileFullPath = path.resolve(root, lockFilePath); if (!fs.existsSync(manifestFileFullPath)) { throw new errors_1.InvalidUserInputError('Target file package.json not found at ' + `location: ${manifestFileFullPath}`); } if (!fs.existsSync(lockFileFullPath)) { throw new errors_1.InvalidUserInputError('Lockfile not found at location: ' + lockFileFullPath); } const manifestFileContents = fs.readFileSync(manifestFileFullPath, 'utf-8'); const lockFileContents = fs.readFileSync(lockFileFullPath, 'utf-8'); let lockFileType; if (lockFilePath.endsWith('package-lock.json')) { lockFileType = parsers_1.LockfileType.npm; } else if (lockFilePath.endsWith('yarn.lock')) { lockFileType = getYarnLockfileType(lockFileContents, root, lockFilePath); } else { throw new errors_1.InvalidUserInputError(`Unknown lockfile ${lockFilePath}. ` + 'Please provide either package-lock.json or yarn.lock.'); } return await buildDepTree(manifestFileContents, lockFileContents, includeDev, lockFileType, strictOutOfSync, manifestFilePath); } exports.buildDepTreeFromFiles = buildDepTreeFromFiles; function getYarnWorkspacesFromFiles(root, manifestFilePath) { if (!root || !manifestFilePath) { throw new Error('Missing required parameters for getYarnWorkspacesFromFiles()'); } const manifestFileFullPath = path.resolve(root, manifestFilePath); if (!fs.existsSync(manifestFileFullPath)) { throw new errors_1.InvalidUserInputError('Target file package.json not found at ' + `location: ${manifestFileFullPath}`); } const manifestFileContents = fs.readFileSync(manifestFileFullPath, 'utf-8'); return (0, parsers_1.getYarnWorkspaces)(manifestFileContents); } exports.getYarnWorkspacesFromFiles = getYarnWorkspacesFromFiles; function getYarnLockfileType(lockFileContents, root, lockFilePath) { if (lockFileContents.includes('__metadata') || (root && lockFilePath && fs.existsSync(path.resolve(root, lockFilePath.replace('yarn.lock', '.yarnrc.yml'))))) { return parsers_1.LockfileType.yarn2; } else { return parsers_1.LockfileType.yarn; } } exports.getYarnLockfileType = getYarnLockfileType; //# sourceMappingURL=index.js.map /***/ }), /***/ 64645: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getPnpmWorkspaces = exports.getYarnWorkspaces = exports.createDepTreeDepFromDep = exports.getTopLevelDeps = exports.parseManifestFile = exports.LockfileType = exports.Scope = void 0; const errors_1 = __webpack_require__(55622); const js_yaml_1 = __webpack_require__(80474); var Scope; (function (Scope) { Scope["prod"] = "prod"; Scope["dev"] = "dev"; })(Scope = exports.Scope || (exports.Scope = {})); var LockfileType; (function (LockfileType) { LockfileType["npm"] = "npm"; LockfileType["npm7"] = "npm7"; LockfileType["yarn"] = "yarn"; LockfileType["yarn2"] = "yarn2"; LockfileType["pnpm"] = "pnpm"; })(LockfileType = exports.LockfileType || (exports.LockfileType = {})); function parseManifestFile(manifestFileContents) { try { return JSON.parse(manifestFileContents); } catch (e) { throw new errors_1.InvalidUserInputError('package.json parsing failed with error ' + e.message); } } exports.parseManifestFile = parseManifestFile; function getTopLevelDeps({ targetFile, includeDev, includePeerDeps = false, applyYarn2Resolutions = false, }) { var _a, _b; let dependencies = []; const dependenciesIterator = Object.entries(Object.assign(Object.assign(Object.assign({}, targetFile.dependencies), (includeDev ? targetFile.devDependencies : null)), (targetFile.optionalDependencies || {}))); for (const [name, version] of dependenciesIterator) { dependencies.push({ dev: includeDev && targetFile.devDependencies ? !!targetFile.devDependencies[name] : false, name, version, }); } if (includePeerDeps && targetFile.peerDependencies) { for (const [name, version] of Object.entries(targetFile.peerDependencies)) { if ((_b = (_a = targetFile === null || targetFile === void 0 ? void 0 : targetFile.peerDependenciesMeta) === null || _a === void 0 ? void 0 : _a[name]) === null || _b === void 0 ? void 0 : _b.optional) { continue; } dependencies.push({ name, version, }); } } if (applyYarn2Resolutions && targetFile.resolutions) { const resMap = new Map(Object.entries(targetFile.resolutions).map(([resName, resVersion]) => [ resName.replace(`${targetFile.name}/`, ''), resVersion, ])); dependencies = dependencies.map((dep) => resMap.has(dep.name) ? Object.assign(Object.assign({}, dep), { version: resMap.get(dep.name) }) : dep); } return dependencies; } exports.getTopLevelDeps = getTopLevelDeps; function createDepTreeDepFromDep(dep) { return { labels: { scope: dep.dev ? Scope.dev : Scope.prod, }, name: dep.name, version: dep.version, }; } exports.createDepTreeDepFromDep = createDepTreeDepFromDep; function getYarnWorkspaces(targetFile) { try { const packageJson = parseManifestFile(targetFile); if (!!packageJson.workspaces && !!packageJson.private) { if (Array.isArray(packageJson.workspaces)) { return packageJson.workspaces; } if ('packages' in packageJson.workspaces && Array.isArray(packageJson.workspaces.packages)) { return packageJson.workspaces.packages; } } return false; } catch (e) { throw new errors_1.InvalidUserInputError('package.json parsing failed with ' + `error ${e.message}`); } } exports.getYarnWorkspaces = getYarnWorkspaces; function getPnpmWorkspaces(workspacesYamlFile) { try { const rawPnpmWorkspacesYaml = (0, js_yaml_1.load)(workspacesYamlFile, { json: true, schema: js_yaml_1.FAILSAFE_SCHEMA, }); if (rawPnpmWorkspacesYaml && rawPnpmWorkspacesYaml.packages) { if (Array.isArray(rawPnpmWorkspacesYaml.packages)) { return rawPnpmWorkspacesYaml.packages; } } // By default, all packages of all subdirectories are included. // https://pnpm.io/pnpm-workspace_yaml return ['*']; } catch (e) { throw new errors_1.InvalidUserInputError('package.json parsing failed with ' + `error ${e.message}`); } } exports.getPnpmWorkspaces = getPnpmWorkspaces; //# sourceMappingURL=index.js.map /***/ }), /***/ 29999: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LockParserBase = void 0; const _cloneDeep = __webpack_require__(83465); const _isEmpty = __webpack_require__(99245); const _toPairs = __webpack_require__(28052); const graphlib = __webpack_require__(39322); const uuid_1 = __webpack_require__(96771); const event_loop_spinner_1 = __webpack_require__(77158); const baseDebug = __webpack_require__(15158); const cli_parser_utils_1 = __webpack_require__(54717); const _1 = __webpack_require__(64645); const errors_1 = __webpack_require__(55622); const debug = baseDebug('snyk-nodejs-parser'); class LockParserBase { constructor(type, treeSizeLimit) { this.type = type; this.treeSizeLimit = treeSizeLimit; this.pathDelimiter = '|'; } async getDependencyTree(manifestFile, lockfile, includeDev = false, strictOutOfSync = true) { var _a; if (lockfile.type !== this.type) { throw new errors_1.InvalidUserInputError('Unsupported lockfile provided. Please ' + 'provide `package-lock.json`.'); } const yarnLock = lockfile; const depTree = { dependencies: {}, hasDevDependencies: !_isEmpty(manifestFile.devDependencies), name: manifestFile.name, size: 1, version: manifestFile.version || '', }; const nodeVersion = (_a = manifestFile === null || manifestFile === void 0 ? void 0 : manifestFile.engines) === null || _a === void 0 ? void 0 : _a.node; if (nodeVersion) { if (!depTree.meta) { depTree.meta = {}; } depTree.meta.nodeVersion = nodeVersion; } // asked to process empty deps if (_isEmpty(manifestFile.dependencies) && !includeDev) { return depTree; } // prepare a flat map, where dependency path is a key to dependency object // path is an unique identifier for each dependency and corresponds to the // relative path on disc const depMap = this.getDepMap(yarnLock, manifestFile.resolutions); // all paths are identified, we can create a graph representing what depends on what const depGraph = this.createGraphOfDependencies(depMap, strictOutOfSync); // topological sort will be applied and it requires acyclic graphs let cycleStarts = {}; if (!graphlib.alg.isAcyclic(depGraph)) { const cycles = graphlib.alg.findCycles(depGraph); for (const cycle of cycles) { // Since one of top level dependencies can be a start of cycle and that node // will be duplicated, we need to store a link between original node // and the new one in order to identify those duplicated top level dependencies cycleStarts = Object.assign(Object.assign({}, cycleStarts), this.removeCycle(cycle, depMap, depGraph)); } } // transform depMap to a map of PkgTrees const { depTrees, depTreesSizes } = await this.createDepTrees(depMap, depGraph); // Only include peerDependencies if using npm and npm is at least // version 7 as npm v7 automatically installs peerDependencies // get trees for dependencies from manifest file const topLevelDeps = (0, _1.getTopLevelDeps)({ targetFile: manifestFile, includeDev, includePeerDeps: lockfile.type === _1.LockfileType.npm7, applyYarn2Resolutions: lockfile.type === _1.LockfileType.yarn2, }); // number of dependencies including root one let treeSize = 1; for (const dep of topLevelDeps) { if (treeSize > this.treeSizeLimit) { throw new errors_1.TreeSizeLimitError(); } // if any of top level dependencies is a part of cycle // it now has a different item in the map const key = this.getDepTreeKey(dep); const depName = cycleStarts[key] || key; if (depTrees[depName]) { // if the top level dependency is dev, all children are dev depTree.dependencies[dep.name] = dep.dev ? this.setDevDepRec(_cloneDeep(depTrees[depName])) : depTrees[depName]; treeSize += depTreesSizes[depName]; if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } else if (/^file:/.test(dep.version)) { depTree.dependencies[dep.name] = (0, _1.createDepTreeDepFromDep)(dep); treeSize++; } else { // TODO: also check the package version // for a stricter check if (strictOutOfSync) { throw new errors_1.OutOfSyncError(dep.name, this.type); } depTree.dependencies[dep.name] = (0, _1.createDepTreeDepFromDep)(dep); if (!depTree.dependencies[dep.name].labels) { depTree.dependencies[dep.name].labels = {}; } depTree.dependencies[dep.name].labels.missingLockFileEntry = 'true'; treeSize++; } } depTree.size = treeSize; return depTree; } setDevDepRec(pkgTree) { for (const [name, subTree] of _toPairs(pkgTree.dependencies)) { pkgTree.dependencies[name] = this.setDevDepRec(subTree); } pkgTree.labels = Object.assign(Object.assign({}, pkgTree.labels), { scope: _1.Scope.dev }); return pkgTree; } /* Algorithm for cycle removal: For every node in a cycle: 1. Create a duplicate of entry node (without edges) 2. For every cyclic dependency of entry node, create a duplicate of the dependency and connect it with the duplicated entry node 3.a If edge goes to already-visited dependency, end of cycle is found; update metadata and do not continue traversing 3.b Follow the edge and repeat the process, storing visited dependency-paths. All non-cyclic dependencies of duplicated node need to be updated. 4. All non-cyclic dependencies or dependants of original node need to be updated to be connected with the duplicated one Once completed for all nodes in a cycle, original cyclic nodes can be removed. */ removeCycle(cycle, depMap, depGraph) { /* FUNCTION DEFINITION To keep an order of algorithm steps readable, function is defined on-the-fly Arrow function is used for calling `this` without .bind(this) in the end */ const acyclicDuplicationRec = (node, traversed, currentCycle, nodeCopy) => { // 2. For every cyclic dependency of entry node... const edgesToProcess = depGraph.inEdges(node).filter((e) => currentCycle.includes(e.v)); for (const edge of edgesToProcess) { // ... create a duplicate of the dependency... const child = edge.v; const dependencyCopy = this.cloneNodeWithoutEdges(child, depMap, depGraph); // ...and connect it with the duplicated entry node depGraph.setEdge(dependencyCopy, nodeCopy); // 3.a If edge goes to already-visited dependency, end of cycle is found; if (traversed.includes(child)) { // update metadata and labels and do not continue traversing if (!depMap[dependencyCopy].labels) { depMap[dependencyCopy].labels = {}; } depMap[dependencyCopy].labels.pruned = 'cyclic'; } else { // 3.b Follow the edge and repeat the process, storing visited dependency-paths acyclicDuplicationRec(child, [...traversed, node], currentCycle, dependencyCopy); // All non-cyclic dependencies of duplicated node need to be updated. this.cloneAcyclicNodeEdges(child, dependencyCopy, cycle, depGraph, { inEdges: true, outEdges: false, }); } } }; const cycleStarts = {}; // For every node in a cycle: for (const start of cycle) { // 1. Create a uniqe duplicate of entry node (without edges) const clonedNode = this.cloneNodeWithoutEdges(start, depMap, depGraph); cycleStarts[start] = clonedNode; // CALL of previously defined function acyclicDuplicationRec(start, [], cycle, clonedNode); // 4. All non-cyclic dependencies or dependants of original node need to be // updated to be connected with the duplicated one this.cloneAcyclicNodeEdges(start, clonedNode, cycle, depGraph, { inEdges: true, outEdges: true, }); } // Once completed for all nodes in a cycle, original cyclic nodes can // be removed. for (const start of cycle) { depGraph.removeNode(start); } return cycleStarts; } cloneAcyclicNodeEdges(nodeFrom, nodeTo, cycle, depGraph, { inEdges, outEdges }) { // node has to have edges const edges = depGraph.nodeEdges(nodeFrom); if (outEdges) { const parentEdges = edges.filter((e) => !cycle.includes(e.w)); for (const edge of parentEdges) { const parent = edge.w; depGraph.setEdge(nodeTo, parent); } } if (inEdges) { const childEdges = edges.filter((e) => !cycle.includes(e.v)); for (const edge of childEdges) { const child = edge.v; depGraph.setEdge(child, nodeTo); } } } cloneNodeWithoutEdges(node, depMap, depGraph) { const newNode = node + (0, uuid_1.v4)(); // update depMap with new node depMap[newNode] = _cloneDeep(depMap[node]); // add new node to the graph depGraph.setNode(newNode); return newNode; } createGraphOfDependencies(depMap, strictOutOfSync = true) { const depGraph = new graphlib.Graph(); for (const depKey of Object.keys(depMap)) { depGraph.setNode(depKey); } for (const [depPath, dep] of Object.entries(depMap)) { for (const depName of dep.requires) { const subDepPath = this.findDepsPath(depPath, depName, depMap, strictOutOfSync); // direction is from the dependency to the package requiring it depGraph.setEdge(subDepPath, depPath); } } return depGraph; } // dependency in package-lock.json v1 can be defined either inside `dependencies` // of other dependency or anywhere upward towards root findDepsPath(startPath, depName, depMap, strictOutOfSync = true) { const depPath = startPath.split(this.pathDelimiter); while (depPath.length) { const currentPath = depPath.concat(depName).join(this.pathDelimiter); if (depMap[currentPath]) { return currentPath; } depPath.pop(); } if (!depMap[depName]) { debug(`Dependency ${depName} not found`); if (strictOutOfSync) { throw new errors_1.OutOfSyncError(depName, this.type); } } return depName; } // Algorithm is based on dynamic programming technique and tries to build // "more simple" trees and compose them into bigger ones. async createDepTrees(depMap, depGraph) { var _a; // Graph has to be acyclic if (!graphlib.alg.isAcyclic(depGraph)) { throw new Error('Cycles were not removed from graph.'); } const depTrees = {}; const depTreesSizes = {}; // topological sort guarantees that when we create a pkg-tree for a dep, // all it's sub-trees were already created. This also implies that leaf // packages will be processed first as they have no sub-trees. const depOrder = graphlib.alg.topsort(depGraph); while (depOrder.length) { const depKey = depOrder.shift(); const dep = depMap[depKey]; let treeSize = 1; if (!dep) { debug(`Missing entry for ${depKey}`); continue; } // direction is from the dependency to the package requiring it, so we are // looking for predecessors for (const subDepPath of depGraph.predecessors(depKey)) { let subDep = depTrees[subDepPath]; if (!dep.dependencies) { dep.dependencies = {}; } if (!subDep) { debug(`Missing entry for ${subDepPath}`); const { name, identifier } = (0, cli_parser_utils_1.extractNameAndIdentifier)(subDepPath); subDep = { name: name, version: identifier, dependencies: {}, labels: Object.assign({ missingLockFileEntry: 'true' }, (((_a = dep.labels) === null || _a === void 0 ? void 0 : _a.scope) && { scope: dep.labels.scope })), }; treeSize += 1; } else { treeSize += depTreesSizes[subDepPath]; } dep.dependencies[subDep.name] = subDep; } const depTreeDep = { labels: dep.labels, name: dep.name, version: dep.version, }; if (dep.dependencies) { depTreeDep.dependencies = dep.dependencies; } depTrees[depKey] = depTreeDep; depTreesSizes[depKey] = treeSize; // Since this code doesn't handle any I/O or network, we need to force // event loop to tick while being used in server for request processing if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } return { depTrees, depTreesSizes }; } getDepMap(lockfile, // eslint-disable-line @typescript-eslint/no-unused-vars resolutions) { throw new Error('Not implemented'); } // eslint-disable-next-line @typescript-eslint/no-unused-vars getDepTreeKey(dep) { throw new Error('Not implemented'); } } exports.LockParserBase = LockParserBase; //# sourceMappingURL=lock-parser-base.js.map /***/ }), /***/ 7725: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PackageLockParser = void 0; const index_1 = __webpack_require__(64645); const errors_1 = __webpack_require__(55622); const lock_parser_base_1 = __webpack_require__(29999); const config_1 = __webpack_require__(76123); class PackageLockParser extends lock_parser_base_1.LockParserBase { constructor() { super(index_1.LockfileType.npm, config_1.config.NPM_TREE_SIZE_LIMIT); } parseLockFile(lockFileContents) { try { const packageLock = JSON.parse(lockFileContents); packageLock.type = packageLock.lockfileVersion === 1 ? index_1.LockfileType.npm : index_1.LockfileType.npm7; this.type = packageLock.type; return packageLock; } catch (e) { throw new errors_1.InvalidUserInputError('package-lock.json parsing failed with ' + `error ${e.message}`); } } async getDependencyTree(manifestFile, lockfile, includeDev = false, strictOutOfSync = true) { const dependencyTree = await super.getDependencyTree(manifestFile, lockfile, includeDev, strictOutOfSync); const meta = { lockfileVersion: lockfile.lockfileVersion, packageManager: 'npm', }; const depTreeWithMeta = Object.assign(Object.assign({}, dependencyTree), { meta: Object.assign(Object.assign({}, dependencyTree.meta), meta) }); return depTreeWithMeta; } getDepMap(lockfile) { const packageLock = lockfile; const depMap = {}; const flattenLockfileRec = (lockfileDeps, path) => { for (const [depName, dep] of Object.entries(lockfileDeps)) { const depNode = { labels: { scope: dep.dev ? index_1.Scope.dev : index_1.Scope.prod, }, name: depName, requires: [], version: dep.version, }; if (dep.requires) { depNode.requires = Object.keys(dep.requires); } const depPath = [...path, depName]; const depKey = depPath.join(this.pathDelimiter); depMap[depKey] = depNode; if (dep.dependencies) { flattenLockfileRec(dep.dependencies, depPath); } } }; flattenLockfileRec(packageLock.dependencies || {}, []); return depMap; } getDepTreeKey(dep) { return dep.name; } } exports.PackageLockParser = PackageLockParser; //# sourceMappingURL=package-lock-parser.js.map /***/ }), /***/ 29532: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.YarnLockParser = void 0; const yarnLockfileParser = __webpack_require__(7615); const index_1 = __webpack_require__(64645); const errors_1 = __webpack_require__(55622); const lock_parser_base_1 = __webpack_require__(29999); const config_1 = __webpack_require__(76123); class YarnLockParser extends lock_parser_base_1.LockParserBase { constructor() { super(index_1.LockfileType.yarn, config_1.config.YARN_TREE_SIZE_LIMIT); } parseLockFile(lockFileContents) { try { const yarnLock = yarnLockfileParser.parse(lockFileContents); yarnLock.dependencies = yarnLock.object; yarnLock.type = this.type; return yarnLock; } catch (e) { throw new errors_1.InvalidUserInputError(`yarn.lock parsing failed with an error: ${e.message}`); } } async getDependencyTree(manifestFile, lockfile, includeDev = false, strictOutOfSync = true) { const depTree = await super.getDependencyTree(manifestFile, lockfile, includeDev, strictOutOfSync); const meta = { lockfileVersion: 1, packageManager: 'yarn' }; const depTreeWithMeta = Object.assign(Object.assign({}, depTree), { meta: Object.assign(Object.assign({}, depTree.meta), meta) }); return depTreeWithMeta; } getDepMap(lockfile) { const yarnLockfile = lockfile; const depMap = {}; for (const [depName, dep] of Object.entries(yarnLockfile.object)) { const subDependencies = Object.entries(Object.assign(Object.assign({}, (dep.dependencies || {})), (dep.optionalDependencies || {}))); depMap[depName] = { labels: { scope: index_1.Scope.prod, }, name: getName(depName), requires: subDependencies.map(([key, ver]) => `${key}@${ver}`), version: dep.version, }; } return depMap; } getDepTreeKey(dep) { return `${dep.name}@${dep.version}`; } } exports.YarnLockParser = YarnLockParser; function getName(depName) { return depName.slice(0, depName.indexOf('@', 1)); } //# sourceMappingURL=yarn-lock-parser.js.map /***/ }), /***/ 58801: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.yarnLockFileKeyNormalizer = void 0; const _flatMap = __webpack_require__(78661); const BUILTIN_PLACEHOLDER = 'builtin'; const MULTIPLE_KEYS_REGEXP = / *, */g; const keyNormalizer = (parseDescriptor, parseRange) => (rawDescriptor) => { // See https://yarnpkg.com/features/protocols const descriptors = [rawDescriptor]; const descriptor = parseDescriptor(rawDescriptor); const name = `${descriptor.scope ? '@' + descriptor.scope + '/' : ''}${descriptor.name}`; const range = parseRange(descriptor.range); const protocol = range.protocol; switch (protocol) { case 'npm:': case 'file:': descriptors.push(`${name}@${range.selector}`); descriptors.push(`${name}@${protocol}${range.selector}`); break; case 'git:': case 'git+ssh:': case 'git+http:': case 'git+https:': case 'github:': if (range.source) { descriptors.push(`${name}@${protocol}${range.source}${range.selector ? '#' + range.selector : ''}`); } else { descriptors.push(`${name}@${protocol}${range.selector}`); } break; case 'patch:': if (range.source && range.selector.indexOf(BUILTIN_PLACEHOLDER) === 0) { descriptors.push(range.source); } else { descriptors.push(`${name}@${protocol}${range.source}${range.selector ? '#' + range.selector : ''}`); } break; case null: case undefined: if (range.source) { descriptors.push(`${name}@${range.source}#${range.selector}`); } else { descriptors.push(`${name}@${range.selector}`); } break; case 'http:': case 'https:': case 'link:': case 'portal:': case 'exec:': case 'workspace:': case 'virtual:': default: // For user defined plugins descriptors.push(`${name}@${protocol}${range.selector}`); break; } return descriptors; }; const yarnLockFileKeyNormalizer = (parseDescriptor, parseRange) => (fullDescriptor) => { const allKeys = fullDescriptor .split(MULTIPLE_KEYS_REGEXP) .map(keyNormalizer(parseDescriptor, parseRange)); return new Set(_flatMap(allKeys)); }; exports.yarnLockFileKeyNormalizer = yarnLockFileKeyNormalizer; //# sourceMappingURL=yarn-utils.js.map /***/ }), /***/ 49053: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Yarn2LockParser = void 0; const js_yaml_1 = __webpack_require__(80474); const yarnCore = __webpack_require__(74876); const lock_parser_base_1 = __webpack_require__(29999); const _1 = __webpack_require__(64645); const config_1 = __webpack_require__(76123); const errors_1 = __webpack_require__(55622); const yarn_utils_1 = __webpack_require__(58801); class Yarn2LockParser extends lock_parser_base_1.LockParserBase { constructor() { super(_1.LockfileType.yarn2, config_1.config.YARN_TREE_SIZE_LIMIT); } parseLockFile(lockFileContents) { try { const rawYarnLock = (0, js_yaml_1.load)(lockFileContents, { json: true, schema: js_yaml_1.FAILSAFE_SCHEMA, }); delete rawYarnLock.__metadata; const dependencies = {}; const structUtils = yarnCore.structUtils; const parseDescriptor = structUtils.parseDescriptor; const parseRange = structUtils.parseRange; const keyNormalizer = (0, yarn_utils_1.yarnLockFileKeyNormalizer)(parseDescriptor, parseRange); Object.entries(rawYarnLock).forEach(([fullDescriptor, versionData]) => { keyNormalizer(fullDescriptor).forEach((descriptor) => { dependencies[descriptor] = versionData; }); }); return { dependencies, lockfileType: _1.LockfileType.yarn2, object: dependencies, type: _1.LockfileType.yarn2, }; } catch (e) { throw new errors_1.InvalidUserInputError(`yarn.lock parsing failed with an error: ${e.message}`); } } async getDependencyTree(manifestFile, lockfile, includeDev = false, strictOutOfSync = true) { const depTree = await super.getDependencyTree(manifestFile, lockfile, includeDev, strictOutOfSync); const meta = { lockfileVersion: 2, packageManager: 'yarn' }; const depTreeWithMeta = Object.assign(Object.assign({}, depTree), { meta: Object.assign(Object.assign({}, depTree.meta), meta) }); return depTreeWithMeta; } getDepMap(lockfile, resolutions) { const yarnLockfile = lockfile; const depMap = {}; const dependencies = lockfile.dependencies || {}; for (const [depName, dep] of Object.entries(yarnLockfile.object)) { const subDependencies = Object.entries(Object.assign(Object.assign({}, (dep.dependencies || {})), (dep.optionalDependencies || {}))).map(([key, ver]) => findResolutions(dependencies, depName, key, resolutions) || `${key}@${ver}`); depMap[depName] = { labels: { scope: _1.Scope.prod, }, name: getName(depName), requires: subDependencies, version: dep.version, }; } return depMap; } getDepTreeKey(dep) { return `${dep.name}@${dep.version}`; } } exports.Yarn2LockParser = Yarn2LockParser; function getName(depName) { return depName.slice(0, depName.indexOf('@', 1)); } function findResolutions(dependencies, depName, subDepKey, resolutions) { if (!resolutions) return; const resolutionKeys = Object.keys(resolutions); const index = depName.indexOf('@', 1); const name = depName.slice(0, index); const version = depName.slice(index + 1); const firstMatchingResolution = resolutionKeys.find((res) => { if (!res.endsWith(subDepKey)) { return false; } const leadingPkg = res.split(subDepKey)[0].slice(0, -1); const noSpecifiedParent = !leadingPkg; const specifiedParentMatchesCurrentDep = leadingPkg === name; const specifiedParentWithVersionMatches = leadingPkg.includes(name) && leadingPkg.includes(dependencies[`${name}@${version}`].version); return (noSpecifiedParent || specifiedParentMatchesCurrentDep || specifiedParentWithVersionMatches); }); if (resolutionKeys && firstMatchingResolution) { return `${subDepKey}@${resolutions[firstMatchingResolution]}`; } } //# sourceMappingURL=yarn2-lock-parser.js.map /***/ }), /***/ 11184: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getNpmLockfileVersion = exports.getYarnLockfileVersion = exports.getPnpmLockfileVersion = exports.getLockfileVersionFromFile = exports.NodeLockfileVersion = void 0; const fs_1 = __webpack_require__(57147); const js_yaml_1 = __webpack_require__(80474); const errors_1 = __webpack_require__(55622); const error_catalog_nodejs_public_1 = __webpack_require__(88404); var NodeLockfileVersion; (function (NodeLockfileVersion) { NodeLockfileVersion["NpmLockV1"] = "NPM_LOCK_V1"; NodeLockfileVersion["NpmLockV2"] = "NPM_LOCK_V2"; NodeLockfileVersion["NpmLockV3"] = "NPM_LOCK_V3"; NodeLockfileVersion["YarnLockV1"] = "YARN_LOCK_V1"; NodeLockfileVersion["YarnLockV2"] = "YARN_LOCK_V2"; NodeLockfileVersion["PnpmLockV5"] = "PNPM_LOCK_V5"; NodeLockfileVersion["PnpmLockV6"] = "PNPM_LOCK_V6"; NodeLockfileVersion["PnpmLockV9"] = "PNPM_LOCK_V9"; })(NodeLockfileVersion = exports.NodeLockfileVersion || (exports.NodeLockfileVersion = {})); const getLockfileVersionFromFile = (targetFile) => { const lockFileContents = (0, fs_1.readFileSync)(targetFile, 'utf-8'); if (targetFile.endsWith('package-lock.json')) { return getNpmLockfileVersion(lockFileContents); } else if (targetFile.endsWith('yarn.lock')) { return getYarnLockfileVersion(lockFileContents); } else if (targetFile.endsWith('pnpm-lock.yaml')) { return getPnpmLockfileVersion(lockFileContents); } else { throw new errors_1.InvalidUserInputError(`Unknown lockfile ${targetFile}. ` + 'Please provide either package-lock.json, yarn.lock or pnpm-lock.yaml'); } }; exports.getLockfileVersionFromFile = getLockfileVersionFromFile; function getPnpmLockfileVersion(lockFileContents) { const rawPnpmLock = (0, js_yaml_1.load)(lockFileContents, { json: true, schema: js_yaml_1.FAILSAFE_SCHEMA, }); const { lockfileVersion } = rawPnpmLock; if (lockfileVersion.startsWith('5')) { return NodeLockfileVersion.PnpmLockV5; } else if (lockfileVersion.startsWith('6')) { return NodeLockfileVersion.PnpmLockV6; } else if (lockfileVersion.startsWith('9')) { return NodeLockfileVersion.PnpmLockV9; } else { throw new error_catalog_nodejs_public_1.OpenSourceEcosystems.PnpmUnsupportedLockfileVersionError(`The pnpm-lock.yaml lockfile version ${lockfileVersion} is not supported`); } } exports.getPnpmLockfileVersion = getPnpmLockfileVersion; function getYarnLockfileVersion(lockFileContents) { if (lockFileContents.includes('__metadata')) { return NodeLockfileVersion.YarnLockV2; } else { return NodeLockfileVersion.YarnLockV1; } } exports.getYarnLockfileVersion = getYarnLockfileVersion; function getNpmLockfileVersion(lockFileContents) { try { const lockfileJson = JSON.parse(lockFileContents); const lockfileVersion = lockfileJson.lockfileVersion || null; switch (lockfileVersion) { case null: case 1: return NodeLockfileVersion.NpmLockV1; case 2: return NodeLockfileVersion.NpmLockV2; case 3: return NodeLockfileVersion.NpmLockV3; default: throw new errors_1.InvalidUserInputError(`Unsupported npm lockfile version in package-lock.json. ` + 'Please provide a package-lock.json with lockfileVersion 1, 2 or 3'); } } catch (e) { throw new errors_1.InvalidUserInputError(`Problem parsing package-lock.json - make sure the package-lock.json is a valid JSON file`); } } exports.getNpmLockfileVersion = getNpmLockfileVersion; //# sourceMappingURL=utils.js.map /***/ }), /***/ 88406: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BigTreeError = void 0; class BigTreeError extends Error { constructor(...args) { super(...args); this.code = 422; this.name = 'BigTreeError'; Error.captureStackTrace(this, BigTreeError); } } exports.BigTreeError = BigTreeError; //# sourceMappingURL=big-tree-error.js.map /***/ }), /***/ 54655: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CliCommandError = void 0; class CliCommandError extends Error { constructor(...args) { super(...args); this.code = 422; this.name = 'CliCommandError'; Error.captureStackTrace(this, CliCommandError); } } exports.CliCommandError = CliCommandError; //# sourceMappingURL=cli-command-error.js.map /***/ }), /***/ 61266: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FileNotFoundError = void 0; class FileNotFoundError extends Error { constructor(...args) { super(...args); this.code = 422; this.name = 'FileNotFoundError'; Error.captureStackTrace(this, FileNotFoundError); } } exports.FileNotFoundError = FileNotFoundError; //# sourceMappingURL=file-not-found-error.js.map /***/ }), /***/ 7717: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FileNotProcessableError = void 0; class FileNotProcessableError extends Error { constructor(...args) { super(...args); this.code = 422; this.name = 'FileNotProcessableError'; Error.captureStackTrace(this, FileNotProcessableError); } } exports.FileNotProcessableError = FileNotProcessableError; //# sourceMappingURL=file-not-processable-error.js.map /***/ }), /***/ 62153: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.InvalidTargetFile = exports.InvalidManifestError = exports.FileNotProcessableError = exports.FileNotFoundError = exports.CliCommandError = exports.BigTreeError = void 0; var big_tree_error_1 = __webpack_require__(88406); Object.defineProperty(exports, "BigTreeError", ({ enumerable: true, get: function () { return big_tree_error_1.BigTreeError; } })); var cli_command_error_1 = __webpack_require__(54655); Object.defineProperty(exports, "CliCommandError", ({ enumerable: true, get: function () { return cli_command_error_1.CliCommandError; } })); var file_not_found_error_1 = __webpack_require__(61266); Object.defineProperty(exports, "FileNotFoundError", ({ enumerable: true, get: function () { return file_not_found_error_1.FileNotFoundError; } })); var file_not_processable_error_1 = __webpack_require__(7717); Object.defineProperty(exports, "FileNotProcessableError", ({ enumerable: true, get: function () { return file_not_processable_error_1.FileNotProcessableError; } })); var invalid_manifest_error_1 = __webpack_require__(22795); Object.defineProperty(exports, "InvalidManifestError", ({ enumerable: true, get: function () { return invalid_manifest_error_1.InvalidManifestError; } })); var invalid_target_file_1 = __webpack_require__(18847); Object.defineProperty(exports, "InvalidTargetFile", ({ enumerable: true, get: function () { return invalid_target_file_1.InvalidTargetFile; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 51901: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.InvalidFolderFormatError = void 0; class InvalidFolderFormatError extends Error { constructor(...args) { super(...args); this.code = 422; this.name = 'InvalidFolderFormat'; Error.captureStackTrace(this, InvalidFolderFormatError); } } exports.InvalidFolderFormatError = InvalidFolderFormatError; //# sourceMappingURL=invalid-folder-format-error.js.map /***/ }), /***/ 22795: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.InvalidManifestError = void 0; class InvalidManifestError extends Error { constructor(...args) { super(...args); this.code = 422; this.name = 'InvalidManifestError'; Error.captureStackTrace(this, InvalidManifestError); } } exports.InvalidManifestError = InvalidManifestError; //# sourceMappingURL=invalid-manifest-error.js.map /***/ }), /***/ 18847: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.InvalidTargetFile = void 0; class InvalidTargetFile extends Error { constructor(...args) { super(...args); this.code = 422; this.name = 'InvalidTargetFile'; Error.captureStackTrace(this, InvalidTargetFile); } } exports.InvalidTargetFile = InvalidTargetFile; //# sourceMappingURL=invalid-target-file.js.map /***/ }), /***/ 82843: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.inspect = inspect; const nugetParser = __webpack_require__(66677); const path = __webpack_require__(71017); const paketParser = __webpack_require__(15371); const types_1 = __webpack_require__(46652); const errors_1 = __webpack_require__(62153); function determineManifestType(filename) { switch (true) { case /project.json$/.test(filename): { return types_1.ManifestType.PROJECT_JSON; } case /project.assets.json$/.test(filename): { return types_1.ManifestType.DOTNET_CORE; } case /packages.config$/.test(filename): { return types_1.ManifestType.PACKAGES_CONFIG; } case /paket.dependencies$/.test(filename): { return types_1.ManifestType.PAKET; } default: { throw new errors_1.InvalidTargetFile('Could not determine manifest type for ' + filename); } } } async function inspect(root, targetFile, options) { options = options || {}; let manifestType; try { manifestType = determineManifestType(path.basename(targetFile || root)); } catch (error) { return Promise.reject(error); } const createPackageTree = (depTree) => { const targetFramework = depTree.meta ? depTree.meta.targetFramework : undefined; delete depTree.meta; return { package: depTree, plugin: { name: 'snyk-nuget-plugin', targetFile, targetRuntime: targetFramework, }, }; }; if (manifestType === types_1.ManifestType.PAKET) { return paketParser .buildDepTreeFromFiles(root, targetFile, path.join(path.dirname(targetFile), 'paket.lock'), options['include-dev'] || options.dev, // TODO: remove include-dev when no longer used. options.strict) .then(createPackageTree); } if (options['dotnet-target-framework'] && !options['dotnet-runtime-resolution']) { return Promise.reject(new errors_1.CliCommandError('target framework flag is currently only supported when also scanning with runtime resolution using the `--dotnet-runtime-resolution` flag')); } if (options['dotnet-runtime-resolution']) { if (manifestType !== types_1.ManifestType.DOTNET_CORE) { return Promise.reject(new errors_1.FileNotProcessableError(`runtime resolution flag is currently only supported for: .NET versions 5 and higher, all versions of .NET Core and all versions of .NET Standard projects. Supplied project type was parsed as ${manifestType}.`)); } console.warn(` \x1b[33m⚠ WARNING\x1b[0m: Testing a .NET project with runtime resolution enabled. This should be considered experimental and not relied upon for production use. Please report issues with this beta feature by submitting a support ticket, and attach the output of running this command with the debug (-d) flag at \x1b[4mhttps://support.snyk.io/hc/en-us/requests/new\x1b[0m.`); const results = await nugetParser.buildDepGraphFromFiles(root, targetFile, manifestType, options['assets-project-name'], options['project-name-prefix'], options['dotnet-target-framework']); // Construct a MultiProjectResult to send to either the CLI or the SCM scanner. const multiProjectResult = { plugin: { name: 'snyk-nuget-plugin', targetFile, }, scannedProjects: [], }; for (const result of results) { multiProjectResult.scannedProjects.push({ targetFile: targetFile, depGraph: result.dependencyGraph, meta: { targetRuntime: result.targetFramework, }, }); } return multiProjectResult; } return nugetParser .buildDepTreeFromFiles(root, targetFile, options.packagesFolder, manifestType, options['assets-project-name'], options['project-name-prefix']) .then(createPackageTree); } //# sourceMappingURL=index.js.map /***/ }), /***/ 62886: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.validate = validate; exports.restore = restore; exports.run = run; exports.publish = publish; const debugModule = __webpack_require__(15158); const errors_1 = __webpack_require__(62153); const path = __webpack_require__(71017); const subprocess = __webpack_require__(24862); const fs = __webpack_require__(57147); const os = __webpack_require__(22037); const debug = debugModule('snyk'); async function handle(operation, command, args) { debug(`running dotnet command: ${operation}: ${command}`); try { return await subprocess.execute(command, args); } catch (error) { if (!(typeof error === 'object' && error !== null && 'stdout' in error && 'stderr' in error)) { throw new errors_1.CliCommandError(`dotnet ${operation} failed with error: ${error}`); } const message = error.stdout || error.stderr; throw new errors_1.CliCommandError(`dotnet ${operation} failed with error: ${message}`); } } async function validate() { const command = 'dotnet'; const args = ['--version']; try { const result = await handle('version', command, args); return result.stdout.trim(); } catch (error) { debug('dotnet tool not found, did you install dotnet core?'); throw error; } } async function restore(projectPath) { const command = 'dotnet'; const args = [ 'restore', // Get a larger amount of debugging information to stdout in case something fails. // Useful for customers to attempt self-debugging before raising support requests. '--verbosity', 'normal', `"${projectPath}"`, '--p=TreatWarningsAsErrors=false;WarningsAsErrors=', ]; await handle('restore', command, args); return; } async function run(projectPath, options) { const command = 'dotnet'; const args = ['run', '--project', projectPath].concat(options); const response = await handle('run', command, args); const stdout = response.stdout; return stdout.slice(stdout.indexOf('{') !== -1 ? stdout.indexOf('{') : stdout.length); } async function publish(projectPath, targetFramework) { const command = 'dotnet'; const args = ['publish', '--nologo']; // Self-contained: Create all required .dlls for version investigation, don't rely on the environment. args.push('--sc'); // Use the current runtime of whatever platform we are on. // This ensures that .dlls will be packaged containing the runtime assembly versions. // TODO: (OSM-521) if/when we allow this to be dynamic based on user input, remember to change this. args.push('--use-current-runtime'); // If your .csproj file contains multiple references, you need to supply which one you want to publish. if (targetFramework) { args.push('--framework'); args.push(targetFramework); } // Define a temporary output dir to use for detecting .dlls to use for runtime version assembly detection. const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), `snyk-nuget-plugin-publish-csharp-`)); // Changing the PublishDir a temporary directory. // See https://learn.microsoft.com/en-us/dotnet/core/compatibility/sdk/7.0/solution-level-output-no-longer-valid#recommended-action // about why we're not using `--output` for this. // Some projects can have turned to false, that won't allow `publish` command to generate the binary we // need for resolution, so we're going to force to be true. // See https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-publish#msbuild // Some projects can have turned on, that won't generate the self-container binary we need, // so we're disabling it during our scan. // See https://learn.microsoft.com/en-us/dotnet/core/deploying/single-file/overview?tabs=cli // Some projects can have tuned on, that will throw errors on any warning, making the project impossible to scan. // Or, they can have a list of warning codes in that will do the same thing as above. So we're disabling them. args.push(`--p:PublishDir=${tempDir};SnykTest=true;IsPublishable=true;PublishSingleFile=false;TreatWarningsAsErrors=false;WarningsAsErrors=`); // The path that contains either some form of project file, or a .sln one. // See: https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-publish#arguments args.push(`"${projectPath}"`); await handle('publish', command, args); return tempDir; } //# sourceMappingURL=dotnet.js.map /***/ }), /***/ 24862: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.execute = execute; const child_process_1 = __webpack_require__(32081); function makeSpawnOptions(options) { const spawnOptions = { shell: false, env: { ...process.env }, }; if (options?.cwd) { spawnOptions.cwd = options.cwd; } if (options?.env) { spawnOptions.env = { ...spawnOptions.env, ...options.env }; } else { spawnOptions.env = { ...spawnOptions.env }; } // Before spawning an external process, we check if we need to // restore the system proxy configuration, which overrides the CLI internal proxy configuration. if (process.env.SNYK_SYSTEM_HTTP_PROXY !== undefined) { spawnOptions.env.HTTP_PROXY = process.env.SNYK_SYSTEM_HTTP_PROXY; } if (process.env.SNYK_SYSTEM_HTTPS_PROXY !== undefined) { spawnOptions.env.HTTPS_PROXY = process.env.SNYK_SYSTEM_HTTPS_PROXY; } if (process.env.SNYK_SYSTEM_NO_PROXY !== undefined) { spawnOptions.env.NO_PROXY = process.env.SNYK_SYSTEM_NO_PROXY; } return spawnOptions; } function execute(command, args, options) { const spawnOptions = makeSpawnOptions(options); return new Promise((resolve, reject) => { let stdout = ''; let stderr = ''; const proc = (0, child_process_1.spawn)(command, args, spawnOptions); proc.stdout?.on('data', (data) => { stdout = stdout + data; }); proc.stderr?.on('data', (data) => { stderr = stderr + data; }); proc.on('close', (code) => { if (code !== 0) { return reject({ stdout, stderr }); } resolve({ stdout, stderr }); }); }); } //# sourceMappingURL=subprocess.js.map /***/ }), /***/ 56421: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.generate = generate; exports.tearDown = tearDown; const path = __webpack_require__(71017); const fs = __webpack_require__(57147); const os = __webpack_require__(22037); const debugModule = __webpack_require__(15158); const NodeCache = __webpack_require__(70321); const crypto = __webpack_require__(6113); const debug = debugModule('snyk'); const cache = new NodeCache(); // Use a simple, fast and not secure hashing algorithm just to ensure we don't return the same cached location for // different types of files. This is mostly to speed up performance of tests, but in theory will also affect customers // when scanning for multiple TargetFrameworks. function generateCacheKey(files) { const hash = crypto.createHash('sha256'); files .map((f) => f.contents) .forEach((content) => { hash.update(content); }); return hash.digest('hex'); } // Importing .NET code from Typescript is not trivial and a bit lose cannon programming. However, we also want to keep // this project dependent on as few packages as possible, so instead of opting into some "run .NET in Typescript" package, // we do the simplest, which is this. Makes C# debugging a bit harder, but it's a compromise. // Further, we also utilize this for our test fixtures. Running tests in parallel can cause race conditions for fixtures // at-rest, if two tests are `dotnet publish`'ing to the same fixture folder. So we supply a generator for populating // fixtures in temporary folders to keep the test stateless while ensuring parallelization. function generate(tempDirNameSpace, files) { const key = generateCacheKey(files); const cached = cache.get(key); if (cached) { return cached; } const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), `snyk-nuget-plugin-test-${tempDirNameSpace}-`)); let tempFilePath; files.forEach((file) => { tempFilePath = path.join(tempDir, file.name); fs.writeFileSync(tempFilePath, file.contents); }); debug(`Generated temporary CS files (${files .map((f) => f.name) .join(',')}) in ${tempDir}`); cache.set(key, tempDir); return tempDir; } function tearDown(dirs) { debug(`Attempting to delete temporary CS files in ${dirs.join(',')}`); for (const dir of dirs) { if (!dir) { // No tempDir to tear down. Assuming the test failed somewhere. // Jest won't throw an error anyway if the operation fails. return; } try { fs.rmSync(dir, { recursive: true }); } catch (error) { // Ignore it, test was tearing down anyway, and it seems Windows boxes especially don't like this. } } } //# sourceMappingURL=generator.js.map /***/ }), /***/ 63662: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.generate = generate; const generator = __webpack_require__(56421); function generate() { const files = [ { name: 'Parse.csproj', contents: ` Exe net6.0 enable ShortNameToLongName true LatestMajor `, }, { name: 'Program.cs', contents: ` using System; using NuGet.Frameworks; using Newtonsoft.Json; class Program { static void Main(string[] args) { if (args.Length < 1) { Console.WriteLine("Usage: dotnet run "); return; } string shortName = args[0]; try { NuGetFramework framework = NuGetFramework.Parse(shortName); string json = JsonConvert.SerializeObject(new { framework.Framework, framework.Version, framework.Platform, framework.PlatformVersion, framework.HasPlatform, framework.HasProfile, framework.Profile, framework.DotNetFrameworkName, framework.DotNetPlatformName, framework.IsPCL, framework.IsPackageBased, framework.AllFrameworkVersions, framework.IsUnsupported, framework.IsAgnostic, framework.IsAny, framework.IsSpecificFramework, ShortName = shortName }, Formatting.None); Console.Write(json); } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } } } `, }, ]; const tempDir = generator.generate('csharp', files); return tempDir; } //# sourceMappingURL=nugetframeworks_parser.js.map /***/ }), /***/ 93935: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toReadableFramework = toReadableFramework; function toReadableFramework(targetFramework) { const typeMapping = { net: '.NETFramework', netcoreapp: '.NETCore', netstandard: '.NETStandard', v: '.NETFramework', }; // HACK: this is an edge case and it's supported by NuGet design // https://github.com/NuGet/Home/issues/1371 if (targetFramework === 'net4') { return { framework: typeMapping.net, original: targetFramework, version: '4', }; } for (const type in typeMapping) { if (new RegExp(type + /\d.?\d(.?\d)?$/.source).test(targetFramework)) { return { framework: typeMapping[type], original: targetFramework, version: targetFramework.split(type)[1], }; } } return undefined; } //# sourceMappingURL=framework.js.map /***/ }), /***/ 66677: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildDepGraphFromFiles = buildDepGraphFromFiles; exports.buildDepTreeFromFiles = buildDepTreeFromFiles; const fs = __webpack_require__(57147); const path = __webpack_require__(71017); const csProjParser = __webpack_require__(81016); const debugModule = __webpack_require__(15158); const depsParser = __webpack_require__(91885); const dotnetCoreParser = __webpack_require__(11404); const dotnetCoreV2Parser = __webpack_require__(25467); const dotnetFrameworkParser = __webpack_require__(11461); const projectJsonParser = __webpack_require__(36722); const packagesConfigParser = __webpack_require__(56409); const errors_1 = __webpack_require__(62153); const types_1 = __webpack_require__(46652); const dotnet = __webpack_require__(62886); const nugetFrameworksParser = __webpack_require__(63662); const runtimeAssembly = __webpack_require__(919); const debug = debugModule('snyk'); const PARSERS = { 'dotnet-core': { depParser: dotnetCoreParser, fileContentParser: JSON, }, 'dotnet-core-v2': { depParser: dotnetCoreV2Parser, fileContentParser: JSON, }, 'packages.config': { depParser: dotnetFrameworkParser, fileContentParser: packagesConfigParser, }, 'project.json': { depParser: dotnetFrameworkParser, fileContentParser: projectJsonParser, }, }; function getPackagesFolder(packagesFolder, projectRootFolder) { if (packagesFolder) { return path.resolve(process.cwd(), packagesFolder); } return path.resolve(projectRootFolder, 'packages'); } function getRootName(root, projectRootFolder, projectNamePrefix) { const defaultRootName = path.basename(root || projectRootFolder || ''); if (projectNamePrefix) { return projectNamePrefix + defaultRootName; } return defaultRootName; } function getFileContents(fileContentPath) { try { debug(`Parsing content of ${fileContentPath}`); return fs.readFileSync(fileContentPath, 'utf-8'); } catch (error) { throw new errors_1.FileNotProcessableError(error); } } function tryToGetFileByName(dir, filename) { const depsFilePath = path.join(dir, filename); try { const depsFile = fs.readFileSync(depsFilePath); if (depsFile) return depsFile; } catch (_) { // Due to race conditions, fs docs suggests to not use .stat or .access to check if a file exists // but instead we should to try and read it. // https://nodejs.org/api/fs.html#fsstatpath-options-callback } return null; } // `dotnet` can publish the .deps file to a variety of places inside the publish folder, depending on what you're // including and targeting. Instead of trying different directories, just scan them all. In most cases, the file // will be in the root directory. (See https://github.com/Azure/azure-functions-vs-build-sdk/issues/518) function findDepsFileInPublishDir(dir, filename) { let renamedFile = null; // Try to get the file via full path. const namedFile = tryToGetFileByName(dir, filename); if (namedFile) return namedFile; for (const item of fs.readdirSync(dir)) { const itemPath = path.join(dir, item); // The file is usually .deps.json, but in edge cases, `dotnet` names it for you. if (itemPath.endsWith('deps.json')) { renamedFile = fs.readFileSync(itemPath); } if (!fs.statSync(itemPath).isDirectory()) { continue; } // Otherwise, look in a nested dir for the same thing. const foundFile = findDepsFileInPublishDir(itemPath, filename); if (!foundFile) { continue; } return foundFile; } return renamedFile || null; } async function buildDepGraphFromFiles(root, targetFile, manifestType, useProjectNameFromAssetsFile, projectNamePrefix, targetFramework) { const safeRoot = root || '.'; const safeTargetFile = targetFile || '.'; const fileContentPath = path.resolve(safeRoot, safeTargetFile); const fileContent = getFileContents(fileContentPath); const parser = PARSERS['dotnet-core-v2']; const projectAssets = await parser.fileContentParser.parse(fileContent); if (!projectAssets.project?.frameworks) { throw new errors_1.FileNotProcessableError(`unable to detect any target framework in manifest file ${safeTargetFile}, a valid one is needed to continue down this path.`); } // Scan all 'frameworks' detected in the project.assets.json file, and use the targetAlias if detected and // otherwise the raw key name, as it's not guaranteed that all framework objects contains a targetAlias. const targetFrameworks = Object.entries(projectAssets.project.frameworks).map(([key, value]) => ('targetAlias' in value ? value.targetAlias : key)); if (targetFrameworks.length <= 0) { throw new errors_1.FileNotProcessableError(`unable to detect a target framework in ${safeTargetFile}, a valid one is needed to continue down this path.`); } if (targetFramework && !targetFrameworks.includes(targetFramework)) { console.warn(`\x1b[33m⚠ WARNING\x1b[0m: Supplied targetframework \x1b[1m${targetFramework}\x1b[0m was not detected in the supplied manifest file. Available targetFrameworks detected was \x1b[1m${targetFrameworks.join(',')}\x1b[0m. Will attempt to build dependency graph anyway, but the operation might fail.`); } let resolvedProjectName = getRootName(root, safeRoot, projectNamePrefix); const projectNameFromManifestFile = projectAssets?.project?.restore?.projectName; if (manifestType === types_1.ManifestType.DOTNET_CORE && useProjectNameFromAssetsFile) { if (projectNameFromManifestFile) { resolvedProjectName = projectNameFromManifestFile; } else { debug(`project.assets.json file doesn't contain a value for 'projectName'. Using default value: ${resolvedProjectName}`); } } // If a specific targetFramework has been requested, only query that, otherwise try to do them all const decidedTargetFrameworks = targetFramework ? [targetFramework] : targetFrameworks.filter((framework) => { if (!depsParser.isSupportedByV2GraphGeneration(framework)) { console.warn(`\x1b[33m⚠ WARNING\x1b[0m: The runtime resolution flag is currently only supported for the following TargetFrameworks: .NET versions 5 and higher, all versions of .NET Core and all versions of .NET Standard. Detected a TargetFramework: \x1b[1m${framework}\x1b[0m, which will be skipped.`); return false; } return true; }); if (decidedTargetFrameworks.length == 0) { throw new errors_1.InvalidManifestError(`Was not able to find any supported TargetFrameworks to scan, aborting`); } // Ensure `dotnet` is installed on the system or fail trying. await dotnet.validate(); // Write a .NET Framework Parser to a temporary directory for validating TargetFrameworks. const nugetFrameworksParserLocation = nugetFrameworksParser.generate(); await dotnet.restore(nugetFrameworksParserLocation); // Access the path of this project, to ensure we get the right .csproj file, in case of multiples present const projectPath = projectAssets.project.restore.projectPath; if (!projectPath) { console.warn(`\x1b[33m⚠ WARNING\x1b[0m: Could not detect any projectPath in the project assets file, if your solution contains multiple projects in the same folder, this operation might fail.`); } // Loop through all TargetFrameworks supplied and generate a dependency graph for each. const results = []; for (const decidedTargetFramework of decidedTargetFrameworks) { // Run `dotnet publish` to create a self-contained publishable binary with included .dlls for assembly version inspection. const publishDir = await dotnet.publish( // Attempt to feed it the full path to the project file itself, as multiple could exist. If that fails, don't break the flow, just send the folder as previously projectPath || safeRoot, decidedTargetFramework); // Then inspect the dependency graph for the runtimepackage's assembly versions. const filename = `${projectNameFromManifestFile}.deps.json`; const depsFile = findDepsFileInPublishDir(publishDir, filename); if (!depsFile) { throw new errors_1.CliCommandError(`unable to locate ${filename} anywhere inside ${publishDir}, file is needed for runtime resolution to occur, aborting`); } const publishedProjectDeps = JSON.parse(depsFile.toString('utf-8')); let assemblyVersions = {}; // Specifically targeting .NET Standard frameworks will not provide any specific runtime assembly information in // the published artifacts files, and can thus not be read more precisely than the .deps file will tell us up-front. // This probably makes sense when looking at https://dotnet.microsoft.com/en-us/platform/dotnet-standard#versions. // As such, we don't generate any runtime assemblies and generate the dependency graph without it. if (!decidedTargetFramework.includes('netstandard')) { assemblyVersions = runtimeAssembly.generateRuntimeAssemblies(publishedProjectDeps); } // Parse the TargetFramework using Nuget.Frameworks itself, instead of trying to reinvent the wheel, thus ensuring // we have maximum context to use later when building the depGraph. const response = await dotnet.run(nugetFrameworksParserLocation, [ decidedTargetFramework, ]); const targetFrameworkInfo = JSON.parse(response); if (targetFrameworkInfo.IsUnsupported) { throw new errors_1.InvalidManifestError(`dotnet was not able to parse the target framework ${decidedTargetFramework}, it was reported unsupported by the dotnet runtime`); } const depGraph = parser.depParser.parse(resolvedProjectName, projectAssets, publishedProjectDeps, assemblyVersions); results.push({ dependencyGraph: depGraph, targetFramework: decidedTargetFramework, }); } return results; } async function buildDepTreeFromFiles(root, targetFile, packagesFolderPath, manifestType, useProjectNameFromAssetsFile, projectNamePrefix) { const safeRoot = root || '.'; const safeTargetFile = targetFile || '.'; const fileContentPath = path.resolve(safeRoot, safeTargetFile); const fileContent = getFileContents(fileContentPath); const projectRootFolder = path.resolve(fileContentPath, '../../'); const packagesFolder = getPackagesFolder(packagesFolderPath, projectRootFolder); const tree = { dependencies: {}, meta: {}, name: getRootName(root, projectRootFolder, projectNamePrefix), packageFormatVersion: 'nuget:0.0.0', version: '0.0.0', }; let targetFrameworks; try { if (manifestType === types_1.ManifestType.DOTNET_CORE) { targetFrameworks = csProjParser.getTargetFrameworksFromProjFile(projectRootFolder); } else { // .csproj is in the same directory as packages.config or project.json const fileContentParentDirectory = path.resolve(fileContentPath, '../'); targetFrameworks = csProjParser.getTargetFrameworksFromProjFile(fileContentParentDirectory); // finally, for the .NETFramework project, try to assume the framework using dotnet-deps-parser if (targetFrameworks.length <= 0) { // currently only process packages.config files if (manifestType === types_1.ManifestType.PACKAGES_CONFIG) { const minimumTargetFramework = await packagesConfigParser.getMinimumTargetFramework(fileContent); if (minimumTargetFramework) { targetFrameworks = [minimumTargetFramework]; } } } } } catch (error) { return Promise.reject(error); } // Only supports the first targetFramework we find. // Use the newer `buildDepGraphFromFiles` for better support for multiple target frameworks. const targetFramework = targetFrameworks.length > 0 ? targetFrameworks[0].original : undefined; tree.meta = { targetFramework: targetFramework, }; const parser = PARSERS[manifestType]; const manifest = await parser.fileContentParser.parse(fileContent, tree); if (manifestType === types_1.ManifestType.DOTNET_CORE && useProjectNameFromAssetsFile) { const projectName = manifest?.project?.restore?.projectName; if (projectName) { tree.name = projectName; } else { debug("project.assets.json file doesn't contain a value for 'projectName'. Using default value: " + tree.name); } } return parser.depParser.parse(tree, manifest, targetFramework, packagesFolder); } //# sourceMappingURL=index.js.map /***/ }), /***/ 81016: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getTargetFrameworksFromProjFile = getTargetFrameworksFromProjFile; const errors_1 = __webpack_require__(62153); const fs = __webpack_require__(57147); const path = __webpack_require__(71017); const parseXML = __webpack_require__(5055); const debugModule = __webpack_require__(15158); const framework_1 = __webpack_require__(93935); const debug = debugModule('snyk'); function findFile(rootDir, filter) { if (!fs.existsSync(rootDir)) { throw new errors_1.FileNotFoundError('No such path: ' + rootDir); } const files = fs.readdirSync(rootDir); for (const file of files) { const filename = path.resolve(rootDir, file); if (filter.test(filename)) { return filename; } } return; } function readEncodedFile(path) { const buffer = fs.readFileSync(path); const firstChar = buffer.readUInt16LE(0); let contents; if (firstChar === 0xfeff) { contents = buffer.toString('utf16le'); } else { contents = buffer.toString('utf8'); } return contents; } function getTargetFrameworksFromProjFile(rootDir) { debug('Looking for your .csproj file in ' + rootDir); const csprojPath = findFile(rootDir, /.*\.csproj$/); if (!csprojPath) { debug('.csproj file not found in ' + rootDir + '.'); return []; } debug(`Checking .NET framework version in .csproj file ${csprojPath}`); const csprojContents = readEncodedFile(csprojPath); let result = []; try { parseXML.parseString(csprojContents, (err, parsedCsprojContents) => { if (err) { throw new errors_1.FileNotProcessableError(err); } const parsedTargetFrameworks = parsedCsprojContents?.Project?.PropertyGroup?.reduce((targetFrameworks, propertyGroup) => { const targetFrameworkSource = propertyGroup?.TargetFrameworkVersion?.[0] || propertyGroup?.TargetFramework?.[0] || propertyGroup?.TargetFrameworks?.[0] || ''; return targetFrameworks .concat(targetFrameworkSource.split(';')) .filter(Boolean); }, []) || []; if (parsedTargetFrameworks.length < 1) { debug('Could not find TargetFrameworkVersion/TargetFramework' + '/TargetFrameworks defined in the Project.PropertyGroup field of ' + 'your .csproj file'); result = []; return; } const targetFrameworks = parsedTargetFrameworks .map(framework_1.toReadableFramework) .filter(Boolean); if (parsedTargetFrameworks.length > 1 && targetFrameworks.length < 1) { debug('Could not find valid/supported .NET version in csproj file located at' + csprojPath); } result = targetFrameworks; return; }); } catch (err) { throw new errors_1.FileNotProcessableError(`Could not parse ${csprojPath}`); } return result; } //# sourceMappingURL=csproj-parser.js.map /***/ }), /***/ 11404: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parse = parse; const errors_1 = __webpack_require__(62153); const debugModule = __webpack_require__(15158); const _ = __webpack_require__(96486); const debug = debugModule('snyk'); const PACKAGE_DELIMITER = '@'; const freqDeps = {}; function initFreqDepsDict() { freqDeps['Microsoft.NETCore.Platforms'] = false; freqDeps['Microsoft.NETCore.Targets'] = false; freqDeps['System.Runtime'] = false; freqDeps['System.IO'] = false; freqDeps['System.Text.Encoding'] = false; freqDeps['System.Threading.Tasks'] = false; freqDeps['System.Reflection'] = false; freqDeps['System.Globalization'] = false; } function isScanned(nodes, pkg) { const node = nodes.find((elem) => elem.name === pkg.name && elem.version === pkg.version); return !!node; } function isFreqDep(packageName) { return packageName in freqDeps; } function pick(obj, keys) { const pickedObj = {}; Object.keys(obj).forEach((k) => { if (keys.includes(k)) { pickedObj[k] = obj[k]; } }); return pickedObj; } function convertFromPathSyntax(path) { let name = path.split('/').join('@'); // posix name = name.split('\\').join('@'); // windows return name; } function findPackage(targetDeps, depName) { debug(`Looking for ${depName}`); const depNameLowerCase = depName.toLowerCase(); for (const currentDep of Object.keys(targetDeps)) { const currentResolvedName = convertFromPathSyntax(currentDep); const [currentDepName, currentDepVersion] = currentResolvedName.split(PACKAGE_DELIMITER); if (currentDepName.toLowerCase() === depNameLowerCase) { return { name: depName, version: currentDepVersion, dependencies: targetDeps[currentDep].dependencies, }; } } debug(`Failed to find ${depName}`); return undefined; } function constructTree(roots, nodes, links) { const treeMap = {}; for (const node of nodes) { const { name, version } = node; const treeNode = { name, version, dependencies: {} }; treeMap[name] = treeNode; } for (const link of links) { const parentName = link.from.name; const childName = link.to.name; const parentNode = treeMap[parentName]; const childNode = treeMap[childName]; if (!isFreqDep(childName)) { parentNode.dependencies[childName] = { ...childNode, }; } } const tree = pick(treeMap, roots); const freqSysDeps = pick(treeMap, Object.keys(freqDeps)); if (Object.keys(freqSysDeps).length > 0) { tree['freqSystemDependencies'] = { name: 'freqSystemDependencies', version: '0.0.0', dependencies: freqSysDeps, }; } return tree; } function collectFlatList(targetObj) { const names = Object.keys(targetObj); return names.map((name) => { name = convertFromPathSyntax(name); return name; }); } function addPackageDepLinks(links, pkg) { if (pkg && pkg.dependencies) { const from = { name: pkg.name, version: pkg.version }; for (const name of Object.keys(pkg.dependencies)) { const to = { name, version: pkg.dependencies[name] }; links.push({ from, to }); } } } function buildBfsTree(targetDeps, roots) { let queue = [...roots]; const nodes = []; const links = []; while (queue.length > 0) { const dep = queue.shift(); const foundPackage = findPackage(targetDeps, dep); if (foundPackage && !isScanned(nodes, foundPackage)) { nodes.push(foundPackage); if (foundPackage.dependencies) { addPackageDepLinks(links, foundPackage); queue = queue.concat(Object.keys(foundPackage.dependencies)); } } } return constructTree(roots, nodes, links); } function getFrameworkToRun(manifest) { const frameworks = manifest?.project?.frameworks; debug(`Available frameworks: '${Object.keys(frameworks)}'`); // not yet supporting multiple frameworks in the same assets file -> // taking only the first 1 const selectedFrameworkKey = Object.keys(frameworks)[0]; debug(`Selected framework: '${selectedFrameworkKey}'`); return selectedFrameworkKey; } function getTargetObjToRun(manifest) { debug(`Available targets: '${Object.keys(manifest.targets)}'`); const selectedTargetKey = Object.keys(manifest.targets)[0]; debug(`Selected target: '${selectedTargetKey}'`); // not yet supporting multiple targets in the same assets file -> // taking only the first 1 return manifest.targets[selectedTargetKey]; } function validateManifest(manifest) { if (!manifest.project) { throw new errors_1.InvalidManifestError('Project field was not found in project.assets.json'); } if (!manifest.project.frameworks) { throw new errors_1.InvalidManifestError('No frameworks were found in project.assets.json'); } if (!manifest.project.frameworks || Object.keys(manifest.project.frameworks).length === 0) { throw new errors_1.InvalidManifestError('0 frameworks were found in project.assets.json'); } if (!manifest.targets) { throw new errors_1.InvalidManifestError('No targets were found in project.assets.json'); } if (!manifest.targets || Object.keys(manifest.targets).length === 0) { throw new errors_1.InvalidManifestError('0 targets were found in project.assets.json'); } } function parse(tree, manifest) { debug('Trying to parse dot-net-cli manifest'); validateManifest(manifest); if (manifest.project.version) { tree.version = manifest.project.version; } // If a targetFramework was not found in the proj file, we will extract it from the lock file // OR // If the targetFramework is undefined, extract it from the lock file // Fix for https://github.com/snyk/snyk-nuget-plugin/issues/75 if (!tree.meta.targetFramework || manifest.project.frameworks[tree.meta.targetFramework] === undefined) { tree.meta.targetFramework = getFrameworkToRun(manifest); } const selectedFrameworkObj = manifest.project.frameworks[tree.meta.targetFramework]; // We currently ignore the found targetFramework when looking for target dependencies const selectedTargetObj = getTargetObjToRun(manifest); initFreqDepsDict(); const directDependencies = selectedFrameworkObj.dependencies ? collectFlatList(selectedFrameworkObj.dependencies) : []; debug(`directDependencies: '${directDependencies}'`); tree.dependencies = buildBfsTree(selectedTargetObj, directDependencies); // to disconnect the object references inside the tree // cloneDeep is used here tree.dependencies = _.cloneDeep(tree.dependencies); return tree; } //# sourceMappingURL=dotnet-core-parser.js.map /***/ }), /***/ 25467: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FILTERED_DEPENDENCY_PREFIX = void 0; exports.parse = parse; const debugModule = __webpack_require__(15158); const dep_graph_1 = __webpack_require__(71479); const errors_1 = __webpack_require__(62153); const debug = debugModule('snyk'); // Dependencies that starts with these are discarded exports.FILTERED_DEPENDENCY_PREFIX = [ // `runtime` and `runtime.native` are a bit of a hot topic, see more https://github.com/dotnet/core/issues/7568. // For our case, we are already creating the correct dependencies and their respective runtime version numbers based // of our runtime resolution logic. So a dependency will already be `System.Net.Http@8.0.0` if running on .NET 8, thus // removing the need for a `runtime.native.System.Net.Http@8.0.0` as well. From our investigation these runtime native // dependencies are causing noise for the customers and are not of interested. 'runtime', ]; function recursivelyPopulateNodes(depGraphBuilder, targetDeps, node, runtimeAssembly, visited) { const parentId = node.type === 'root' ? 'root-node' : `${node.name}@${node.version}`; for (const depNode of Object.entries(node.dependencies || {})) { const localVisited = visited || new Set(); const name = depNode[0]; const version = depNode[1]; // Ignore packages with specific prefixes, which for one reason or the other are no interesting and pollutes the // graph. Refer to comments on the individual elements in the ignore list for more information. if (exports.FILTERED_DEPENDENCY_PREFIX.some((prefix) => name.startsWith(prefix))) { debug(`${name} matched a prefix we ignore, not adding to graph`); continue; } const childNode = { ...targetDeps[`${name}/${version}`], name, version, }; const childId = `${childNode.name}@${childNode.version}`; // If we're looking at a runtime assembly version for self-contained dlls, overwrite the dependency version // we've found in the graph with those from the runtime assembly, as they take precedence. let assemblyVersion = version; // The RuntimeAssembly type contains the name with a .dll suffix, as this is how .NET represents them in the // dependency file. This must be stripped in order to match the elements during depGraph construction. const dll = `${name}.dll`; if (dll in runtimeAssembly) { assemblyVersion = runtimeAssembly[dll]; } if (localVisited.has(childId)) { const prunedId = `${childId}:pruned`; depGraphBuilder.addPkgNode({ name: childNode.name, version: assemblyVersion }, prunedId, { labels: { pruned: 'true' }, }); depGraphBuilder.connectDep(parentId, prunedId); continue; } depGraphBuilder.addPkgNode({ name: childNode.name, version: assemblyVersion }, childId); depGraphBuilder.connectDep(parentId, childId); localVisited.add(childId); recursivelyPopulateNodes(depGraphBuilder, targetDeps, childNode, runtimeAssembly, localVisited); } } function getRestoredProjectName(publishedProjectDeps, runtimeTarget, projectName) { return Object.keys(publishedProjectDeps.targets[runtimeTarget]).find((f) => f.startsWith(projectName)); } function extractLocalProjects(libs) { const localPackages = []; for (const [key, value] of Object.entries(libs)) { if (!key.includes('runtimepack')) { // Local projects (.csproj files) don't have values declared for these two properties. // https://github.com/dotnet/sdk/blob/main/documentation/specs/runtime-configuration-file.md#libraries-section-depsjson if (!value.serviceable && !value.sha512 && value.type === 'project') { localPackages.push(key); } } } return localPackages; } function getDllName(depName) { return `${depName}.dll`; } function buildGraph(projectName, projectAssets, publishedProjectDeps, runtimeAssembly) { const depGraphBuilder = new dep_graph_1.DepGraphBuilder({ name: 'nuget' }, { name: projectName, version: projectAssets.project.version, }); // We publish to one RID and one only, so we can safely assume that the true dependencies will exist in this key. // E.g. targets -> .NETCoreApp,Version=v8.0/osx-arm64 const runtimeTarget = publishedProjectDeps.runtimeTarget.name; // Those dependencies are referenced in the 'targets' member in the same .deps file. if (Object.keys(publishedProjectDeps.targets).length <= 0) { throw new errors_1.InvalidManifestError('no target dependencies in found in published deps file (project.deps.json -> targets -> []), cannot continue without that'); } if (!(runtimeTarget in publishedProjectDeps.targets)) { throw new errors_1.InvalidManifestError(`no ${runtimeTarget} found in targets object, cannot continue without it`); } // What `dotnet` wants to call this project is not always the same as what Snyk wants to call it, and the version // postfix is not the same as what's defined in `project.assets.json` due to NuGet version normalization, which is // not applied during publish, only during restore. So we have to rely on the fact that the name is enough. const restoreProjectName = getRestoredProjectName(publishedProjectDeps, runtimeTarget, projectAssets.project.restore.projectName) || // Last attempt to find the target using the .csproj filename. // property overrides most of the naming when restoring, but when publishing, the actual filename is used as the target. getRestoredProjectName(publishedProjectDeps, runtimeTarget, projectName); if (!restoreProjectName) { throw new errors_1.InvalidManifestError(`no project name containing ${projectAssets.project.restore.projectName} or ${projectName} found in ${runtimeTarget} object, cannot continue without it`); } // Find names and versions of all dependencies of the root package. These are already structured correctly in // the deps.json generated by `dotnet publish`. const topLevelDepPackages = publishedProjectDeps.targets[runtimeTarget][restoreProjectName] .dependencies; // Iterate over all the dependencies found in the target dependency list, and build the depGraph based off of that. const targetDependencies = Object.entries(publishedProjectDeps.targets[runtimeTarget]).reduce((acc, entry) => { const [nameWithVersion, pkg] = entry; return { ...acc, [nameWithVersion]: pkg }; }, {}); const rootNode = { type: 'root', dependencies: topLevelDepPackages, }; // runtimeAssembly doesn't have entries if the target framework is `netstandard` if (Object.keys(runtimeAssembly).length > 0) { const localPackagesNames = extractLocalProjects(publishedProjectDeps.libraries); const targets = publishedProjectDeps.targets[runtimeTarget]; // Overwriting the runtime versions with the values used in local projects. for (const pgkName of localPackagesNames) { if (targets[pgkName]?.dependencies) { for (const [key, value] of Object.entries(targets[pgkName].dependencies)) { const dllName = getDllName(key); if (runtimeAssembly[dllName]) { runtimeAssembly[dllName] = value; } } } } // Overwriting the runtime versions with the values used in fetched packages. for (const [key, value] of Object.entries(targets)) { if (value && Object.keys(value).length === 0) { const [depName, depVersion] = key.split('/'); const dllName = getDllName(depName); // NuGet’s dependency resolution mechanism will choose the higher available version. if (runtimeAssembly[dllName] && depVersion > runtimeAssembly[dllName]) { runtimeAssembly[dllName] = depVersion; } } } } recursivelyPopulateNodes(depGraphBuilder, targetDependencies, rootNode, runtimeAssembly); return depGraphBuilder.build(); } function parse(projectName, projectAssets, publishedProjectDeps, runtimeAssembly) { debug('Trying to parse .net core manifest with v2 depGraph builder'); const result = buildGraph(projectName, projectAssets, publishedProjectDeps, runtimeAssembly); return result; } //# sourceMappingURL=dotnet-core-v2-parser.js.map /***/ }), /***/ 11461: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.cloneShallow = cloneShallow; exports.fromFolderName = fromFolderName; exports.parse = parse; const fs = __webpack_require__(57147); const path = __webpack_require__(71017); const debugModule = __webpack_require__(15158); const nuspec_parser_1 = __webpack_require__(27300); const invalid_folder_format_error_1 = __webpack_require__(51901); const debug = debugModule('snyk'); function cloneShallow(dep) { // clone, without the dependencies return { dependencies: {}, name: dep.name, version: dep.version, }; } function extractFromDotVersionNotation(expression) { const regexParseResult = /(?=\S+)(?=\.{1})((\.\d+)+((-?\w+\.?\d*)|(\+?[0-9a-f]{5,40}))?)/.exec(expression); if (regexParseResult == null) { debug(`Failed to extract version from the folder: ${expression}. This is not supposed to happen and should be reported - the folders should always be in the form of [FolderName].[semantic version]`); throw new invalid_folder_format_error_1.InvalidFolderFormatError(`Tried to parse package version from a folder name but failed. I received: ${expression}`); } const versionRef = regexParseResult?.[0]; const name = expression.split(versionRef)[0]; return { name, version: versionRef.slice(1), }; } function fromFolderName(folderName) { debug('Extracting by folder name ' + folderName); const info = extractFromDotVersionNotation(folderName); return { dependencies: {}, name: info.name, version: info.version, }; } function injectPath(dep, packagesFolder) { dep.path = dep.localPath ? path.resolve(packagesFolder, dep.localPath) : path.resolve(packagesFolder, dep.name + '.' + dep.version); if (dep.localPath) { delete dep.localPath; } } function scanInstalled(installedPackages, packagesFolder) { const flattenedPackageList = {}; debug('Located ' + installedPackages.length + ' packages in manifest'); installedPackages.forEach((entry) => { injectPath(entry, packagesFolder); flattenedPackageList[entry.name] = flattenedPackageList[entry.name] || entry; debug('Entry: ' + entry.name + ' -> ' + entry.path); }); try { debug('Scanning local installed folders'); debug('Trying to read from installed packages folder: ' + packagesFolder); fs.readdirSync(packagesFolder) .map((folderName) => { try { return fromFolderName(folderName); } catch (error) { debug('Unable to parse dependency from folder'); debug(error); return; } }) .forEach((dep) => { if (dep) { injectPath(dep, packagesFolder); // only add a package from packages folder if version is different if (flattenedPackageList[dep.name] && flattenedPackageList[dep.name].version !== dep.version) { // prefer found from packages folder (dep) over existing debug('For package ' + dep.name + ' the version ' + flattenedPackageList[dep.name].version + ' was extracted from manifest file.' + '\nWe are overwriting it with version ' + dep.version + ' from the packages folder'); flattenedPackageList[dep.name] = dep; } } }); } catch (error) { debug('Could not complete packages folder scanning'); debug(error); } return flattenedPackageList; } async function fetchNugetInformationFromPackages(flattenedPackageList, targetFramework) { const nugetPackageInformation = []; // begin collecting information from .nuget files on installed packages debug('Trying to analyze .nuspec files'); for (const name of Object.keys(flattenedPackageList)) { try { const dep = flattenedPackageList[name]; debug('...' + name); const resolved = await (0, nuspec_parser_1.parseNuspec)(dep, targetFramework); nugetPackageInformation.push(resolved); } catch (e) { debug('Failed parsing nuspec file'); debug(e); // log but make sure to rethrow the error // why? if we cannot parse nuspec file, we got nothing to do! throw e; } } return nugetPackageInformation; } function processNugetInformation(nuspecResolutionChain) { const nuspecResolutions = {}; nuspecResolutionChain.forEach((resolution) => { if (!resolution) { return; } // jscs:ignore debug('.nuspec analyzed for ' + resolution.name); nuspecResolutions[resolution.name] = resolution; }); return nuspecResolutions; } function buildTree(node, requiredChildren, flattenedPackageList, nuspecResolutions) { for (const requiredChild of requiredChildren) { let transitiveDependency; if (flattenedPackageList[requiredChild.name]) { // fetch from repo transitiveDependency = cloneShallow(flattenedPackageList[requiredChild.name]); } else { // create as new (uninstalled) transitiveDependency = { dependencies: {}, name: requiredChild.name, version: requiredChild.version, }; } const transitiveChildren = (nuspecResolutions[transitiveDependency.name] && nuspecResolutions[transitiveDependency.name].children) || []; buildTree(transitiveDependency, transitiveChildren, flattenedPackageList, nuspecResolutions); node.dependencies[transitiveDependency.name] = transitiveDependency; } } async function parse(tree, manifest, targetFramework, packagesFolder) { if (!targetFramework) { throw new Error('No valid Dotnet target framework found'); } const flattenedPackageList = scanInstalled(manifest, packagesFolder); const nugetPackageInformation = await fetchNugetInformationFromPackages(flattenedPackageList, targetFramework); const nuspecResolutions = processNugetInformation(nugetPackageInformation); // .nuget parsing is complete, returned as array of promise resolutions // now the flat list should be rebuilt as a tree debug('Building dependency tree'); const nugetKeys = Object.keys(nuspecResolutions); Object.keys(flattenedPackageList).forEach((packageName) => { tree.dependencies[packageName] = cloneShallow(flattenedPackageList[packageName]); }); if (nugetKeys.length > 0) { // local folders scanned, build list from .nuspec for (const key of nugetKeys) { const resolution = nuspecResolutions[key]; const node = cloneShallow(flattenedPackageList[resolution.name]); buildTree(node, resolution.children, flattenedPackageList, nuspecResolutions); tree.dependencies[node.name] = node; } } return tree; } //# sourceMappingURL=dotnet-framework-parser.js.map /***/ }), /***/ 27300: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parse = parse; exports.parseNuspec = parseNuspec; const JSZip = __webpack_require__(66085); const fs = __webpack_require__(57147); const path = __webpack_require__(71017); const parseXML = __webpack_require__(5055); const debugModule = __webpack_require__(15158); const debug = debugModule('snyk'); const targetFrameworkRegex = /([.a-zA-Z]+)([.0-9]+)/; var SupportedEncodings; (function (SupportedEncodings) { SupportedEncodings["UTF8"] = "utf-8"; SupportedEncodings["UTF16LE"] = "utf-16le"; })(SupportedEncodings || (SupportedEncodings = {})); function extractDepsForPlainGroups(rawDependency) { if (!rawDependency.group) { return []; } return rawDependency.group.filter((group) => { // valid group with no attributes or no `targetFramework` attribute return group && !(group.$ && group.$.targetFramework); }); } function assertNuspecSchema(nuspecContent, parsedNuspec) { if (!parsedNuspec.package?.metadata) { throw new Error('This is an invalid nuspec file. Package or Metadata xml section is missing. This is a required element. See https://docs.microsoft.com/en-us/nuget/reference/nuspec. The nuspec in question: ' + nuspecContent); } // just in case, this should *not* happen if (!Array.isArray(parsedNuspec.package.metadata)) { throw new Error('This is an invalid nuspec file; the metadata tag is supposed to be a collection of objects but it is not! The nuspec in question: ' + nuspecContent); } for (const metadata of parsedNuspec.package.metadata) { // just in case, this shouldn't happen as this would indicate invalid/malformed nuspec file if (metadata == null || typeof metadata !== 'object') { throw new Error('Expected elements in a "metadata" tag to be objects, but they were ' + typeof metadata + ', this is not supposed to happen and is likely due to malformed nuspec file. The nuspec in question: ' + nuspecContent); } if (metadata.dependencies) { // just in case, error would indicate malformed nuspec if (!Array.isArray(metadata.dependencies)) { throw new Error('Expected that "dependencies" tag would be an array but it isn\'t. This is not supposed to happen and is likely due to malformed nuspec file! The nuspec in question: ' + nuspecContent); } } } } function extractDepsForTargetFramework(rawDependency, targetFramework) { if (!rawDependency || !rawDependency.group) { return; } return rawDependency.group .filter((group) => { return (group?.$?.targetFramework && targetFrameworkRegex.test(group.$.targetFramework)); }) .map((group) => { const parts = group.$.targetFramework.split(targetFrameworkRegex); return { framework: parts[1], group, version: parts[2], }; }) .sort((a, b) => { if (a.framework === b.framework) { return Number(b.version) - Number(a.version); } return a.framework > b.framework ? -1 : 1; }) .find((group) => { return (targetFramework.framework === group.framework && targetFramework.version >= group.version); }); } function extractDepsFromRaw(rawDependencies) { if (!rawDependencies) { return []; } const deps = []; rawDependencies.forEach((dep) => { if (dep && dep.$) { deps.push({ dependencies: {}, name: dep.$.id, version: dep.$.version, }); } }); return deps; } function detectNuspecContentEncoding(nuspecContent) { // 65533 is a code for replacement character that is unique to UTF-16 // https://www.unicodepedia.com/unicode/specials/fffd/replacement-character/ if (nuspecContent.charCodeAt(0) === 65533) { return SupportedEncodings.UTF16LE; } return SupportedEncodings.UTF8; } function removePotentialUtf16Characters(input) { return input .replace(/\uFFFD/g, '') .replace(/\uBFEF/g, '') .replace(/\uBDBF/g, '') .replace(/\uEFBD/g, ''); } async function parse(nuspecContent, targetFramework, depName) { const parsedNuspec = await parseXML.parseStringPromise(nuspecContent); let ownDeps = []; // note: this will throw if assertion fails assertNuspecSchema(nuspecContent, parsedNuspec); for (const metadata of parsedNuspec.package.metadata) { metadata.dependencies?.forEach((rawDependency) => { // Find and add target framework version specific dependencies const depsForTargetFramework = extractDepsForTargetFramework(rawDependency, targetFramework); if (depsForTargetFramework && depsForTargetFramework.group) { ownDeps = ownDeps.concat(extractDepsFromRaw(depsForTargetFramework.group.dependency)); } // Find all groups with no targetFramework attribute // add their deps const depsFromPlainGroups = extractDepsForPlainGroups(rawDependency); if (depsFromPlainGroups) { depsFromPlainGroups.forEach((depGroup) => { ownDeps = ownDeps.concat(extractDepsFromRaw(depGroup.dependency)); }); } // Add the default dependencies ownDeps = ownDeps.concat(extractDepsFromRaw(rawDependency.dependency)); }); } return { children: ownDeps, name: depName, }; } async function loadNuspecFromAsync(dep) { const nupkgPath = path.resolve(dep.path, dep.name + '.' + dep.version + '.nupkg'); let nupkgData; try { nupkgData = fs.readFileSync(nupkgPath); } catch (error) { if (error.code == 'ENOENT') { debug('No nupkg file found at ' + nupkgPath); return null; // this is needed not to break existing code flow } throw error; } const nuspecZipData = await JSZip.loadAsync(nupkgData); const nuspecFile = Object.keys(nuspecZipData.files).find((file) => { return path.extname(file) === '.nuspec'; }); if (!nuspecFile) { throw new Error(`failed to read nupkg file from: ${nupkgPath}`); } if (!nuspecZipData) { throw new Error(`failed to open nupkg file as an archive from: ${nupkgPath}`); } const rawNuspecContent = await nuspecZipData.files[nuspecFile].async('text'); const encoding = detectNuspecContentEncoding(rawNuspecContent); const encoder = new TextEncoder(); const encoded = encoder.encode(rawNuspecContent); const decoder = new TextDecoder(encoding); const encodedNuspecContent = decoder.decode(encoded); return removePotentialUtf16Characters(encodedNuspecContent); } async function parseNuspec(dep, targetFramework) { // precaution if (!dep) { throw new Error('expected DependencyInfo parameter to have value but found it undefined'); } // another precaution if (!targetFramework) { throw new Error('expected TargetFramework parameter to have value but found it undefined'); } const nuspecContent = await loadNuspecFromAsync(dep); if (nuspecContent === null) { debug('failed to load nuspec content'); return null; } return await parse(nuspecContent, targetFramework, dep.name); } //# sourceMappingURL=nuspec-parser.js.map /***/ }), /***/ 56409: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fromPackagesConfigEntry = fromPackagesConfigEntry; exports.parse = parse; exports.getMinimumTargetFramework = getMinimumTargetFramework; const parseXML = __webpack_require__(5055); const debugModule = __webpack_require__(15158); const depsParser = __webpack_require__(91885); const framework_1 = __webpack_require__(93935); const errors_1 = __webpack_require__(62153); const debug = debugModule('snyk'); function fromPackagesConfigEntry(manifest) { debug('Extracting by packages.config entry:' + ' name = ' + manifest.$.id + ' version = ' + manifest.$.version); return { dependencies: {}, name: manifest.$.id, version: manifest.$.version, }; } function parse(fileContent) { const installedPackages = []; debug('Trying to parse packages.config manifest'); parseXML.parseString(fileContent, (err, result) => { if (err) { throw err; } if (!('packages' in result)) { throw new errors_1.InvalidManifestError(`Could not find a tag in your packages.config file. Please read this guide \x1b[4mhttps://learn.microsoft.com/en-us/nuget/reference/packages-config#schema\x1b[0m.`); } const packages = result.packages.package || []; packages.forEach(function scanPackagesConfigNode(node) { const installedDependency = fromPackagesConfigEntry(node); installedPackages.push(installedDependency); }); }); return installedPackages; } async function getMinimumTargetFramework(fileContent) { const extractedFrameworks = await depsParser.extractTargetFrameworksFromProjectConfig(fileContent); if (extractedFrameworks && extractedFrameworks.length > 0) { const minimumFramework = extractedFrameworks.reduce((prev, curr) => prev < curr ? prev : curr); return (0, framework_1.toReadableFramework)(minimumFramework); } return undefined; } //# sourceMappingURL=packages-config-parser.js.map /***/ }), /***/ 36722: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parse = parse; const debugModule = __webpack_require__(15158); const debug = debugModule('snyk'); function scanForDependencies(obj, deps) { deps = deps || {}; if (typeof obj !== 'object') { return deps; } for (const key of Object.keys(obj)) { if (key === 'dependencies') { const dependencies = obj.dependencies; for (const dep of Object.keys(dependencies)) { const depName = dep; let version = dependencies[dep]; if (typeof version === 'object') { version = version.version; } if (typeof version === 'undefined') { version = 'unknown'; } else { version = version.toString(); } deps[depName] = version; } } else { scanForDependencies(obj[key], deps); } } return deps; } function parseJsonManifest(fileContent) { const rawContent = JSON.parse(fileContent); const result = { dependencies: scanForDependencies(rawContent, {}), }; if (typeof rawContent.project === 'object') { const pData = rawContent.project; const name = pData.restore && pData.restore.projectName; result.project = { version: pData.version || '0.0.0', name, }; } return result; } function parse(fileContent, tree) { const installedPackages = []; debug('Trying to parse project.json format manifest'); const projectData = parseJsonManifest(fileContent); const rawDependencies = projectData.dependencies; debug(rawDependencies); if (rawDependencies) { for (const name of Object.keys(rawDependencies)) { // Array<{ "libraryName": "version" }> const version = rawDependencies[name]; installedPackages.push({ dependencies: {}, name, version, }); } } if (projectData.project) { tree.name = projectData.project.name; tree.version = projectData.project.version; } return installedPackages; } //# sourceMappingURL=project-json-parser.js.map /***/ }), /***/ 919: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.generateRuntimeAssemblies = generateRuntimeAssemblies; const errors = __webpack_require__(62153); const lodash_1 = __webpack_require__(96486); const debugModule = __webpack_require__(15158); const debug = debugModule('snyk'); // The Nuget dependency resolution rule of lowest applicable version // (see https://learn.microsoft.com/en-us/nuget/concepts/dependency-resolution#lowest-applicable-version) // does not apply to runtime dependencies. If you resolve a dependency graph of some package, that depends on // System.Http.Net 4.0.0, you might still very well end up using System.Http.Net 7.0.0 if you are running your // executable on .net7.0. // The `dotnet publish` will give a good estimate of what runtime dependencies are going to be used, so we inspect // that for information. // See https://natemcmaster.com/blog/2017/12/21/netcore-primitives/ for a good overview. // And https://github.com/dotnet/sdk/blob/main/documentation/specs/runtime-configuration-file.md for the official // explanation of what the `deps.json` file is doing that we are traversing. function generateRuntimeAssemblies(deps) { const runtimeTargetName = deps.runtimeTarget.name; debug(`extracting runtime assemblies from ${runtimeTargetName}`); if (!deps.targets) { throw new errors.FileNotProcessableError('could not find any targets in deps file'); } if (!(runtimeTargetName in deps.targets)) { throw new errors.FileNotProcessableError(`could not locate ${runtimeTargetName} in list of targets, cannot continue`); } // Run through all runtimepacks in target, indexed for example as // runtimepack.Microsoft.NETCore.App.Runtime.osx-arm64/7.0.14 // runtimepack.Microsoft.AspNetCore.App.Runtime.osx-arm64/7.0.14 // ... etc. // See all: https://github.com/dotnet/runtime/blob/bd83e17052d3c09022bad1d91dca860ca6b27ab9/src/libraries/Microsoft.NETCore.Platforms/src/runtime.json let runtimeAssemblyVersions = {}; const runtimePacks = Object.keys(deps.targets[runtimeTargetName]).filter((t) => t.startsWith('runtimepack')); if (runtimePacks.length <= 0) { throw new errors.FileNotProcessableError(`could not find any runtimepack.* identifiers in ${runtimeTargetName}, cannot continue`); } runtimePacks.forEach((runtimePack) => { const dependencies = deps.targets[runtimeTargetName][runtimePack]; // The runtimepack contains all the current RuntimeIdentifier (RID) assemblies which we are interested in. // Such as // "runtimepack.Microsoft.NETCore.App.Runtime.osx-arm64/6.0.16": { // "runtime": { // "Microsoft.CSharp.dll": { .. assembly version 6.0.0 } // } // } // We traverse all those and store them for the dependency graph build. if (!('runtime' in dependencies)) { throw new errors.FileNotProcessableError(`could not find any runtime list in the ${runtimePack} dependency`); } const runtimes = dependencies['runtime']; // Dig down into the specific runtimepack which contains all the assembly versions of // the bundled DLLs for the given runtime, as: // "runtimepack.Microsoft.NETCore.App.Runtime.osx-arm64/6.0.16": { // "runtime": { // "Microsoft.CSharp.dll": { // "assemblyVersion": "6.0.0.0", // "fileVersion": "6.0.1623.17311" // }, // "Microsoft.VisualBasic.Core.dll": { // "assemblyVersion": "11.0.0.0", // "fileVersion": "11.100.1623.17311" // }, // (...) // We currently only address assemblyVersions. FileVersion might become relevant, depending // on how vulnerabilities are reported in the future. runtimeAssemblyVersions = { ...runtimeAssemblyVersions, ...Object.entries(runtimes).reduce((acc, [dll, versions]) => { // Take the version number (N.N.N.N) and remove the last element, in order for vulndb to understand anything. acc[dll] = versions.assemblyVersion.split('.').slice(0, -1).join('.'); return acc; }, {}), }; }); if ((0, lodash_1.isEmpty)(runtimeAssemblyVersions)) { throw new errors.FileNotProcessableError('collection of runtime assembly versions was empty, that should not happen'); } debug(`finished extracting runtime assemblies from ${runtimeTargetName}`); return runtimeAssemblyVersions; } //# sourceMappingURL=runtime-assembly.js.map /***/ }), /***/ 46652: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ManifestType = void 0; var ManifestType; (function (ManifestType) { ManifestType["PROJECT_JSON"] = "project.json"; ManifestType["DOTNET_CORE"] = "dotnet-core"; ManifestType["PACKAGES_CONFIG"] = "packages.config"; ManifestType["PAKET"] = "paket"; })(ManifestType || (exports.ManifestType = ManifestType = {})); //# sourceMappingURL=types.js.map /***/ }), /***/ 28743: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const line_parser_1 = __webpack_require__(98512); const COMMENTS = ['#', '//']; const GROUP = 'group'; const SOURCE = 'source'; // https://fsprojects.github.io/Paket/dependencies-file.html#Sources const GITHUB = 'github'; const NUGET = 'nuget'; const CLITOOL = 'clitool'; const GIT = 'git'; const GIST = 'gist'; const HTTP = 'http'; function parseNuget(line) { const commentRegex = new RegExp(`(?:${COMMENTS[0]}|${COMMENTS[1]}).+`); const nameVersionOptionsRegex = new RegExp(/(\S+)\s*([^:\n]*)(:.*)?/); const versionFirstOptionRegex = new RegExp(/\s(?=[^ ]*$)/); const [, name, versionRangeAndFirstOption, restOptions] = line .replace(NUGET, '') // Remove 'nuget' string .replace(commentRegex, '') // Remove comments from line end .trim() .match(nameVersionOptionsRegex); // Split into groups for further parsing // nuget dependency result object to be returned const result = { source: NUGET, name, versionRange: versionRangeAndFirstOption, options: {}, }; if (restOptions) { // tslint:disable-next-line:prefer-const let [versionRange, firstOptionName] = versionRangeAndFirstOption.split(versionFirstOptionRegex); result.versionRange = versionRange; // If version is missing it will treat first option as version if (!firstOptionName) { result.versionRange = ''; firstOptionName = versionRange; } result.options = `${firstOptionName}${restOptions}` .split(/\s*,\s*/) // Split by comma if there is couple possibilities for option (e.g. framework >= net40, net45) .reverse() .reduce((optionsMap, option, index, array) => { if (option.includes(':')) { const [optionKey, value] = option.split(/:\s*/); optionsMap[optionKey] = value; } else { array[index + 1] = `${array[index + 1]}, ${option}`; } return optionsMap; }, {}); } return result; } // https://fsprojects.github.io/Paket/github-dependencies.html function parseGithub(line) { const re = /"[^"]*"|\S+/g; const parts = line.match(re).splice(1); const [repo, version] = parts[0].split(':'); return { file: parts[1] || '', repo, source: 'github', token: parts[2] || '', version: version || '', }; } // https://fsprojects.github.io/Paket/nuget-dependencies.html#NuGet-feeds function parseSource(line) { // Split URL and option string including possible comments. const urlRe = /^source ([^\s]+)(.*)$/i; const [, url, optionsString] = line.match(urlRe); // Options in this line is always double quoted. const options = {}; const optionsRe = /(.*?)\W*:\W*"(.*?)"/g; const optionsStringTrimmed = optionsString.trim(); let matches = optionsRe.exec(optionsStringTrimmed); while (matches) { options[matches[1].trim()] = matches[2].trim(); matches = optionsRe.exec(optionsStringTrimmed); } return { options, url, }; } function parseGroupOption(line) { // Line could be separated by space or by colon. // TODO: Think what to do with possible comment in the line. const result = line.match(/(\S+?)\s*(:|\s)\s*(.*)/); return [result[1] || '', result[3] || '']; } function parseDependenciesFile(input) { const lines = line_parser_1.parseLines(input); const result = []; let group = { dependencies: [], name: null, options: {}, sources: [], }; for (const line of lines) { const isComment = !!COMMENTS.find((comment) => line.data.startsWith(comment)); // Ignore commented lines. if (isComment) { continue; } if (line.data.startsWith(`${GROUP} `)) { result.push(group); group = { dependencies: [], name: line.data.replace(GROUP, '').trim(), options: {}, sources: [], }; } else if (line.data.startsWith(`${SOURCE} `)) { group.sources.push(parseSource(line.data)); } else if (line.data.startsWith(`${GITHUB} `)) { group.dependencies.push(parseGithub(line.data)); } else if (line.data.startsWith(`${NUGET} `)) { group.dependencies.push(parseNuget(line.data)); } else if (line.data.startsWith(`${CLITOOL} `)) { // TODO } else if (line.data.startsWith(`${GIT} `)) { // TODO } else if (line.data.startsWith(`${GIST} `)) { // TODO } else if (line.data.startsWith(`${HTTP} `)) { // TODO } else { const [name, value] = parseGroupOption(line.data); group.options[name] = value; } } result.push(group); return result; } exports.parseDependenciesFile = parseDependenciesFile; //# sourceMappingURL=dependencies-parser.js.map /***/ }), /***/ 30716: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); var invalid_user_input_error_1 = __webpack_require__(21238); exports.InvalidUserInputError = invalid_user_input_error_1.InvalidUserInputError; var out_of_sync_error_1 = __webpack_require__(54041); exports.OutOfSyncError = out_of_sync_error_1.OutOfSyncError; //# sourceMappingURL=index.js.map /***/ }), /***/ 21238: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); class InvalidUserInputError extends Error { constructor(...args) { super(...args); this.code = 422; this.name = 'InvalidUserInputError'; Error.captureStackTrace(this, InvalidUserInputError); } } exports.InvalidUserInputError = InvalidUserInputError; //# sourceMappingURL=invalid-user-input-error.js.map /***/ }), /***/ 54041: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); class OutOfSyncError extends Error { constructor(dependencyName) { super(`Dependency ${dependencyName} was not found in paket.lock. Your ` + 'paket.dependencies and paket.lock are probably out of sync. Please ' + 'run "paket install" and try again.'); this.code = 422; this.name = 'OutOfSyncError'; this.dependencyName = dependencyName; Error.captureStackTrace(this, OutOfSyncError); } } exports.OutOfSyncError = OutOfSyncError; //# sourceMappingURL=out-of-sync-error.js.map /***/ }), /***/ 15371: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __webpack_require__(70655); const lock_parser_1 = __webpack_require__(7672); const dependencies_parser_1 = __webpack_require__(28743); const path = __webpack_require__(71017); const fs = __webpack_require__(57147); const errors_1 = __webpack_require__(30716); exports.InvalidUserInputError = errors_1.InvalidUserInputError; exports.OutOfSyncError = errors_1.OutOfSyncError; const DEV_GROUPS = ['build', 'test', 'tests']; const SUPPORTED_SOURCES = ['nuget']; const FREQUENCY_THRESHOLD = 100; var DepType; (function (DepType) { DepType["prod"] = "prod"; DepType["dev"] = "dev"; })(DepType = exports.DepType || (exports.DepType = {})); function buildDepTreeFromFiles(root, manifestFilePath, lockFilePath, includeDev = false, strict = true) { return tslib_1.__awaiter(this, void 0, void 0, function* () { const manifestFileFullPath = path.resolve(root, manifestFilePath); const lockFileFullPath = path.resolve(root, lockFilePath); if (!fs.existsSync(manifestFileFullPath)) { throw new errors_1.InvalidUserInputError('Target file paket.dependencies not found at ' + `location: ${manifestFileFullPath}`); } if (!fs.existsSync(lockFileFullPath)) { throw new errors_1.InvalidUserInputError('Lockfile not found at location: ' + lockFileFullPath); } const manifestFileContents = fs.readFileSync(manifestFileFullPath, 'utf-8'); const lockFileContents = fs.readFileSync(lockFileFullPath, 'utf-8'); return { dependencies: yield buildDepTree(manifestFileContents, lockFileContents, includeDev, strict), name: path.basename(path.dirname(manifestFileFullPath)), version: '', }; }); } exports.buildDepTreeFromFiles = buildDepTreeFromFiles; function buildDepTree(manifestFileContents, lockFileContents, includeDev = false, strict = true) { return tslib_1.__awaiter(this, void 0, void 0, function* () { const manifestFile = dependencies_parser_1.parseDependenciesFile(manifestFileContents); const lockFile = lock_parser_1.parseLockFile(lockFileContents); const dependenciesMap = new Map(); collectRootDeps(manifestFile, dependenciesMap); collectResolvedDeps(lockFile, dependenciesMap); for (const dep of dependenciesMap.values()) { if (dep.root) { calculateReferences(dep, dependenciesMap); } } const dependencies = {}; for (const dep of dependenciesMap.values()) { if (dep.root && (includeDev || dep.depType === DepType.prod)) { if (strict && !dep.resolved) { throw new errors_1.OutOfSyncError(dep.name); } dependencies[dep.name] = buildTreeFromList(dep, dependenciesMap); if (!dep.resolved) { dependencies[dep.name].missingLockFileEntry = true; } } } const frequentSubTree = buildFrequentDepsSubtree(dependenciesMap); if (Object.keys(frequentSubTree.dependencies).length) { dependencies[frequentSubTree.name] = frequentSubTree; } return dependencies; }); } function collectRootDeps(manifestFile, dependenciesMap) { for (const group of manifestFile) { const isDev = DEV_GROUPS.indexOf((group.name || '').toLowerCase()) !== -1; for (const dep of group.dependencies) { if (SUPPORTED_SOURCES.indexOf(dep.source.toLowerCase()) === -1) { continue; } const nugetDep = dep; if (!dependenciesMap.has(nugetDep.name.toLowerCase())) { dependenciesMap.set(nugetDep.name.toLowerCase(), { name: nugetDep.name, // Will be overwritten in `collectResolvedDeps`. version: nugetDep.versionRange, // Will be overwritten in `collectResolvedDeps`. dependencies: [], depType: isDev ? DepType.dev : DepType.prod, root: true, refs: 1, // Will be overwritten in `collectResolvedDeps`. resolved: false, }); } } } } function collectResolvedDeps(lockFile, dependenciesMap) { for (const group of lockFile.groups) { const isDev = DEV_GROUPS.indexOf((group.name || '').toLowerCase()) !== -1; for (const dep of group.dependencies) { if (SUPPORTED_SOURCES.indexOf(dep.repository.toLowerCase()) === -1) { continue; } if (dependenciesMap.has(dep.name.toLowerCase())) { const rootDep = dependenciesMap.get(dep.name.toLowerCase()); rootDep.version = dep.version; rootDep.dependencies = dep.dependencies.map((d) => d.name.toLowerCase()); rootDep.resolved = true; } else { dependenciesMap.set(dep.name.toLowerCase(), { name: dep.name, version: dep.version, dependencies: dep.dependencies.map((d) => d.name.toLowerCase()), depType: isDev ? DepType.dev : DepType.prod, root: false, refs: 0, resolved: true, }); } } } } function calculateReferences(node, dependenciesMap) { for (const subName of node.dependencies) { const sub = dependenciesMap.get(subName); sub.refs += node.refs; // Do not propagate calculations if we already reach threshold for the node. if (sub.refs < FREQUENCY_THRESHOLD) { calculateReferences(sub, dependenciesMap); } } } function buildFrequentDepsSubtree(dependenciesMap) { const tree = { name: 'meta-common-packages', version: 'meta', dependencies: {}, }; getFrequentDependencies(dependenciesMap).forEach((listItem) => { const treeNode = buildTreeFromList(listItem, dependenciesMap); tree.dependencies[treeNode.name] = treeNode; }); return tree; } function getFrequentDependencies(dependenciesMap) { const frequentDeps = []; for (const dep of dependenciesMap.values()) { if (!dep.root && dep.refs >= FREQUENCY_THRESHOLD) { frequentDeps.push(dep); } } return frequentDeps; } function buildTreeFromList(listItem, dependenciesMap) { const tree = { name: listItem.name, version: listItem.version, dependencies: {}, depType: listItem.depType, }; for (const name of listItem.dependencies) { const subListItem = dependenciesMap.get(name); if (!(subListItem.refs >= FREQUENCY_THRESHOLD)) { const subtree = buildTreeFromList(subListItem, dependenciesMap); tree.dependencies[subtree.name] = subtree; } } return tree; } //# sourceMappingURL=index.js.map /***/ }), /***/ 98512: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); class Line { constructor(data, indentation) { this.data = data; this.indentation = indentation; } } exports.Line = Line; function countIndents(line, indent) { const spaces = line.match(/^\s*/)[0].length; const count = spaces / indent.length; if (count % 1 !== 0) { throw new Error('Line indentation malformed'); } return count; } // On windows machines first symbol of the file sometimes is special // "ZERO WIDTH NO-BREAK SPACE". Remove it before continue processing because it // could be counted as a space in `countIndents`. // // - https://en.wikipedia.org/wiki/Byte_order_mark // - https://stackoverflow.com/questions/6784799/what-is-this-char-65279 function removeByteOrderMark(input) { if (input.length > 0 && input.charAt(0) === '\uFEFF') { return input.substr(1); } return input; } // parse space indented lines into array of Lines function parseLines(input, indent = ' ' /* two spaces */, lineSeparator = /\r?\n/) { const lines = removeByteOrderMark(input).split(lineSeparator); const result = []; for (const line of lines) { const data = line.trim(); if (data === '') { // GROUPS often separated by blank lines continue; } const indentation = countIndents(line, indent); result.push(new Line(data, indentation)); } return result; } exports.parseLines = parseLines; //# sourceMappingURL=line-parser.js.map /***/ }), /***/ 7672: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const line_parser_1 = __webpack_require__(98512); const REPOSITORY_TYPES = ['HTTP', 'GIST', 'GIT', 'NUGET', 'GITHUB']; // naming convention in paket's standard parser const GROUP = 'GROUP'; const REMOTE = 'REMOTE'; const SPECS = 'SPECS'; function parseOptions(optionsString) { const options = {}; for (const option of optionsString.split(/, +/)) { const optionParts = option.split(/: +/); if (optionParts[0] !== '') { options[optionParts[0]] = optionParts[1]; } } return options; } function parseDependencyLine(line, isSubDependency) { const re = /^([^ ]+)\W+\(([^)]+)\)\W*(.*)$/; const match = line.data.match(re); const result = { name: '', version: '', options: {}, }; if (!match && !isSubDependency) { throw new Error(`Malformed paket.lock file: Missing resolved version on ${line.data}`); } // Octokit (0.10.0) // Microsoft.Net.Http // For this case where there is no version in the transitive, // we are not yet sure it is valid but want to retain the data. if (!match) { result.name = line.data; } else { result.name = match[1]; result.version = match[2]; result.options = parseOptions(match[3]); } if (!isSubDependency) { result.dependencies = []; } return result; } function parseLockFile(input) { const result = { groups: [], }; const lines = line_parser_1.parseLines(input); let group = { name: null, repositories: {}, dependencies: [], }; let depContext = {}; let dependency = null; for (const line of lines) { const upperCaseLine = line.data.toUpperCase(); if (line.indentation === 0) { // group or group option if (upperCaseLine.startsWith(GROUP)) { result.groups.push(group); depContext = {}; group = { name: line.data.substr(GROUP.length).trim(), repositories: {}, dependencies: [], }; } else if (REPOSITORY_TYPES.indexOf(upperCaseLine) !== -1) { depContext.repository = line.data; group.repositories[line.data] = []; } else { const [optionName, optionValue] = line.data.split(':'); group.options = group.options || {}; // TODO: keeping null option values to know the option names // need to decide what to do with them group.options[optionName.trim()] = optionValue ? optionValue.trim() : null; } } else if (line.indentation === 1) { // remote or specs if (upperCaseLine.startsWith(REMOTE)) { const remote = line.data.substring(REMOTE.length + ':'.length).trim(); if (remote) { depContext.remote = remote; group.repositories[depContext.repository].push(remote); } } else if (upperCaseLine.startsWith(SPECS)) { // TODO: for now we add the specs as boolean in meta group.specs = true; } } else { const dep = parseDependencyLine(line, line.indentation === 3); if (line.indentation === 2) { // Resolved Dependency dep.remote = depContext.remote; dep.repository = depContext.repository; dependency = dep; } else { // Transitive Dependency dependency.dependencies.push(dep); } } if (group && dependency && group.dependencies.indexOf(dependency) === -1) { group.dependencies.push(dependency); } } result.groups.push(group); return result; } exports.parseLockFile = parseLockFile; //# sourceMappingURL=lock-parser.js.map /***/ }), /***/ 38354: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.localComposer = exports.globalComposer = void 0; exports.cmdReturnsOk = cmdReturnsOk; exports.execWithResult = execWithResult; const path = __webpack_require__(71017); const childProcess = __webpack_require__(32081); function versionCmd() { return { command: this.command, args: [...this.args, '--version'], }; } function listPlatformDepsCmd() { return { command: this.command, args: [...this.args, 'show', '-p', '--format=json'], }; } exports.globalComposer = { command: 'composer', args: [], version: versionCmd, listPlatformDeps: listPlatformDepsCmd, }; exports.localComposer = { command: 'php', args: [`${path.resolve(path.resolve() + '/composer.phar')}`], version: versionCmd, listPlatformDeps: listPlatformDepsCmd, }; function cleanUpComposerWarnings(composerOutput) { // Remove all lines preceding the JSON data; including "Deprecated" messages and blank lines. const lines = composerOutput.split('\n'); const jsonStartIndex = lines.findIndex((line) => line.startsWith('{')); return lines.slice(jsonStartIndex).join('\n'); } function cmdReturnsOk(cmd) { const spawnOptions = { shell: false }; return (!!cmd && childProcess.spawnSync(cmd.command, cmd.args, spawnOptions).status === 0); } // run a cmd in a specific folder and it's result should be there function execWithResult(cmd, basePath) { const spawnOptions = { cwd: basePath, shell: false, }; const execResult = childProcess.spawnSync(cmd.command, cmd.args, spawnOptions); // Throw the whole Result object in case of error, similarly to `execSync`. if (execResult.status !== 0) { throw execResult; } return cleanUpComposerWarnings(execResult.stdout.toString()); } //# sourceMappingURL=composer-cmds.js.map /***/ }), /***/ 18630: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.inspect = inspect; const composerLockFileParser = __webpack_require__(59794); const system_deps_1 = __webpack_require__(21899); const PLUGIN_NAME = 'snyk-php-plugin'; async function inspect(basePath, fileName, options = {}) { const systemVersions = (0, system_deps_1.systemDeps)(basePath, options); const depsTree = composerLockFileParser.buildDepTreeFromFiles(basePath, fileName, systemVersions, options.dev); return Promise.resolve({ package: depsTree, plugin: { name: PLUGIN_NAME, targetFile: fileName }, }); } //# sourceMappingURL=index.js.map /***/ }), /***/ 21899: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.systemDeps = systemDeps; const cmds = __webpack_require__(38354); function systemDeps(basePath, options) { var _a, _b; const composerOk = (_a = options.composerIsFine) !== null && _a !== void 0 ? _a : cmds.cmdReturnsOk(cmds.globalComposer.version()); const composerPharOk = (_b = options.composerPharIsFine) !== null && _b !== void 0 ? _b : cmds.cmdReturnsOk(cmds.localComposer.version()); let finalVersionsObj = {}; if (options.systemVersions && Object.keys(options.systemVersions).length > 0) { // give first preference to a stub finalVersionsObj = options.systemVersions; } else if (composerOk || composerPharOk) { const composer = composerOk ? cmds.globalComposer : cmds.localComposer; const output = cmds.execWithResult(composer.listPlatformDeps(), basePath); const versionsObj = JSON.parse(output).platform; versionsObj.forEach(({ name, version }) => { finalVersionsObj[name] = version; }); } else { // TODO: tell the user we are not reporting accurately system versions, so some version info may not be exact } return finalVersionsObj; } //# sourceMappingURL=system-deps.js.map /***/ }), /***/ 34580: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildDepGraph = buildDepGraph; const manifest = __webpack_require__(91314); const lockFile = __webpack_require__(95531); const poetryDepGraphBuilder = __webpack_require__(42393); function buildDepGraph(manifestFileContents, lockFileContents, includeDevDependencies = false) { const dependencies = manifest.getDependenciesFrom(manifestFileContents, includeDevDependencies); const pkgDetails = manifest.pkgInfoFrom(manifestFileContents); const pkgSpecs = lockFile.packageSpecsFrom(lockFileContents); return poetryDepGraphBuilder.build(pkgDetails, dependencies, pkgSpecs); } //# sourceMappingURL=index.js.map /***/ }), /***/ 95531: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.packageSpecsFrom = packageSpecsFrom; const toml = __webpack_require__(5022); const error_catalog_nodejs_public_1 = __webpack_require__(82073); function packageSpecsFrom(lockFileContents) { let lockFile; try { lockFile = toml.parse(lockFileContents); } catch (error) { throw new error_catalog_nodejs_public_1.OpenSourceEcosystems.UnparseableLockFileError('The poetry.lock file is not parsable.', { error }); } if (!lockFile.package) { throw new error_catalog_nodejs_public_1.OpenSourceEcosystems.UnparseableLockFileError('The poetry.lock file contains no package stanza.'); } return lockFile.package.map((pkg) => { return { name: pkg.name, version: pkg.version, dependencies: Object.keys(pkg.dependencies || []), }; }); } //# sourceMappingURL=lock-file-parser.js.map /***/ }), /***/ 91314: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.pkgInfoFrom = pkgInfoFrom; exports.getDependenciesFrom = getDependenciesFrom; const utils_1 = __webpack_require__(96397); function pkgInfoFrom(manifestFileContents) { const parser = (0, utils_1.createManifestFileParser)(manifestFileContents); return parser.pkgInfoFrom(); } function getDependenciesFrom(manifestFileContents, includeDevDependencies) { const parser = (0, utils_1.createManifestFileParser)(manifestFileContents, includeDevDependencies); return parser.getDependencies(); } //# sourceMappingURL=manifest-parser.js.map /***/ }), /***/ 47896: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.V1Parser = void 0; class V1Parser { constructor(manifest, includeDevDependencies) { this.version = '1'; this.manifest = manifest; this.includeDevDependencies = !!includeDevDependencies; } pkgInfoFrom() { return { name: this.manifest.tool.poetry.name, version: this.manifest.tool.poetry.version, }; } dependenciesFrom() { return Object.keys(this.manifest.tool.poetry.dependencies || []); } getGroupDevDepNames(obj) { return Object.values(obj) .map((group) => group.dependencies) .map((depsObj) => Object.keys(depsObj)) .reduce((acc, curr) => [...acc, ...curr], []); } getAllDevDependencyNames() { var _a, _b, _c; // pre-v1.2.0 naming convention const devDepsProperty = Object.keys((_a = this.manifest.tool.poetry['dev-dependencies']) !== null && _a !== void 0 ? _a : []); // post-v1.2.0 dependency groups // https://python-poetry.org/docs/master/managing-dependencies // we will handle all tool.poetry.group. as dev-deps const groupDevDepsProperty = ((_b = this.manifest.tool) === null || _b === void 0 ? void 0 : _b.poetry.group) ? this.getGroupDevDepNames((_c = this.manifest.tool) === null || _c === void 0 ? void 0 : _c.poetry.group) : []; return [...devDepsProperty, ...groupDevDepsProperty]; } getDependencies() { const dependencies = this.dependenciesFrom().map((dep) => ({ name: dep, isDev: false, })); const devDependencies = (this.includeDevDependencies ? this.getAllDevDependencyNames() : []).map((devDep) => ({ name: devDep, isDev: true, })); return [...dependencies, ...devDependencies].filter((pkg) => pkg.name != 'python'); } } exports.V1Parser = V1Parser; //# sourceMappingURL=v1Parser.js.map /***/ }), /***/ 98565: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.V2Parser = void 0; class V2Parser { constructor(manifest, includeDevDependencies) { this.version = '2'; this.manifest = manifest; this.includeDevDependencies = !!includeDevDependencies; } pkgInfoFrom() { return { name: this.manifest.project.name, version: this.manifest.project.version, }; } dependenciesFrom() { var _a, _b; const depsRegex = /^[a-zA-Z][a-zA-Z0-9_-]*/; const deps = this.manifest.project.dependencies || []; const newFormatDeps = deps .map((dep) => { var _a; return (_a = dep.match(depsRegex)) === null || _a === void 0 ? void 0 : _a[0]; }) .filter((dep) => typeof dep === 'string') || []; const legacyFormatDeps = Object.keys(((_b = (_a = this.manifest.tool) === null || _a === void 0 ? void 0 : _a.poetry) === null || _b === void 0 ? void 0 : _b.dependencies) || []); return [...newFormatDeps, ...legacyFormatDeps]; } getGroupDevDepNames(obj) { const groupDevDepNames = Object.values(obj) .map((group) => group.dependencies) .map((depsObj) => Object.keys(depsObj)) .reduce((acc, curr) => [...acc, ...curr], []); return groupDevDepNames; } getAllDevDependencyNames() { var _a, _b, _c, _d, _e, _f, _g; // pre-v1.2.0 naming convention const devDepsProperty = Object.keys((_c = (_b = (_a = this.manifest.tool) === null || _a === void 0 ? void 0 : _a.poetry.group) === null || _b === void 0 ? void 0 : _b.dev.dependencies) !== null && _c !== void 0 ? _c : []); const legacyDevDepsProperty = Object.keys((_e = (_d = this.manifest.tool) === null || _d === void 0 ? void 0 : _d.poetry['dev-dependencies']) !== null && _e !== void 0 ? _e : []); // post-v1.2.0 dependency groups // https://python-poetry.org/docs/master/managing-dependencies // we will handle all tool.poetry.group. as dev-deps const groupDevDepsProperty = ((_f = this.manifest.tool) === null || _f === void 0 ? void 0 : _f.poetry.group) ? this.getGroupDevDepNames((_g = this.manifest.tool) === null || _g === void 0 ? void 0 : _g.poetry.group) : []; return [ ...devDepsProperty, ...groupDevDepsProperty, ...legacyDevDepsProperty, ]; } getDependencies() { const dependencies = this.dependenciesFrom().map((dep) => ({ name: dep, isDev: false, })); const devDependencies = (this.includeDevDependencies ? this.getAllDevDependencyNames() : []).map((devDep) => ({ name: devDep, isDev: true, })); return [...dependencies, ...devDependencies].filter((pkg) => pkg.name != 'python'); } } exports.V2Parser = V2Parser; //# sourceMappingURL=v2Parser.js.map /***/ }), /***/ 42393: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.build = build; const lodash_1 = __webpack_require__(96486); const dep_graph_1 = __webpack_require__(71479); // Poetry uses the virtualenv to create an environment and this comes with these // packages pre-installed, therefore they won't be part of the lockfile. // See: https://github.com/python-poetry/poetry/issues/3075#issuecomment-703334427 const IGNORED_DEPENDENCIES = [ 'setuptools', 'distribute', 'pip', 'wheel', ]; const DEFAULT_ROOT_PKG = { name: '_root', version: '0.0.0', }; function build(pkgDetails, dependencies, pkgSpecs) { const rootPkg = (0, lodash_1.defaults)({}, pkgDetails, DEFAULT_ROOT_PKG); const builder = new dep_graph_1.DepGraphBuilder({ name: 'poetry' }, rootPkg); addDependenciesToGraph(dependencies, pkgSpecs, builder.rootNodeId, builder); return builder.build(); } function addDependenciesToGraph(dependencies, pkgSpecs, parentNodeId, builder) { for (const dep of dependencies) { addDependenciesForPkg(dep, pkgSpecs, parentNodeId, builder); } } function addDependenciesForPkg(dependency, pkgSpecs, parentNodeId, builder) { const pkgName = dependency.name; if (IGNORED_DEPENDENCIES.includes(pkgName)) { return; } const pkg = pkgLockInfoFor(pkgName, pkgSpecs); if (!pkg) { return; } if (isPkgAlreadyInGraph(pkg, builder)) { builder.connectDep(parentNodeId, pkg.name); return; } const pkgInfo = { name: pkg.name, version: pkg.version }; const labels = { scope: dependency.isDev ? 'dev' : 'prod', }; if (pkg.name != pkgName) { labels.pkgIdProvenance = `${pkgName}@${pkg.version}`; } builder .addPkgNode(pkgInfo, pkg.name, { labels, }) .connectDep(parentNodeId, pkg.name); addDependenciesToGraph(pkg.dependencies.map((dep) => ({ name: dep, isDev: dependency.isDev, })), pkgSpecs, pkg.name, builder); } function isPkgAlreadyInGraph(pkg, builder) { return builder .getPkgs() .some((existingPkg) => existingPkg.name === pkg.name && existingPkg.version === pkg.version); } function pkgLockInfoFor(pkgName, pkgSpecs) { // From PEP 426 https://www.python.org/dev/peps/pep-0426/#name // All comparisons of distribution names MUST be case insensitive, and MUST // consider hyphens and underscores to be equivalent const pkgLockInfo = pkgSpecs.find((lockItem) => lockItem.name.toLowerCase().replace(/_/g, '-') === pkgName.toLowerCase().replace(/_/g, '-') || lockItem.name.toLowerCase().replace(/-/g, '_') === pkgName.toLowerCase().replace(/-/g, '_')); if (!pkgLockInfo) { console.warn(`Could not find any lockfile metadata for package: ${pkgName}. This package will not be represented in the dependency graph.`); } return pkgLockInfo; } //# sourceMappingURL=poetry-dep-graph-builder.js.map /***/ }), /***/ 96397: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createManifestFileParser = void 0; const toml = __webpack_require__(5022); const error_catalog_nodejs_public_1 = __webpack_require__(82073); const v1Parser_1 = __webpack_require__(47896); const v2Parser_1 = __webpack_require__(98565); const createManifestFileParser = (manifestFileContents, includeDevDependencies) => { var _a; let manifest; try { manifest = toml.parse(manifestFileContents); } catch (error) { throw new error_catalog_nodejs_public_1.OpenSourceEcosystems.UnparseableManifestError('The pyproject.toml file is not parsable.', { error }); } if (manifest.project) { return new v2Parser_1.V2Parser(manifest, includeDevDependencies); } if ((_a = manifest.tool) === null || _a === void 0 ? void 0 : _a.poetry) { return new v1Parser_1.V1Parser(manifest, includeDevDependencies); } throw new error_catalog_nodejs_public_1.OpenSourceEcosystems.UnparseableManifestError('The pyproject.toml is not a valid poetry file.'); }; exports.createManifestFileParser = createManifestFileParser; //# sourceMappingURL=utils.js.map /***/ }), /***/ 73901: /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; // ESM COMPAT FLAG __webpack_require__.r(__webpack_exports__); // EXPORTS __webpack_require__.d(__webpack_exports__, { "NIL": () => (/* reexport */ nil), "parse": () => (/* reexport */ esm_node_parse), "stringify": () => (/* reexport */ esm_node_stringify), "v1": () => (/* reexport */ esm_node_v1), "v3": () => (/* reexport */ esm_node_v3), "v4": () => (/* reexport */ esm_node_v4), "v5": () => (/* reexport */ esm_node_v5), "validate": () => (/* reexport */ esm_node_validate), "version": () => (/* reexport */ esm_node_version) }); // EXTERNAL MODULE: external "crypto" var external_crypto_ = __webpack_require__(6113); var external_crypto_default = /*#__PURE__*/__webpack_require__.n(external_crypto_); ;// CONCATENATED MODULE: ./node_modules/snyk-poetry-lockfile-parser/node_modules/uuid/dist/esm-node/rng.js const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate let poolPtr = rnds8Pool.length; function rng() { if (poolPtr > rnds8Pool.length - 16) { external_crypto_default().randomFillSync(rnds8Pool); poolPtr = 0; } return rnds8Pool.slice(poolPtr, poolPtr += 16); } ;// CONCATENATED MODULE: ./node_modules/snyk-poetry-lockfile-parser/node_modules/uuid/dist/esm-node/regex.js /* harmony default export */ const regex = (/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i); ;// CONCATENATED MODULE: ./node_modules/snyk-poetry-lockfile-parser/node_modules/uuid/dist/esm-node/validate.js function validate(uuid) { return typeof uuid === 'string' && regex.test(uuid); } /* harmony default export */ const esm_node_validate = (validate); ;// CONCATENATED MODULE: ./node_modules/snyk-poetry-lockfile-parser/node_modules/uuid/dist/esm-node/stringify.js /** * 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]]; } function stringify(arr, offset = 0) { const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one // of the following: // - One or more input array values don't map to a hex octet (leading to // "undefined" in the uuid) // - Invalid input values for the RFC `version` or `variant` fields if (!esm_node_validate(uuid)) { throw TypeError('Stringified UUID is invalid'); } return uuid; } /* harmony default export */ const esm_node_stringify = (stringify); ;// CONCATENATED MODULE: ./node_modules/snyk-poetry-lockfile-parser/node_modules/uuid/dist/esm-node/v1.js // **`v1()` - Generate time-based UUID** // // Inspired by https://github.com/LiosK/UUID.js // and http://docs.python.org/library/uuid.html let _nodeId; let _clockseq; // Previous uuid creation time let _lastMSecs = 0; let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details function v1(options, buf, offset) { let i = buf && offset || 0; const b = buf || new Array(16); options = options || {}; let node = options.node || _nodeId; let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not // specified. We do this lazily to minimize issues related to insufficient // system entropy. See #189 if (node == null || clockseq == null) { const seedBytes = options.random || (options.rng || rng)(); if (node == null) { // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; } if (clockseq == null) { // Per 4.2.2, randomize (14 bit) clockseq clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; } } // UUID timestamps are 100 nano-second units since the Gregorian epoch, // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock // cycle to simulate higher resolution clock let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression if (dt < 0 && options.clockseq === undefined) { clockseq = clockseq + 1 & 0x3fff; } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new // time interval if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { nsecs = 0; } // Per 4.2.1.2 Throw error if too many uuids are requested if (nsecs >= 10000) { throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); } _lastMSecs = msecs; _lastNSecs = nsecs; _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch msecs += 12219292800000; // `time_low` const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; b[i++] = tl >>> 24 & 0xff; b[i++] = tl >>> 16 & 0xff; b[i++] = tl >>> 8 & 0xff; b[i++] = tl & 0xff; // `time_mid` const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; b[i++] = tmh >>> 8 & 0xff; b[i++] = tmh & 0xff; // `time_high_and_version` b[i++] = tmh >>> 24 & 0xf | 0x10; // include version b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` b[i++] = clockseq & 0xff; // `node` for (let n = 0; n < 6; ++n) { b[i + n] = node[n]; } return buf || unsafeStringify(b); } /* harmony default export */ const esm_node_v1 = (v1); ;// CONCATENATED MODULE: ./node_modules/snyk-poetry-lockfile-parser/node_modules/uuid/dist/esm-node/parse.js function parse(uuid) { if (!esm_node_validate(uuid)) { throw TypeError('Invalid UUID'); } let v; const arr = new Uint8Array(16); // Parse ########-....-....-....-............ arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; arr[1] = v >>> 16 & 0xff; arr[2] = v >>> 8 & 0xff; arr[3] = v & 0xff; // Parse ........-####-....-....-............ arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; arr[5] = v & 0xff; // Parse ........-....-####-....-............ arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; arr[7] = v & 0xff; // Parse ........-....-....-####-............ arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; arr[9] = v & 0xff; // Parse ........-....-....-....-############ // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; arr[11] = v / 0x100000000 & 0xff; arr[12] = v >>> 24 & 0xff; arr[13] = v >>> 16 & 0xff; arr[14] = v >>> 8 & 0xff; arr[15] = v & 0xff; return arr; } /* harmony default export */ const esm_node_parse = (parse); ;// CONCATENATED MODULE: ./node_modules/snyk-poetry-lockfile-parser/node_modules/uuid/dist/esm-node/v35.js function stringToBytes(str) { str = unescape(encodeURIComponent(str)); // UTF8 escape const bytes = []; for (let i = 0; i < str.length; ++i) { bytes.push(str.charCodeAt(i)); } return bytes; } const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; function v35(name, version, hashfunc) { function generateUUID(value, namespace, buf, offset) { var _namespace; if (typeof value === 'string') { value = stringToBytes(value); } if (typeof namespace === 'string') { namespace = esm_node_parse(namespace); } if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); } // Compute hash of namespace and value, Per 4.3 // Future: Use spread syntax when supported on all platforms, e.g. `bytes = // hashfunc([...namespace, ... value])` let bytes = new Uint8Array(16 + value.length); bytes.set(namespace); bytes.set(value, namespace.length); bytes = hashfunc(bytes); bytes[6] = bytes[6] & 0x0f | version; bytes[8] = bytes[8] & 0x3f | 0x80; if (buf) { offset = offset || 0; for (let i = 0; i < 16; ++i) { buf[offset + i] = bytes[i]; } return buf; } return unsafeStringify(bytes); } // Function#name is not settable on some platforms (#270) try { generateUUID.name = name; // eslint-disable-next-line no-empty } catch (err) {} // For CommonJS default export support generateUUID.DNS = DNS; generateUUID.URL = URL; return generateUUID; } ;// CONCATENATED MODULE: ./node_modules/snyk-poetry-lockfile-parser/node_modules/uuid/dist/esm-node/md5.js function md5(bytes) { if (Array.isArray(bytes)) { bytes = Buffer.from(bytes); } else if (typeof bytes === 'string') { bytes = Buffer.from(bytes, 'utf8'); } return external_crypto_default().createHash('md5').update(bytes).digest(); } /* harmony default export */ const esm_node_md5 = (md5); ;// CONCATENATED MODULE: ./node_modules/snyk-poetry-lockfile-parser/node_modules/uuid/dist/esm-node/v3.js const v3 = v35('v3', 0x30, esm_node_md5); /* harmony default export */ const esm_node_v3 = (v3); ;// CONCATENATED MODULE: ./node_modules/snyk-poetry-lockfile-parser/node_modules/uuid/dist/esm-node/native.js /* harmony default export */ const esm_node_native = ({ randomUUID: (external_crypto_default()).randomUUID }); ;// CONCATENATED MODULE: ./node_modules/snyk-poetry-lockfile-parser/node_modules/uuid/dist/esm-node/v4.js function v4(options, buf, offset) { if (esm_node_native.randomUUID && !buf && !options) { return esm_node_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); } /* harmony default export */ const esm_node_v4 = (v4); ;// CONCATENATED MODULE: ./node_modules/snyk-poetry-lockfile-parser/node_modules/uuid/dist/esm-node/sha1.js function sha1(bytes) { if (Array.isArray(bytes)) { bytes = Buffer.from(bytes); } else if (typeof bytes === 'string') { bytes = Buffer.from(bytes, 'utf8'); } return external_crypto_default().createHash('sha1').update(bytes).digest(); } /* harmony default export */ const esm_node_sha1 = (sha1); ;// CONCATENATED MODULE: ./node_modules/snyk-poetry-lockfile-parser/node_modules/uuid/dist/esm-node/v5.js const v5 = v35('v5', 0x50, esm_node_sha1); /* harmony default export */ const esm_node_v5 = (v5); ;// CONCATENATED MODULE: ./node_modules/snyk-poetry-lockfile-parser/node_modules/uuid/dist/esm-node/nil.js /* harmony default export */ const nil = ('00000000-0000-0000-0000-000000000000'); ;// CONCATENATED MODULE: ./node_modules/snyk-poetry-lockfile-parser/node_modules/uuid/dist/esm-node/version.js function version(uuid) { if (!esm_node_validate(uuid)) { throw TypeError('Invalid UUID'); } return parseInt(uuid.slice(14, 15), 16); } /* harmony default export */ const esm_node_version = (version); ;// CONCATENATED MODULE: ./node_modules/snyk-poetry-lockfile-parser/node_modules/uuid/dist/esm-node/index.js /***/ }), /***/ 41669: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildDepGraph = void 0; const legacy_1 = __webpack_require__(51731); function buildDepGraph(partialDepTree, projectName) { const packageToDepTreeMap = new Map(); const queue = [partialDepTree.dependencies]; const referencesToUpdate = []; while (queue.length > 0) { const dependencies = queue.pop(); if (!dependencies) continue; for (const [key, dependencyDepTree] of Object.entries(dependencies)) { if (dependencyDepTree === 'true') { referencesToUpdate.push({ key, dependencies }); } else { packageToDepTreeMap.set(key, dependencyDepTree); queue.push(dependencyDepTree.dependencies); } } } referencesToUpdate.forEach(({ key, dependencies }) => { if (!packageToDepTreeMap.get(key)) { // this should never happen throw new Error(`key ${key} not found in packageToDepTreeMap`); } dependencies[key] = packageToDepTreeMap.get(key); }); if (projectName) partialDepTree.name = projectName; return (0, legacy_1.depTreeToGraph)(partialDepTree, 'pip'); } exports.buildDepGraph = buildDepGraph; //# sourceMappingURL=build-dep-graph.js.map /***/ }), /***/ 69797: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getDependencies = void 0; const tslib_1 = __webpack_require__(70655); const path = __webpack_require__(71017); const subProcess = __webpack_require__(9783); const inspect_implementation_1 = __webpack_require__(11297); const poetry_1 = __webpack_require__(98406); const types_1 = __webpack_require__(62914); // Given a path to a manifest file and assuming that all the packages (transitively required by the // manifest) were installed (e.g. using `pip install`), produce a tree of dependencies. function getDependencies(root, targetFile, options) { return tslib_1.__awaiter(this, void 0, void 0, function* () { if (!options) { options = {}; } let command = options.command || 'python'; const includeDevDeps = !!(options.dev || false); // handle poetry projects by parsing manifest & lockfile and return a dep-graph if (path.basename(targetFile) === types_1.FILENAMES.poetry.lockfile) { return (0, poetry_1.getPoetryDependencies)(command, root, targetFile, includeDevDeps); } let baseargs = []; if (path.basename(targetFile) === types_1.FILENAMES.pipenv.manifest) { // Check that pipenv is available by running it. const pipenvCheckProc = subProcess.executeSync('pipenv', ['--version']); if (pipenvCheckProc.status !== 0) { throw new Error('Failed to run `pipenv`; please make sure it is installed.'); } command = 'pipenv'; baseargs = ['run', 'python']; } const [plugin, dependencyGraph] = yield Promise.all([ (0, inspect_implementation_1.getMetaData)(command, baseargs, root, targetFile), (0, inspect_implementation_1.inspectInstalledDeps)(command, baseargs, root, targetFile, options.allowMissing || false, includeDevDeps, options.allowEmpty, options.args, options.projectName), ]); return { plugin, dependencyGraph }; }); } exports.getDependencies = getDependencies; //# sourceMappingURL=index.js.map /***/ }), /***/ 11297: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildArgs = exports.getPythonEnv = exports.inspectInstalledDeps = exports.getMetaData = void 0; const tslib_1 = __webpack_require__(70655); const fs = __webpack_require__(57147); const path = __webpack_require__(71017); const tmp = __webpack_require__(77997); const subProcess = __webpack_require__(9783); const build_dep_graph_1 = __webpack_require__(41669); const types_1 = __webpack_require__(62914); const errors_1 = __webpack_require__(99893); const returnedTargetFile = (originalTargetFile) => { const basename = path.basename(originalTargetFile); switch (basename) { case types_1.FILENAMES.poetry.lockfile: { const dirname = path.dirname(originalTargetFile); const pyprojectRelativePath = path.join(dirname, types_1.FILENAMES.poetry.manifest); return pyprojectRelativePath; } case types_1.FILENAMES.pipenv.manifest: case types_1.FILENAMES.setuptools.manifest: return originalTargetFile; default: return; } }; function getMetaData(command, baseargs, root, targetFile) { const pythonEnv = getPythonEnv(targetFile); return subProcess .execute(command, [...baseargs, '--version'], { cwd: root, env: pythonEnv }) .then((output) => { return { name: 'snyk-python-plugin', runtime: output.replace('\n', ''), targetFile: returnedTargetFile(targetFile), }; }); } exports.getMetaData = getMetaData; // path.join calls have to be exactly in this format, needed by "pkg" to build a standalone Snyk CLI binary: // https://www.npmjs.com/package/pkg#detecting-assets-in-source-code function createAssets() { return [ path.join(__dirname, '../../pysrc/constants.py'), path.join(__dirname, '../../pysrc/pip_resolve.py'), path.join(__dirname, '../../pysrc/distPackage.py'), path.join(__dirname, '../../pysrc/package.py'), path.join(__dirname, '../../pysrc/pipfile.py'), path.join(__dirname, '../../pysrc/reqPackage.py'), path.join(__dirname, '../../pysrc/setup_file.py'), path.join(__dirname, '../../pysrc/utils.py'), path.join(__dirname, '../../pysrc/pkg_resources.py'), path.join(__dirname, '../../pysrc/requirements/fragment.py'), path.join(__dirname, '../../pysrc/requirements/parser.py'), path.join(__dirname, '../../pysrc/requirements/requirement.py'), path.join(__dirname, '../../pysrc/requirements/vcs.py'), path.join(__dirname, '../../pysrc/requirements/__init__.py'), path.join(__dirname, '../../pysrc/pytoml/__init__.py'), path.join(__dirname, '../../pysrc/pytoml/core.py'), path.join(__dirname, '../../pysrc/pytoml/parser.py'), path.join(__dirname, '../../pysrc/pytoml/writer.py'), path.join(__dirname, '../../pysrc/pkg_resources_py2/_vendor/packaging/version.py'), path.join(__dirname, '../../pysrc/pkg_resources_py2/_vendor/packaging/__init__.py'), path.join(__dirname, '../../pysrc/pkg_resources_py2/_vendor/packaging/utils.py'), path.join(__dirname, '../../pysrc/pkg_resources_py2/_vendor/packaging/requirements.py'), path.join(__dirname, '../../pysrc/pkg_resources_py2/_vendor/packaging/_structures.py'), path.join(__dirname, '../../pysrc/pkg_resources_py2/_vendor/packaging/markers.py'), path.join(__dirname, '../../pysrc/pkg_resources_py2/_vendor/packaging/__about__.py'), path.join(__dirname, '../../pysrc/pkg_resources_py2/_vendor/packaging/_compat.py'), path.join(__dirname, '../../pysrc/pkg_resources_py2/_vendor/packaging/specifiers.py'), path.join(__dirname, '../../pysrc/pkg_resources_py2/_vendor/__init__.py'), path.join(__dirname, '../../pysrc/pkg_resources_py2/_vendor/appdirs.py'), path.join(__dirname, '../../pysrc/pkg_resources_py2/_vendor/six.py'), path.join(__dirname, '../../pysrc/pkg_resources_py2/_vendor/pyparsing.py'), path.join(__dirname, '../../pysrc/pkg_resources_py2/extern/__init__.py'), path.join(__dirname, '../../pysrc/pkg_resources_py2/py31compat.py'), path.join(__dirname, '../../pysrc/pkg_resources_py2/__init__.py'), path.join(__dirname, '../../pysrc/pkg_resources_py3/_vendor/packaging/tags.py'), path.join(__dirname, '../../pysrc/pkg_resources_py3/_vendor/packaging/_musllinux.py'), path.join(__dirname, '../../pysrc/pkg_resources_py3/_vendor/packaging/version.py'), path.join(__dirname, '../../pysrc/pkg_resources_py3/_vendor/packaging/__init__.py'), path.join(__dirname, '../../pysrc/pkg_resources_py3/_vendor/packaging/utils.py'), path.join(__dirname, '../../pysrc/pkg_resources_py3/_vendor/packaging/requirements.py'), path.join(__dirname, '../../pysrc/pkg_resources_py3/_vendor/packaging/_structures.py'), path.join(__dirname, '../../pysrc/pkg_resources_py3/_vendor/packaging/markers.py'), path.join(__dirname, '../../pysrc/pkg_resources_py3/_vendor/packaging/__about__.py'), path.join(__dirname, '../../pysrc/pkg_resources_py3/_vendor/packaging/_manylinux.py'), path.join(__dirname, '../../pysrc/pkg_resources_py3/_vendor/packaging/specifiers.py'), path.join(__dirname, '../../pysrc/pkg_resources_py3/_vendor/__init__.py'), path.join(__dirname, '../../pysrc/pkg_resources_py3/_vendor/appdirs.py'), path.join(__dirname, '../../pysrc/pkg_resources_py3/_vendor/pyparsing.py'), path.join(__dirname, '../../pysrc/pkg_resources_py3/__init__.py'), path.join(__dirname, '../../pysrc/pkg_resources_py3/extern/__init__.py'), path.join(__dirname, '../../pysrc/pkg_resources_py3_12/__init__.py'), ]; } function writeFile(writeFilePath, contents) { const dirPath = path.dirname(writeFilePath); if (!fs.existsSync(dirPath)) { fs.mkdirSync(dirPath, { recursive: true }); } fs.writeFileSync(writeFilePath, contents); } function getFilePathRelativeToDumpDir(filePath) { let pathParts = filePath.split('\\pysrc\\'); // Windows if (pathParts.length > 1) { return pathParts[1]; } // Unix pathParts = filePath.split('/pysrc/'); return pathParts[1]; } function dumpAllFilesInTempDir(tempDirName) { createAssets().forEach((currentReadFilePath) => { if (!fs.existsSync(currentReadFilePath)) { throw new Error('The file `' + currentReadFilePath + '` is missing'); } const relFilePathToDumpDir = getFilePathRelativeToDumpDir(currentReadFilePath); const writeFilePath = path.join(tempDirName, relFilePathToDumpDir); const contents = fs.readFileSync(currentReadFilePath, 'utf8'); writeFile(writeFilePath, contents); }); } function inspectInstalledDeps(command, baseargs, root, targetFile, allowMissing, includeDevDeps, allowEmpty, args, projectName) { return tslib_1.__awaiter(this, void 0, void 0, function* () { const tempDirObj = tmp.dirSync({ unsafeCleanup: true, }); dumpAllFilesInTempDir(tempDirObj.name); try { const pythonEnv = getPythonEnv(targetFile); // See ../../pysrc/README.md const output = yield subProcess.execute(command, [ ...baseargs, ...buildArgs(targetFile, allowMissing, allowEmpty, tempDirObj.name, includeDevDeps, args), ], { cwd: root, env: pythonEnv, }); const result = JSON.parse(output); return (0, build_dep_graph_1.buildDepGraph)(result, projectName); } catch (error) { if (typeof error === 'string') { const emptyManifestMsg = 'No dependencies detected in manifest.'; const noDependenciesDetected = error.includes(emptyManifestMsg); if (noDependenciesDetected) { throw new errors_1.EmptyManifestError(emptyManifestMsg); } if (error.indexOf('Required packages missing') !== -1) { let errMsg = error; if (path.basename(targetFile) === types_1.FILENAMES.pipenv.manifest) { errMsg += '\nPlease run `pipenv update`.'; } else if (path.basename(targetFile) === types_1.FILENAMES.setuptools.manifest) { errMsg += '\nPlease run `pip install -e .`.'; } else { errMsg += '\nPlease run `pip install -r ' + targetFile + '`.'; } errMsg += ' If the issue persists try again with --skip-unresolved.'; throw new errors_1.RequiredPackagesMissingError(errMsg); } if (error.indexOf('Unparsable requirement line') !== -1) { throw new errors_1.UnparsableRequirementError(error); } } throw error; } finally { tempDirObj.removeCallback(); } }); } exports.inspectInstalledDeps = inspectInstalledDeps; function getPythonEnv(targetFile) { if (path.basename(targetFile) === 'Pipfile') { const envOverrides = { PIPENV_PIPFILE: targetFile, }; return Object.assign(Object.assign({}, process.env), envOverrides); } else { return process.env; } } exports.getPythonEnv = getPythonEnv; // Exported for tests only function buildArgs(targetFile, allowMissing, allowEmpty, tempDirPath, includeDevDeps, extraArgs) { const pathToRun = path.join(tempDirPath, 'pip_resolve.py'); let args = [pathToRun]; if (targetFile) { args.push(targetFile); } if (allowMissing) { args.push('--allow-missing'); } if (allowEmpty) { args.push('--allow-empty'); } if (includeDevDeps) { args.push('--dev-deps'); } if (extraArgs) { args = args.concat(extraArgs); } return args; } exports.buildArgs = buildArgs; //# sourceMappingURL=inspect-implementation.js.map /***/ }), /***/ 98406: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getPoetryDependencies = void 0; const tslib_1 = __webpack_require__(70655); const fs = __webpack_require__(57147); const path = __webpack_require__(71017); const poetry = __webpack_require__(34580); const inspect_implementation_1 = __webpack_require__(11297); const types_1 = __webpack_require__(62914); function getPoetryDependencies(command, root, targetFile, includeDevDeps = false) { return tslib_1.__awaiter(this, void 0, void 0, function* () { const lockfilePath = path.join(root, targetFile); const baseDir = path.dirname(lockfilePath); const manifestPath = path.join(baseDir, types_1.FILENAMES.poetry.manifest); const manifestExists = fs.existsSync(manifestPath); if (!manifestExists) { throw new Error('Cannot find manifest file ' + manifestPath); } const lockfileExists = fs.existsSync(lockfilePath); if (!lockfileExists) { throw new Error('Cannot find lockfile ' + lockfilePath); } try { const manifestContents = fs.readFileSync(manifestPath, 'utf-8'); const lockfileContents = fs.readFileSync(lockfilePath, 'utf-8'); const dependencyGraph = poetry.buildDepGraph(manifestContents, lockfileContents, includeDevDeps); const plugin = yield (0, inspect_implementation_1.getMetaData)(command, [], root, targetFile); return { plugin, package: null, dependencyGraph, }; } catch (error) { throw new Error('Error processing poetry project. ' + (error.message || error)); } }); } exports.getPoetryDependencies = getPoetryDependencies; //# sourceMappingURL=poetry.js.map /***/ }), /***/ 9783: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.executeSync = exports.execute = void 0; const child_process_1 = __webpack_require__(32081); const shescape_1 = __webpack_require__(79114); function makeSpawnOptions(options) { const spawnOptions = { shell: true, env: Object.assign({}, process.env), }; if (options && options.cwd) { spawnOptions.cwd = options.cwd; } if (options && options.env) { spawnOptions.env = Object.assign({}, options.env); } // Before spawning an external process, we look if we need to restore the system proxy configuration, // which overides the cli internal proxy configuration. if (process.env.SNYK_SYSTEM_HTTP_PROXY !== undefined) { spawnOptions.env.HTTP_PROXY = process.env.SNYK_SYSTEM_HTTP_PROXY; } if (process.env.SNYK_SYSTEM_HTTPS_PROXY !== undefined) { spawnOptions.env.HTTPS_PROXY = process.env.SNYK_SYSTEM_HTTPS_PROXY; } if (process.env.SNYK_SYSTEM_NO_PROXY !== undefined) { spawnOptions.env.NO_PROXY = process.env.SNYK_SYSTEM_NO_PROXY; } return spawnOptions; } function execute(command, args, options) { const spawnOptions = makeSpawnOptions(options); args = (0, shescape_1.quoteAll)(args, spawnOptions); return new Promise((resolve, reject) => { let stdout = ''; let stderr = ''; const proc = (0, child_process_1.spawn)(command, args, spawnOptions); proc.stdout.on('data', (data) => { stdout = stdout + data; }); proc.stderr.on('data', (data) => { stderr = stderr + data; }); proc.on('close', (code) => { if (code !== 0) { return reject(stdout || stderr); } resolve(stdout || stderr); }); }); } exports.execute = execute; function executeSync(command, args, options) { const spawnOptions = makeSpawnOptions(options); args = (0, shescape_1.quoteAll)(args, spawnOptions); return (0, child_process_1.spawnSync)(command, args, spawnOptions); } exports.executeSync = executeSync; //# sourceMappingURL=sub-process.js.map /***/ }), /***/ 99893: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UnparsableRequirementError = exports.RequiredPackagesMissingError = exports.EmptyManifestError = exports.PythonPluginErrorNames = void 0; var PythonPluginErrorNames; (function (PythonPluginErrorNames) { PythonPluginErrorNames["EMPTY_MANIFEST_ERROR"] = "EMPTY_MANIFEST_ERROR"; PythonPluginErrorNames["REQUIRED_PACKAGES_MISSING_ERROR"] = "REQUIRED_PACKAGES_MISSING_ERROR"; PythonPluginErrorNames["UNPARSABLE_REQUIREMENT_ERROR"] = "UNPARSABLE_REQUIREMENT_ERROR"; })(PythonPluginErrorNames = exports.PythonPluginErrorNames || (exports.PythonPluginErrorNames = {})); class EmptyManifestError extends Error { constructor(message) { super(message); this.name = PythonPluginErrorNames.EMPTY_MANIFEST_ERROR; } } exports.EmptyManifestError = EmptyManifestError; class RequiredPackagesMissingError extends Error { constructor(message) { super(message); this.name = PythonPluginErrorNames.REQUIRED_PACKAGES_MISSING_ERROR; } } exports.RequiredPackagesMissingError = RequiredPackagesMissingError; class UnparsableRequirementError extends Error { constructor(message) { super(message); this.name = PythonPluginErrorNames.UNPARSABLE_REQUIREMENT_ERROR; } } exports.UnparsableRequirementError = UnparsableRequirementError; //# sourceMappingURL=errors.js.map /***/ }), /***/ 85054: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PythonPluginErrorNames = exports.RequiredPackagesMissingError = exports.EmptyManifestError = exports.inspect = void 0; var dependencies_1 = __webpack_require__(69797); Object.defineProperty(exports, "inspect", ({ enumerable: true, get: function () { return dependencies_1.getDependencies; } })); var errors_1 = __webpack_require__(99893); Object.defineProperty(exports, "EmptyManifestError", ({ enumerable: true, get: function () { return errors_1.EmptyManifestError; } })); Object.defineProperty(exports, "RequiredPackagesMissingError", ({ enumerable: true, get: function () { return errors_1.RequiredPackagesMissingError; } })); Object.defineProperty(exports, "PythonPluginErrorNames", ({ enumerable: true, get: function () { return errors_1.PythonPluginErrorNames; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 62914: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FILENAMES = void 0; exports.FILENAMES = { pip: { manifest: 'requirements.txt', }, setuptools: { manifest: 'setup.py', }, pipenv: { manifest: 'Pipfile', lockfile: 'Pipfile.lock', }, poetry: { manifest: 'pyproject.toml', lockfile: 'poetry.lock', }, }; //# sourceMappingURL=types.js.map /***/ }), /***/ 35041: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DepGraphBuilder = void 0; const graphlib = __webpack_require__(93220); const dep_graph_1 = __webpack_require__(93593); class DepGraphBuilder { constructor(pkgManager, rootPkg) { this._pkgs = {}; this._pkgNodes = {}; const graph = new graphlib.Graph({ directed: true, multigraph: false, compound: false, }); if (!rootPkg) { rootPkg = { name: '_root', version: '0.0.0', }; } this._rootNodeId = 'root-node'; this._rootPkgId = DepGraphBuilder._getPkgId(rootPkg); this._pkgs[this._rootPkgId] = rootPkg; graph.setNode(this._rootNodeId, { pkgId: this._rootPkgId }); this._pkgNodes[this._rootPkgId] = new Set([this._rootNodeId]); this._graph = graph; this._pkgManager = pkgManager; } get rootNodeId() { return this._rootNodeId; } static _getPkgId(pkg) { return `${pkg.name}@${pkg.version || ''}`; } getPkgs() { return Object.values(this._pkgs); } // TODO: this can create disconnected nodes addPkgNode(pkgInfo, nodeId, nodeInfo) { if (nodeId === this._rootNodeId) { throw new Error('DepGraphBuilder.addPkgNode() cant override root node'); } const pkgId = DepGraphBuilder._getPkgId(pkgInfo); this._pkgs[pkgId] = pkgInfo; this._pkgNodes[pkgId] = this._pkgNodes[pkgId] || new Set(); this._pkgNodes[pkgId].add(nodeId); this._graph.setNode(nodeId, { pkgId, info: nodeInfo }); return this; } // TODO: this can create cycles connectDep(parentNodeId, depNodeId) { if (!this._graph.hasNode(parentNodeId)) { throw new Error('parentNodeId does not exist'); } if (!this._graph.hasNode(depNodeId)) { throw new Error('depNodeId does not exist'); } this._graph.setEdge(parentNodeId, depNodeId); return this; } build() { return new dep_graph_1.DepGraphImpl(this._graph, this._rootNodeId, this._pkgs, this._pkgNodes, this._pkgManager); } } exports.DepGraphBuilder = DepGraphBuilder; //# sourceMappingURL=builder.js.map /***/ }), /***/ 55120: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createFromJSON = exports.SUPPORTED_SCHEMA_RANGE = void 0; const semver = __webpack_require__(73245); const graphlib = __webpack_require__(93220); const errors_1 = __webpack_require__(9965); const validate_graph_1 = __webpack_require__(47483); const dep_graph_1 = __webpack_require__(93593); exports.SUPPORTED_SCHEMA_RANGE = '^1.0.0'; /** * Create a DepGraph instance from a JSON representation of a dep graph. This * is typically used after passing the graph over the wire as `DepGraphData`. */ function createFromJSON(depGraphData) { validateDepGraphData(depGraphData); const graph = new graphlib.Graph({ directed: true, multigraph: false, compound: false, }); const pkgs = {}; const pkgNodes = {}; for (const { id, info } of depGraphData.pkgs) { pkgs[id] = info.version ? info : Object.assign(Object.assign({}, info), { version: undefined }); } for (const node of depGraphData.graph.nodes) { const pkgId = node.pkgId; if (!pkgNodes[pkgId]) { pkgNodes[pkgId] = new Set(); } pkgNodes[pkgId].add(node.nodeId); graph.setNode(node.nodeId, { pkgId, info: node.info }); } for (const node of depGraphData.graph.nodes) { for (const depNodeId of node.deps) { graph.setEdge(node.nodeId, depNodeId.nodeId); } } validate_graph_1.validateGraph(graph, depGraphData.graph.rootNodeId, pkgs, pkgNodes); return new dep_graph_1.DepGraphImpl(graph, depGraphData.graph.rootNodeId, pkgs, pkgNodes, depGraphData.pkgManager); } exports.createFromJSON = createFromJSON; function assert(condition, msg) { if (!condition) { throw new errors_1.ValidationError(msg); } } function validateDepGraphData(depGraphData) { assert(!!semver.valid(depGraphData.schemaVersion) && semver.satisfies(depGraphData.schemaVersion, exports.SUPPORTED_SCHEMA_RANGE), `dep-graph schemaVersion not in "${exports.SUPPORTED_SCHEMA_RANGE}"`); assert(depGraphData.pkgManager && !!depGraphData.pkgManager.name, '.pkgManager.name is missing'); const pkgsMap = depGraphData.pkgs.reduce((acc, cur) => { assert(!(cur.id in acc), 'more than one pkg with same id'); assert(!!cur.info, '.pkgs item missing .info'); acc[cur.id] = cur.info; return acc; }, {}); const nodesMap = depGraphData.graph.nodes.reduce((acc, cur) => { assert(!(cur.nodeId in acc), 'more than on node with same id'); acc[cur.nodeId] = cur; return acc; }, {}); const rootNodeId = depGraphData.graph.rootNodeId; const rootNode = nodesMap[rootNodeId]; assert(rootNodeId in nodesMap, `.${rootNodeId} root graph node is missing`); const rootPkgId = rootNode.pkgId; assert(rootPkgId in pkgsMap, `.${rootPkgId} root pkg missing`); assert(nodesMap[rootNodeId].pkgId === rootPkgId, `the root node .pkgId should be "${rootPkgId}"`); const pkgIds = Object.keys(pkgsMap); // NOTE: this name@version check is very strict, // we can relax it later, it just makes things easier now assert(pkgIds.filter((pkgId) => pkgId !== dep_graph_1.DepGraphImpl.getPkgId(pkgsMap[pkgId])) .length === 0, 'pkgs ids should be name@version'); assert(Object.values(nodesMap).filter((node) => !(node.pkgId in pkgsMap)) .length === 0, 'some instance nodes belong to non-existing pkgIds'); assert(Object.values(pkgsMap).filter((pkg) => !pkg.name) .length === 0, 'some .pkgs elements have no .name field'); } //# sourceMappingURL=create-from-json.js.map /***/ }), /***/ 93593: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DepGraphImpl = void 0; const _isEqual = __webpack_require__(72307); const graphlib = __webpack_require__(93220); const create_from_json_1 = __webpack_require__(55120); class DepGraphImpl { constructor(_graph, _rootNodeId, _pkgs, _pkgNodes, _pkgManager) { this._graph = _graph; this._rootNodeId = _rootNodeId; this._pkgs = _pkgs; this._pkgNodes = _pkgNodes; this._pkgManager = _pkgManager; this._countNodePathsToRootCache = new Map(); this._rootPkgId = _graph.node(_rootNodeId).pkgId; this._pkgList = Object.values(_pkgs); this._depPkgsList = this._pkgList.filter((pkg) => pkg !== this.rootPkg); } static getPkgId(pkg) { return `${pkg.name}@${pkg.version || ''}`; } get pkgManager() { return this._pkgManager; } get rootPkg() { return this._pkgs[this._rootPkgId]; } get rootNodeId() { return this._rootNodeId; } /** * Get all unique packages in the graph (including the root package) */ getPkgs() { return this._pkgList; } /** * Get all unique packages in the graph (excluding the root package) */ getDepPkgs() { return this._depPkgsList; } getPkgNodes(pkg) { const pkgId = DepGraphImpl.getPkgId(pkg); const nodes = []; for (const nodeId of Array.from(this._pkgNodes[pkgId])) { const graphNode = this.getGraphNode(nodeId); nodes.push({ info: graphNode.info || {}, }); } return nodes; } getNode(nodeId) { return this.getGraphNode(nodeId).info || {}; } getNodePkg(nodeId) { return this._pkgs[this.getGraphNode(nodeId).pkgId]; } getPkgNodeIds(pkg) { const pkgId = DepGraphImpl.getPkgId(pkg); if (!this._pkgs[pkgId]) { throw new Error(`no such pkg: ${pkgId}`); } return Array.from(this._pkgNodes[pkgId]); } getNodeDepsNodeIds(nodeId) { const deps = this._graph.successors(nodeId); if (!deps) { throw new Error(`no such node: ${nodeId}`); } return deps; } getNodeParentsNodeIds(nodeId) { const parents = this._graph.predecessors(nodeId); if (!parents) { throw new Error(`no such node: ${nodeId}`); } return parents; } hasCycles() { // `isAcyclic` is expensive, so memoize if (this._hasCycles === undefined) { this._hasCycles = !graphlib.alg.isAcyclic(this._graph); } return this._hasCycles; } pkgPathsToRoot(pkg, opts) { const pathsToRoot = []; const limit = opts === null || opts === void 0 ? void 0 : opts.limit; for (const nodeId of this.getPkgNodeIds(pkg)) { const pathsFromNodeToRoot = this.pathsFromNodeToRoot(nodeId, [], { limit, }); for (const path of pathsFromNodeToRoot) { pathsToRoot.push(path); } if (limit && pathsToRoot.length >= limit) { break; } } // note: sorting to get shorter paths first - // it's nicer - and better resembles older behaviour return pathsToRoot.sort((a, b) => a.length - b.length); } countPathsToRoot(pkg) { let count = 0; for (const nodeId of this.getPkgNodeIds(pkg)) { count += this.countNodePathsToRoot(nodeId); } return count; } equals(other, { compareRoot = true } = {}) { let otherDepGraph; if (other instanceof DepGraphImpl) { otherDepGraph = other; } else { // At runtime theoretically we can have multiple versions of // @snyk/dep-graph. If "other" is not an instance of the same class it is // safer to rebuild it from JSON. otherDepGraph = create_from_json_1.createFromJSON(other.toJSON()); } // In theory, for the graphs created by standard means, `_.isEquals(this._data, otherDepGraph._data)` // should suffice, since node IDs will be generated in a predictable way. // However, there might be different versions of graph and inconsistencies // in the ordering of the arrays, so we perform a deep comparison. return this.nodeEquals(this, this.rootNodeId, otherDepGraph, otherDepGraph.rootNodeId, compareRoot); } directDepsLeadingTo(pkg) { const pkgNodes = this.getPkgNodeIds(pkg); const directDeps = this.getNodeDepsNodeIds(this.rootNodeId); const nodes = directDeps.filter((directDep) => { const reachableNodes = graphlib.alg.postorder(this._graph, [directDep]); return reachableNodes.filter((node) => pkgNodes.includes(node)).length; }); return nodes.map((node) => this.getNodePkg(node)); } /** * Create a JSON representation of a dep graph. This is typically used to * send the dep graph over the wire */ toJSON() { const nodeIds = this._graph.nodes(); const nodes = nodeIds.reduce((acc, nodeId) => { const deps = (this._graph.successors(nodeId) || []).map((depNodeId) => ({ nodeId: depNodeId, })); const node = this._graph.node(nodeId); const elem = { nodeId, pkgId: node.pkgId, deps, }; if (node.info && Object.keys(node.info).length > 0) { elem.info = node.info; } acc.push(elem); return acc; }, []); const pkgs = Object.keys(this._pkgs).map((pkgId) => ({ id: pkgId, info: this._pkgs[pkgId], })); return { schemaVersion: DepGraphImpl.SCHEMA_VERSION, pkgManager: this._pkgManager, pkgs, graph: { rootNodeId: this._rootNodeId, nodes, }, }; } nodeEquals(graphA, nodeIdA, graphB, nodeIdB, compareRoot, traversedPairs = new Set()) { // Skip root nodes comparision if needed. if (compareRoot || (nodeIdA !== graphA.rootNodeId && nodeIdB !== graphB.rootNodeId)) { const pkgA = graphA.getNodePkg(nodeIdA); const pkgB = graphB.getNodePkg(nodeIdB); // Compare PkgInfo (name and version). if (!_isEqual(pkgA, pkgB)) { return false; } const infoA = graphA.getNode(nodeIdA); const infoB = graphB.getNode(nodeIdB); // Compare NodeInfo (VersionProvenance and labels). if (!_isEqual(infoA, infoB)) { return false; } } let depsA = graphA.getNodeDepsNodeIds(nodeIdA); let depsB = graphB.getNodeDepsNodeIds(nodeIdB); // Number of dependencies should be the same. if (depsA.length !== depsB.length) { return false; } // Sort dependencies by name@version string. const sortFn = (graph) => (idA, idB) => { const pkgA = graph.getNodePkg(idA); const pkgB = graph.getNodePkg(idB); return DepGraphImpl.getPkgId(pkgA).localeCompare(DepGraphImpl.getPkgId(pkgB)); }; depsA = depsA.sort(sortFn(graphA)); depsB = depsB.sort(sortFn(graphB)); // Compare Each dependency recursively. for (let i = 0; i < depsA.length; i++) { const pairKey = `${depsA[i]}_${depsB[i]}`; // Prevent cycles. if (traversedPairs.has(pairKey)) { continue; } traversedPairs.add(pairKey); if (!this.nodeEquals(graphA, depsA[i], graphB, depsB[i], compareRoot, traversedPairs)) { return false; } } return true; } getGraphNode(nodeId) { const node = this._graph.node(nodeId); if (!node) { throw new Error(`no such node: ${nodeId}`); } return node; } pathsFromNodeToRoot(nodeId, ancestors = [], opts) { const parentNodesIds = this.getNodeParentsNodeIds(nodeId); const pkgInfo = this.getNodePkg(nodeId); if (parentNodesIds.length === 0) { return [[pkgInfo]]; } const allPaths = []; ancestors = ancestors.concat(nodeId); const limit = opts.limit; for (const id of parentNodesIds) { if (ancestors.includes(id)) continue; const pathsFromNodeToRoot = this.pathsFromNodeToRoot(id, ancestors, opts); pathsFromNodeToRoot.forEach((path) => allPaths.push([pkgInfo].concat(path))); if (limit && allPaths.length >= limit) { break; } } return allPaths; } countNodePathsToRoot(nodeId, ancestors = []) { if (ancestors.includes(nodeId)) { return 0; } if (this._countNodePathsToRootCache.has(nodeId)) { return this._countNodePathsToRootCache.get(nodeId) || 0; } const parentNodesIds = this.getNodeParentsNodeIds(nodeId); if (parentNodesIds.length === 0) { this._countNodePathsToRootCache.set(nodeId, 1); return 1; } ancestors = ancestors.concat(nodeId); const count = parentNodesIds.reduce((acc, parentNodeId) => { return acc + this.countNodePathsToRoot(parentNodeId, ancestors); }, 0); this._countNodePathsToRootCache.set(nodeId, count); return count; } } exports.DepGraphImpl = DepGraphImpl; DepGraphImpl.SCHEMA_VERSION = '1.2.0'; //# sourceMappingURL=dep-graph.js.map /***/ }), /***/ 31965: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CustomError = void 0; class CustomError extends Error { constructor(message) { super(message); Object.setPrototypeOf(this, CustomError.prototype); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; } } exports.CustomError = CustomError; //# sourceMappingURL=custom-error.js.map /***/ }), /***/ 9965: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ValidationError = void 0; const validation_error_1 = __webpack_require__(1930); Object.defineProperty(exports, "ValidationError", ({ enumerable: true, get: function () { return validation_error_1.ValidationError; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 1930: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ValidationError = void 0; const custom_error_1 = __webpack_require__(31965); class ValidationError extends custom_error_1.CustomError { constructor(message) { super(message); Object.setPrototypeOf(this, ValidationError.prototype); } } exports.ValidationError = ValidationError; //# sourceMappingURL=validation-error.js.map /***/ }), /***/ 47483: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.validateGraph = void 0; const graphlib = __webpack_require__(93220); const errors_1 = __webpack_require__(9965); function assert(condition, msg) { if (!condition) { throw new errors_1.ValidationError(msg); } } function validateGraph(graph, rootNodeId, pkgs, pkgNodes) { assert((graph.predecessors(rootNodeId) || []).length === 0, `"${rootNodeId}" is not really the root`); const reachableFromRoot = graphlib.alg.postorder(graph, [rootNodeId]); const nodeIds = graph.nodes(); assert(JSON.stringify(nodeIds.sort()) === JSON.stringify(reachableFromRoot.sort()), 'not all graph nodes are reachable from root'); const pkgIds = Object.keys(pkgs); const pkgsWithoutInstances = pkgIds.filter((pkgId) => !pkgNodes[pkgId] || pkgNodes[pkgId].size === 0); assert(pkgsWithoutInstances.length === 0, 'not all pkgs have instance nodes'); } exports.validateGraph = validateGraph; //# sourceMappingURL=validate-graph.js.map /***/ }), /***/ 39600: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.dfs = void 0; const each = __webpack_require__(43590); /* * A helper that preforms a pre- or post-order traversal on the input graph * and returns the nodes in the order they were visited. If the graph is * undirected then this algorithm will navigate using neighbors. If the graph * is directed then this algorithm will navigate using successors. * * Order must be one of "pre" or "post". */ function dfs(g, vs, order) { if (!Array.isArray(vs)) { vs = [vs]; } const navigation = (g.isDirected() ? g.successors : g.neighbors).bind(g); const acc = []; const visited = {}; each(vs, (v) => { if (!g.hasNode(v)) { throw new Error('Graph does not have node: ' + v); } doDfs(g, v, order === 'post', visited, navigation, acc); }); return acc; } exports.dfs = dfs; function doDfs(g, v, postorder, visited, navigation, acc) { if (!(v in visited)) { visited[v] = true; if (!postorder) { acc.push(v); } each(navigation(v), function (w) { doDfs(g, w, postorder, visited, navigation, acc); }); if (postorder) { acc.push(v); } } } //# sourceMappingURL=dfs.js.map /***/ }), /***/ 7356: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isAcyclic = void 0; const topsort_1 = __webpack_require__(12003); function isAcyclic(g) { try { topsort_1.topsort(g); } catch (e) { if (e instanceof topsort_1.CycleException) { return false; } throw e; } return true; } exports.isAcyclic = isAcyclic; //# sourceMappingURL=is-acyclic.js.map /***/ }), /***/ 22644: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.postorder = void 0; const dfs_1 = __webpack_require__(39600); function postorder(g, vs) { return dfs_1.dfs(g, vs, 'post'); } exports.postorder = postorder; //# sourceMappingURL=postorder.js.map /***/ }), /***/ 12003: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CycleException = exports.topsort = void 0; const each = __webpack_require__(43590); const size = __webpack_require__(27946); function topsort(g) { const visited = {}; const stack = {}; const results = []; function visit(node) { if (node in stack) { throw new CycleException(); } if (!(node in visited)) { stack[node] = true; visited[node] = true; each(g.predecessors(node), visit); delete stack[node]; results.push(node); } } each(g.sinks(), visit); if (size(visited) !== g.nodeCount()) { throw new CycleException(); } return results; } exports.topsort = topsort; class CycleException extends Error { } exports.CycleException = CycleException; //# sourceMappingURL=topsort.js.map /***/ }), /***/ 61913: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Graph = void 0; /* eslint-disable prefer-rest-params */ /* eslint-disable @typescript-eslint/no-this-alias */ const constant = __webpack_require__(4254); const each = __webpack_require__(43590); const _filter = __webpack_require__(43590); const isEmpty = __webpack_require__(99245); const isFunction = __webpack_require__(98423); const isUndefined = __webpack_require__(28801); const keys = __webpack_require__(44799); const reduce = __webpack_require__(34766); const union = __webpack_require__(96744); const values = __webpack_require__(17720); const DEFAULT_EDGE_NAME = '\x00'; const GRAPH_NODE = '\x00'; const EDGE_KEY_DELIM = '\x01'; // Implementation notes: // // * Node id query functions should return string ids for the nodes // * Edge id query functions should return an "edgeObj", edge object, that is // composed of enough information to uniquely identify an edge: {v, w, name}. // * Internally we use an "edgeId", a stringified form of the edgeObj, to // reference edges. This is because we need a performant way to look these // edges up and, object properties, which have string keys, are the closest // we're going to get to a performant hashtable in JavaScript. class Graph { constructor(opts) { var _a, _b, _c; /* Number of nodes in the graph. Should only be changed by the implementation. */ this._nodeCount = 0; /* Number of edges in the graph. Should only be changed by the implementation. */ this._edgeCount = 0; this._isDirected = (_a = opts === null || opts === void 0 ? void 0 : opts.directed) !== null && _a !== void 0 ? _a : true; this._isMultigraph = (_b = opts === null || opts === void 0 ? void 0 : opts.multigraph) !== null && _b !== void 0 ? _b : false; this._isCompound = (_c = opts === null || opts === void 0 ? void 0 : opts.compound) !== null && _c !== void 0 ? _c : false; // Label for the graph itself this._label = undefined; // Defaults to be set when creating a new node this._defaultNodeLabelFn = constant(undefined); // Defaults to be set when creating a new edge this._defaultEdgeLabelFn = constant(undefined); // v -> label this._nodes = {}; if (this._isCompound) { // v -> parent this._parent = {}; // v -> children this._children = {}; this._children[GRAPH_NODE] = {}; } // v -> edgeObj this._in = {}; // u -> v -> Number this._preds = {}; // v -> edgeObj this._out = {}; // v -> w -> Number this._sucs = {}; // e -> edgeObj this._edgeObjs = {}; // e -> label this._edgeLabels = {}; } /* === Graph functions ========= */ isDirected() { return this._isDirected; } isMultigraph() { return this._isMultigraph; } isCompound() { return this._isCompound; } setGraph(label) { this._label = label; return this; } graph() { return this._label; } /* === Node functions ========== */ setDefaultNodeLabel(newDefault) { if (!isFunction(newDefault)) { newDefault = constant(newDefault); } this._defaultNodeLabelFn = newDefault; return this; } nodeCount() { return this._nodeCount; } nodes() { return keys(this._nodes); } sources() { const self = this; return _filter(this.nodes(), function (v) { return isEmpty(self._in[v]); }); } sinks() { const self = this; return _filter(this.nodes(), function (v) { return isEmpty(self._out[v]); }); } setNodes(vs, value) { const args = arguments; const self = this; each(vs, function (v) { if (args.length > 1) { self.setNode(v, value); } else { self.setNode(v); } }); return this; } setNode(v, value) { if (v in this._nodes) { if (arguments.length > 1) { this._nodes[v] = value; } return this; } this._nodes[v] = arguments.length > 1 ? value : this._defaultNodeLabelFn(v); if (this._isCompound) { this._parent[v] = GRAPH_NODE; this._children[v] = {}; this._children[GRAPH_NODE][v] = true; } this._in[v] = {}; this._preds[v] = {}; this._out[v] = {}; this._sucs[v] = {}; ++this._nodeCount; return this; } node(v) { return this._nodes[v]; } hasNode(v) { return v in this._nodes; } removeNode(v) { const self = this; if (v in this._nodes) { const removeEdge = function (e) { self.removeEdge(self._edgeObjs[e]); }; delete this._nodes[v]; if (this._isCompound) { this._removeFromParentsChildList(v); delete this._parent[v]; each(this.children(v), function (child) { self.setParent(child); }); delete this._children[v]; } each(keys(this._in[v]), removeEdge); delete this._in[v]; delete this._preds[v]; each(keys(this._out[v]), removeEdge); delete this._out[v]; delete this._sucs[v]; --this._nodeCount; } return this; } setParent(v, parent) { if (!this._isCompound) { throw new Error('Cannot set parent in a non-compound graph'); } if (isUndefined(parent)) { parent = GRAPH_NODE; } else { // Coerce parent to string parent += ''; for (let ancestor = parent; !isUndefined(ancestor); ancestor = this.parent(ancestor)) { if (ancestor === v) { throw new Error('Setting ' + parent + ' as parent of ' + v + ' would create a cycle'); } } this.setNode(parent); } this.setNode(v); this._removeFromParentsChildList(v); this._parent[v] = parent; this._children[parent][v] = true; return this; } _removeFromParentsChildList(v) { delete this._children[this._parent[v]][v]; } parent(v) { if (this._isCompound) { const parent = this._parent[v]; if (parent !== GRAPH_NODE) { return parent; } } } children(v) { if (isUndefined(v)) { v = GRAPH_NODE; } if (this._isCompound) { const children = this._children[v]; if (children) { return keys(children); } } else if (v === GRAPH_NODE) { return this.nodes(); } else if (this.hasNode(v)) { return []; } } predecessors(v) { const predsV = this._preds[v]; if (predsV) { return keys(predsV); } } successors(v) { const sucsV = this._sucs[v]; if (sucsV) { return keys(sucsV); } } neighbors(v) { const preds = this.predecessors(v); if (preds) { return union(preds, this.successors(v)); } } isLeaf(v) { let neighbors; if (this.isDirected()) { neighbors = this.successors(v); } else { neighbors = this.neighbors(v); } return neighbors.length === 0; } filterNodes(filter) { const copy = new Graph({ directed: this._isDirected, multigraph: this._isMultigraph, compound: this._isCompound, }); copy.setGraph(this.graph()); const self = this; each(this._nodes, function (value, v) { if (filter(v)) { copy.setNode(v, value); } }); each(this._edgeObjs, function (e) { if (copy.hasNode(e.v) && copy.hasNode(e.w)) { copy.setEdge(e, self.edge(e)); } }); const parents = {}; function findParent(v) { const parent = self.parent(v); if (parent === undefined || copy.hasNode(parent)) { parents[v] = parent; return parent; } else if (parent in parents) { return parents[parent]; } else { return findParent(parent); } } if (this._isCompound) { each(copy.nodes(), function (v) { copy.setParent(v, findParent(v)); }); } return copy; } /* === Edge functions ========== */ setDefaultEdgeLabel(newDefault) { if (!isFunction(newDefault)) { newDefault = constant(newDefault); } this._defaultEdgeLabelFn = newDefault; return this; } edgeCount() { return this._edgeCount; } edges() { return values(this._edgeObjs); } setPath(vs, value) { const self = this; const args = arguments; reduce(vs, function (v, w) { if (args.length > 1) { self.setEdge(v, w, value); } else { self.setEdge(v, w); } return w; }); return this; } // eslint-disable-next-line @typescript-eslint/no-unused-vars setEdge(...args) { let v, w, name, value; let valueSpecified = false; const arg0 = arguments[0]; if (typeof arg0 === 'object' && arg0 !== null && 'v' in arg0) { v = arg0.v; w = arg0.w; name = arg0.name; if (arguments.length === 2) { value = arguments[1]; valueSpecified = true; } } else { v = arg0; w = arguments[1]; name = arguments[3]; if (arguments.length > 2) { value = arguments[2]; valueSpecified = true; } } v = '' + v; w = '' + w; if (!isUndefined(name)) { name = '' + name; } const e = edgeArgsToId(this._isDirected, v, w, name); if (e in this._edgeLabels) { if (valueSpecified) { this._edgeLabels[e] = value; } return this; } if (!isUndefined(name) && !this._isMultigraph) { throw new Error('Cannot set a named edge when isMultigraph = false'); } // It didn't exist, so we need to create it. // First ensure the nodes exist. this.setNode(v); this.setNode(w); this._edgeLabels[e] = valueSpecified ? value : this._defaultEdgeLabelFn(v, w, name); const edgeObj = edgeArgsToObj(this._isDirected, v, w, name); // Ensure we add undirected edges in a consistent way. v = edgeObj.v; w = edgeObj.w; Object.freeze(edgeObj); this._edgeObjs[e] = edgeObj; incrementOrInitEntry(this._preds[w], v); incrementOrInitEntry(this._sucs[v], w); this._in[w][e] = edgeObj; this._out[v][e] = edgeObj; this._edgeCount++; return this; } edge(v, w, name) { const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); return this._edgeLabels[e]; } hasEdge(v, w, name) { const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); return e in this._edgeLabels; } removeEdge(v, w, name) { const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); const edge = this._edgeObjs[e]; if (edge) { v = edge.v; w = edge.w; delete this._edgeLabels[e]; delete this._edgeObjs[e]; decrementOrRemoveEntry(this._preds[w], v); decrementOrRemoveEntry(this._sucs[v], w); delete this._in[w][e]; delete this._out[v][e]; this._edgeCount--; } return this; } inEdges(v, u) { const inV = this._in[v]; if (inV) { const edges = values(inV); if (!u) { return edges; } return _filter(edges, function (edge) { return edge.v === u; }); } } outEdges(v, w) { const outV = this._out[v]; if (outV) { const edges = values(outV); if (!w) { return edges; } return _filter(edges, function (edge) { return edge.w === w; }); } } nodeEdges(v, w) { const inEdges = this.inEdges(v, w); if (inEdges) { return inEdges.concat(this.outEdges(v, w)); } } } exports.Graph = Graph; function incrementOrInitEntry(map, k) { if (map[k]) { map[k]++; } else { map[k] = 1; } } function decrementOrRemoveEntry(map, k) { if (!--map[k]) { delete map[k]; } } function edgeArgsToId(isDirected, v_, w_, name) { let v = '' + v_; let w = '' + w_; if (!isDirected && v > w) { const tmp = v; v = w; w = tmp; } return (v + EDGE_KEY_DELIM + w + EDGE_KEY_DELIM + (isUndefined(name) ? DEFAULT_EDGE_NAME : name)); } function edgeArgsToObj(isDirected, v_, w_, name) { let v = '' + v_; let w = '' + w_; if (!isDirected && v > w) { const tmp = v; v = w; w = tmp; } const edgeObj = { v: v, w: w }; if (name) { edgeObj.name = name; } return edgeObj; } function edgeObjToId(isDirected, edgeObj) { return edgeArgsToId(isDirected, edgeObj.v, edgeObj.w, edgeObj.name); } //# sourceMappingURL=graph.js.map /***/ }), /***/ 93220: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.alg = exports.Graph = void 0; var graph_1 = __webpack_require__(61913); Object.defineProperty(exports, "Graph", ({ enumerable: true, get: function () { return graph_1.Graph; } })); const is_acyclic_1 = __webpack_require__(7356); const postorder_1 = __webpack_require__(22644); exports.alg = { isAcyclic: is_acyclic_1.isAcyclic, postorder: postorder_1.postorder, }; //# sourceMappingURL=index.js.map /***/ }), /***/ 15162: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.partitionCycles = exports.getCycle = void 0; function getCycle(ancestors, nodeId) { if (!ancestors.includes(nodeId)) { return null; } // first item is where the cycle starts and ends. return ancestors.slice(ancestors.indexOf(nodeId)); } exports.getCycle = getCycle; function partitionCycles(nodeId, allCyclesTheNodeIsPartOf) { const cyclesStartWithThisNode = []; const cyclesWithThisNode = []; for (const cycle of allCyclesTheNodeIsPartOf) { const nodeStartsCycle = cycle[0] === nodeId; if (nodeStartsCycle) { cyclesStartWithThisNode.push(cycle); } else { cyclesWithThisNode.push(cycle); } } return { cyclesStartWithThisNode, cyclesWithThisNode }; } exports.partitionCycles = partitionCycles; //# sourceMappingURL=cycles.js.map /***/ }), /***/ 51731: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.graphToDepTree = exports.depTreeToGraph = void 0; const crypto = __webpack_require__(6113); const event_loop_spinner_1 = __webpack_require__(77158); const builder_1 = __webpack_require__(35041); const objectHash = __webpack_require__(92855); const cycles_1 = __webpack_require__(15162); const memiozation_1 = __webpack_require__(30699); function addLabel(dep, key, value) { if (!dep.labels) { dep.labels = {}; } dep.labels[key] = value; } /** * @deprecated Don't use dep trees as an intermediate step, because they are * large structures, resulting in high memory usage and high CPU costs from * serializing / deserializing. Instead, create a graph directly with * {@link DepGraphBuilder} */ async function depTreeToGraph(depTree, pkgManagerName) { const rootPkg = { name: depTree.name, version: depTree.version || undefined, }; const pkgManagerInfo = { name: pkgManagerName, }; const targetOS = depTree.targetOS; if (targetOS) { pkgManagerInfo.repositories = [ { alias: `${targetOS.name}:${targetOS.version}`, }, ]; } const builder = new builder_1.DepGraphBuilder(pkgManagerInfo, rootPkg); await buildGraph(builder, depTree, depTree.name, true); const depGraph = await builder.build(); return shortenNodeIds(depGraph); } exports.depTreeToGraph = depTreeToGraph; async function buildGraph(builder, depTree, pkgName, isRoot = false, memoizationMap = new Map()) { if (memoizationMap.has(depTree)) { return memoizationMap.get(depTree); } const getNodeId = (name, version, hashId) => `${name}@${version || ''}|${hashId}`; const depNodesIds = []; const hash = crypto.createHash('sha1'); if (depTree.versionProvenance) { hash.update(objectHash(depTree.versionProvenance)); } if (depTree.labels) { hash.update(objectHash(depTree.labels)); } const deps = depTree.dependencies || {}; // filter-out invalid null deps (shouldn't happen - but did...) const depNames = Object.keys(deps).filter((d) => !!deps[d]); for (const depName of depNames.sort()) { const dep = deps[depName]; const subtreeHash = await buildGraph(builder, dep, depName, false, memoizationMap); const depPkg = { name: depName, version: dep.version, }; const depNodeId = getNodeId(depPkg.name, depPkg.version, subtreeHash); depNodesIds.push(depNodeId); const nodeInfo = {}; if (dep.versionProvenance) { nodeInfo.versionProvenance = dep.versionProvenance; } if (dep.labels) { nodeInfo.labels = dep.labels; } builder.addPkgNode(depPkg, depNodeId, nodeInfo); hash.update(depNodeId); } const treeHash = hash.digest('hex'); let pkgNodeId; if (isRoot) { pkgNodeId = builder.rootNodeId; } else { // we don't assume depTree has a .name to support output of `npm list --json` const pkg = { name: pkgName, version: depTree.version, }; pkgNodeId = getNodeId(pkg.name, pkg.version, treeHash); const nodeInfo = {}; if (depTree.versionProvenance) { nodeInfo.versionProvenance = depTree.versionProvenance; } if (depTree.labels) { nodeInfo.labels = depTree.labels; } builder.addPkgNode(pkg, pkgNodeId, nodeInfo); } for (const depNodeId of depNodesIds) { builder.connectDep(pkgNodeId, depNodeId); } if (depNodesIds.length > 0 && event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } memoizationMap.set(depTree, treeHash); return treeHash; } async function shortenNodeIds(depGraph) { const builder = new builder_1.DepGraphBuilder(depGraph.pkgManager, depGraph.rootPkg); const nodesMap = {}; // create nodes with shorter ids for (const pkg of depGraph.getPkgs()) { const nodeIds = depGraph.getPkgNodeIds(pkg); for (let i = 0; i < nodeIds.length; i++) { const nodeId = nodeIds[i]; if (nodeId === depGraph.rootNodeId) { continue; } const nodeInfo = depGraph.getNode(nodeId); let newNodeId; if (nodeIds.length === 1) { newNodeId = `${trimAfterLastSep(nodeId, '|')}`; } else { newNodeId = `${trimAfterLastSep(nodeId, '|')}|${i + 1}`; } nodesMap[nodeId] = newNodeId; builder.addPkgNode(pkg, newNodeId, nodeInfo); } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } // connect nodes for (const pkg of depGraph.getPkgs()) { for (const nodeId of depGraph.getPkgNodeIds(pkg)) { for (const depNodeId of depGraph.getNodeDepsNodeIds(nodeId)) { const parentNode = nodesMap[nodeId] || nodeId; const childNode = nodesMap[depNodeId] || depNodeId; builder.connectDep(parentNode, childNode); } } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } } return builder.build(); } /** * @deprecated Don't use dep trees. You should adapt your code to use graphs, * and enhance the dep-graph library if there is missing functionality from * the graph structure */ async function graphToDepTree(depGraphInterface, pkgType, opts = { deduplicateWithinTopLevelDeps: false }) { const depGraph = depGraphInterface; const [depTree] = await buildSubtree(depGraph, depGraph.rootNodeId, opts.deduplicateWithinTopLevelDeps ? null : false); depTree.type = depGraph.pkgManager.name; depTree.packageFormatVersion = constructPackageFormatVersion(pkgType); const targetOS = constructTargetOS(depGraph); if (targetOS) { depTree.targetOS = targetOS; } return depTree; } exports.graphToDepTree = graphToDepTree; function constructPackageFormatVersion(pkgType) { if (pkgType === 'maven') { pkgType = 'mvn'; } return `${pkgType}:0.0.1`; } function constructTargetOS(depGraph) { if (['apk', 'apt', 'deb', 'rpm', 'linux'].indexOf(depGraph.pkgManager.name) === -1) { // .targetOS is undefined unless its a linux pkgManager return; } if (!depGraph.pkgManager.repositories || !depGraph.pkgManager.repositories.length || !depGraph.pkgManager.repositories[0].alias) { throw new Error('Incomplete .pkgManager, could not create .targetOS'); } const [name, version] = depGraph.pkgManager.repositories[0].alias.split(':'); return { name, version }; } async function buildSubtree(depGraph, nodeId, maybeDeduplicationSet = false, // false = disabled; null = not in deduplication scope yet ancestors = [], memoizationMap = new Map()) { if (!maybeDeduplicationSet) { const memoizedDepTree = memiozation_1.getMemoizedDepTree(nodeId, ancestors, memoizationMap); if (memoizedDepTree) { return [memoizedDepTree, undefined]; } } const isRoot = nodeId === depGraph.rootNodeId; const nodePkg = depGraph.getNodePkg(nodeId); const nodeInfo = depGraph.getNode(nodeId); const depTree = {}; depTree.name = nodePkg.name; depTree.version = nodePkg.version; if (nodeInfo.versionProvenance) { depTree.versionProvenance = nodeInfo.versionProvenance; } if (nodeInfo.labels) { depTree.labels = Object.assign({}, nodeInfo.labels); } const depInstanceIds = depGraph.getNodeDepsNodeIds(nodeId); if (!depInstanceIds || depInstanceIds.length === 0) { memoizationMap.set(nodeId, { depTree }); return [depTree, undefined]; } const cycle = cycles_1.getCycle(ancestors, nodeId); if (cycle) { // This node starts a cycle and now it's the second visit. addLabel(depTree, 'pruned', 'cyclic'); return [depTree, [cycle]]; } if (maybeDeduplicationSet) { if (maybeDeduplicationSet.has(nodeId)) { if (depInstanceIds.length > 0) { addLabel(depTree, 'pruned', 'true'); } return [depTree, undefined]; } maybeDeduplicationSet.add(nodeId); } const cycles = []; for (const depInstId of depInstanceIds) { // Deduplication of nodes occurs only within a scope of a top-level dependency. // Therefore, every top-level dep gets an independent set to track duplicates. if (isRoot && maybeDeduplicationSet !== false) { maybeDeduplicationSet = new Set(); } const [subtree, subtreeCycles] = await buildSubtree(depGraph, depInstId, maybeDeduplicationSet, ancestors.concat(nodeId), memoizationMap); if (subtreeCycles) { for (const cycle of subtreeCycles) { cycles.push(cycle); } } if (!subtree) { continue; } if (!depTree.dependencies) { depTree.dependencies = {}; } depTree.dependencies[subtree.name] = subtree; } if (event_loop_spinner_1.eventLoopSpinner.isStarving()) { await event_loop_spinner_1.eventLoopSpinner.spin(); } const partitionedCycles = cycles_1.partitionCycles(nodeId, cycles); memiozation_1.memoize(nodeId, memoizationMap, depTree, partitionedCycles); return [depTree, partitionedCycles.cyclesWithThisNode]; } function trimAfterLastSep(str, sep) { return str.slice(0, str.lastIndexOf(sep)); } //# sourceMappingURL=index.js.map /***/ }), /***/ 30699: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getMemoizedDepTree = exports.memoize = void 0; function memoize(nodeId, memoizationMap, depTree, partitionedCycles) { const { cyclesStartWithThisNode, cyclesWithThisNode } = partitionedCycles; if (cyclesStartWithThisNode.length > 0) { const cycleNodeIds = new Set(...cyclesStartWithThisNode); memoizationMap.set(nodeId, { depTree, cycleNodeIds }); } else if (cyclesWithThisNode.length === 0) { memoizationMap.set(nodeId, { depTree }); } // Don't memoize nodes in cycles (cyclesWithThisNode.length > 0) } exports.memoize = memoize; function getMemoizedDepTree(nodeId, ancestors, memoizationMap) { if (!memoizationMap.has(nodeId)) return null; const { depTree, cycleNodeIds } = memoizationMap.get(nodeId); if (!cycleNodeIds) return depTree; const ancestorsArePartOfTheCycle = ancestors.some((nodeId) => cycleNodeIds.has(nodeId)); return ancestorsArePartOfTheCycle ? null : depTree; } exports.getMemoizedDepTree = getMemoizedDepTree; //# sourceMappingURL=memiozation.js.map /***/ }), /***/ 92855: /***/ ((module, exports, __webpack_require__) => { "use strict"; var crypto = __webpack_require__(6113); /** * Exported function * * Options: * * - `algorithm` hash algo to be used by this instance: *'sha1', 'md5' * - `excludeValues` {true|*false} hash object keys, values ignored * - `encoding` hash encoding, supports 'buffer', '*hex', 'binary', 'base64' * - `ignoreUnknown` {true|*false} ignore unknown object types * - `replacer` optional function that replaces values before hashing * - `respectFunctionProperties` {*true|false} consider function properties when hashing * - `respectFunctionNames` {*true|false} consider 'name' property of functions for hashing * - `respectType` {*true|false} Respect special properties (prototype, constructor) * when hashing to distinguish between types * - `unorderedArrays` {true|*false} Sort all arrays before hashing * - `unorderedSets` {*true|false} Sort `Set` and `Map` instances before hashing * * = default * * @param {object} object value to hash * @param {object} options hashing options * @return {string} hash value * @api public */ exports = module.exports = objectHash; function objectHash(object, options){ options = applyDefaults(object, options); return hash(object, options); } /** * Exported sugar methods * * @param {object} object value to hash * @return {string} hash value * @api public */ exports.sha1 = function(object){ return objectHash(object); }; exports.keys = function(object){ return objectHash(object, {excludeValues: true, algorithm: 'sha1', encoding: 'hex'}); }; exports.MD5 = function(object){ return objectHash(object, {algorithm: 'md5', encoding: 'hex'}); }; exports.keysMD5 = function(object){ return objectHash(object, {algorithm: 'md5', encoding: 'hex', excludeValues: true}); }; // Internals var hashes = crypto.getHashes ? crypto.getHashes().slice() : ['sha1', 'md5']; hashes.push('passthrough'); var encodings = ['buffer', 'hex', 'binary', 'base64']; function applyDefaults(object, sourceOptions){ sourceOptions = sourceOptions || {}; // create a copy rather than mutating var options = {}; options.algorithm = sourceOptions.algorithm || 'sha1'; options.encoding = sourceOptions.encoding || 'hex'; options.excludeValues = sourceOptions.excludeValues ? true : false; options.algorithm = options.algorithm.toLowerCase(); options.encoding = options.encoding.toLowerCase(); options.ignoreUnknown = sourceOptions.ignoreUnknown !== true ? false : true; // default to false options.respectType = sourceOptions.respectType === false ? false : true; // default to true options.respectFunctionNames = sourceOptions.respectFunctionNames === false ? false : true; options.respectFunctionProperties = sourceOptions.respectFunctionProperties === false ? false : true; options.unorderedArrays = sourceOptions.unorderedArrays !== true ? false : true; // default to false options.unorderedSets = sourceOptions.unorderedSets === false ? false : true; // default to false options.unorderedObjects = sourceOptions.unorderedObjects === false ? false : true; // default to true options.replacer = sourceOptions.replacer || undefined; options.excludeKeys = sourceOptions.excludeKeys || undefined; if(typeof object === 'undefined') { throw new Error('Object argument required.'); } // if there is a case-insensitive match in the hashes list, accept it // (i.e. SHA256 for sha256) for (var i = 0; i < hashes.length; ++i) { if (hashes[i].toLowerCase() === options.algorithm.toLowerCase()) { options.algorithm = hashes[i]; } } if(hashes.indexOf(options.algorithm) === -1){ throw new Error('Algorithm "' + options.algorithm + '" not supported. ' + 'supported values: ' + hashes.join(', ')); } if(encodings.indexOf(options.encoding) === -1 && options.algorithm !== 'passthrough'){ throw new Error('Encoding "' + options.encoding + '" not supported. ' + 'supported values: ' + encodings.join(', ')); } return options; } /** Check if the given function is a native function */ function isNativeFunction(f) { if ((typeof f) !== 'function') { return false; } var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i; return exp.exec(Function.prototype.toString.call(f)) != null; } function hash(object, options) { var hashingStream; if (options.algorithm !== 'passthrough') { hashingStream = crypto.createHash(options.algorithm); } else { hashingStream = new PassThrough(); } if (typeof hashingStream.write === 'undefined') { hashingStream.write = hashingStream.update; hashingStream.end = hashingStream.update; } var hasher = typeHasher(options, hashingStream); hasher.dispatch(object); if (!hashingStream.update) { hashingStream.end(''); } if (hashingStream.digest) { return hashingStream.digest(options.encoding === 'buffer' ? undefined : options.encoding); } var buf = hashingStream.read(); if (options.encoding === 'buffer') { return buf; } return buf.toString(options.encoding); } /** * Expose streaming API * * @param {object} object Value to serialize * @param {object} options Options, as for hash() * @param {object} stream A stream to write the serializiation to * @api public */ exports.writeToStream = function(object, options, stream) { if (typeof stream === 'undefined') { stream = options; options = {}; } options = applyDefaults(object, options); return typeHasher(options, stream).dispatch(object); }; function typeHasher(options, writeTo, context){ context = context || []; var write = function(str) { if (writeTo.update) { return writeTo.update(str, 'utf8'); } else { return writeTo.write(str, 'utf8'); } }; return { dispatch: function(value){ if (options.replacer) { value = options.replacer(value); } var type = typeof value; if (value === null) { type = 'null'; } //console.log("[DEBUG] Dispatch: ", value, "->", type, " -> ", "_" + type); return this['_' + type](value); }, _object: function(object) { var pattern = (/\[object (.*)\]/i); var objString = Object.prototype.toString.call(object); var objType = pattern.exec(objString); if (!objType) { // object type did not match [object ...] objType = 'unknown:[' + objString + ']'; } else { objType = objType[1]; // take only the class name } objType = objType.toLowerCase(); var objectNumber = null; if ((objectNumber = context.indexOf(object)) >= 0) { return this.dispatch('[CIRCULAR:' + objectNumber + ']'); } else { context.push(object); } if (typeof Buffer !== 'undefined' && Buffer.isBuffer && Buffer.isBuffer(object)) { write('buffer:'); return write(object); } if(objType !== 'object' && objType !== 'function' && objType !== 'asyncfunction') { if(this['_' + objType]) { this['_' + objType](object); } else if (options.ignoreUnknown) { return write('[' + objType + ']'); } else { throw new Error('Unknown object type "' + objType + '"'); } }else{ var keys = Object.keys(object); if (options.unorderedObjects) { keys = keys.sort(); } // Make sure to incorporate special properties, so // Types with different prototypes will produce // a different hash and objects derived from // different functions (`new Foo`, `new Bar`) will // produce different hashes. // We never do this for native functions since some // seem to break because of that. if (options.respectType !== false && !isNativeFunction(object)) { keys.splice(0, 0, 'prototype', '__proto__', 'constructor'); } if (options.excludeKeys) { keys = keys.filter(function(key) { return !options.excludeKeys(key); }); } write('object:' + keys.length + ':'); var self = this; return keys.forEach(function(key){ self.dispatch(key); write(':'); if(!options.excludeValues) { self.dispatch(object[key]); } write(','); }); } }, _array: function(arr, unordered){ unordered = typeof unordered !== 'undefined' ? unordered : options.unorderedArrays !== false; // default to options.unorderedArrays var self = this; write('array:' + arr.length + ':'); if (!unordered || arr.length <= 1) { return arr.forEach(function(entry) { return self.dispatch(entry); }); } // the unordered case is a little more complicated: // since there is no canonical ordering on objects, // i.e. {a:1} < {a:2} and {a:1} > {a:2} are both false, // we first serialize each entry using a PassThrough stream // before sorting. // also: we can’t use the same context array for all entries // since the order of hashing should *not* matter. instead, // we keep track of the additions to a copy of the context array // and add all of them to the global context array when we’re done var contextAdditions = []; var entries = arr.map(function(entry) { var strm = new PassThrough(); var localContext = context.slice(); // make copy var hasher = typeHasher(options, strm, localContext); hasher.dispatch(entry); // take only what was added to localContext and append it to contextAdditions contextAdditions = contextAdditions.concat(localContext.slice(context.length)); return strm.read().toString(); }); context = context.concat(contextAdditions); entries.sort(); return this._array(entries, false); }, _date: function(date){ return write('date:' + date.toJSON()); }, _symbol: function(sym){ return write('symbol:' + sym.toString()); }, _error: function(err){ return write('error:' + err.toString()); }, _boolean: function(bool){ return write('bool:' + bool.toString()); }, _string: function(string){ write('string:' + string.length + ':'); write(string.toString()); }, _function: function(fn){ write('fn:'); if (isNativeFunction(fn)) { this.dispatch('[native]'); } else { this.dispatch(fn.toString()); } if (options.respectFunctionNames !== false) { // Make sure we can still distinguish native functions // by their name, otherwise String and Function will // have the same hash this.dispatch("function-name:" + String(fn.name)); } if (options.respectFunctionProperties) { this._object(fn); } }, _number: function(number){ return write('number:' + number.toString()); }, _xml: function(xml){ return write('xml:' + xml.toString()); }, _null: function() { return write('Null'); }, _undefined: function() { return write('Undefined'); }, _regexp: function(regex){ return write('regex:' + regex.toString()); }, _uint8array: function(arr){ write('uint8array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _uint8clampedarray: function(arr){ write('uint8clampedarray:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _int8array: function(arr){ write('uint8array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _uint16array: function(arr){ write('uint16array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _int16array: function(arr){ write('uint16array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _uint32array: function(arr){ write('uint32array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _int32array: function(arr){ write('uint32array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _float32array: function(arr){ write('float32array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _float64array: function(arr){ write('float64array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _arraybuffer: function(arr){ write('arraybuffer:'); return this.dispatch(new Uint8Array(arr)); }, _url: function(url) { return write('url:' + url.toString(), 'utf8'); }, _map: function(map) { write('map:'); var arr = Array.from(map); return this._array(arr, options.unorderedSets !== false); }, _set: function(set) { write('set:'); var arr = Array.from(set); return this._array(arr, options.unorderedSets !== false); }, _file: function(file) { write('file:'); return this.dispatch([file.name, file.size, file.type, file.lastModfied]); }, _blob: function() { if (options.ignoreUnknown) { return write('[blob]'); } throw Error('Hashing Blob objects is currently not supported\n' + '(see https://github.com/puleos/object-hash/issues/26)\n' + 'Use "options.replacer" or "options.ignoreUnknown"\n'); }, _domwindow: function() { return write('domwindow'); }, _bigint: function(number){ return write('bigint:' + number.toString()); }, /* Node.js standard native objects */ _process: function() { return write('process'); }, _timer: function() { return write('timer'); }, _pipe: function() { return write('pipe'); }, _tcp: function() { return write('tcp'); }, _udp: function() { return write('udp'); }, _tty: function() { return write('tty'); }, _statwatcher: function() { return write('statwatcher'); }, _securecontext: function() { return write('securecontext'); }, _connection: function() { return write('connection'); }, _zlib: function() { return write('zlib'); }, _context: function() { return write('context'); }, _nodescript: function() { return write('nodescript'); }, _httpparser: function() { return write('httpparser'); }, _dataview: function() { return write('dataview'); }, _signal: function() { return write('signal'); }, _fsevent: function() { return write('fsevent'); }, _tlswrap: function() { return write('tlswrap'); }, }; } // Mini-implementation of stream.PassThrough // We are far from having need for the full implementation, and we can // make assumptions like "many writes, then only one final read" // and we can ignore encoding specifics function PassThrough() { return { buf: '', write: function(b) { this.buf += b; }, end: function(b) { this.buf += b; }, read: function() { return this.buf; } }; } /***/ }), /***/ 29973: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const ANY = Symbol('SemVer ANY') // hoisted class for cyclic dependency class Comparator { static get ANY () { return ANY } constructor (comp, options) { options = parseOptions(options) if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } comp = comp.trim().split(/\s+/).join(' ') debug('comparator', comp, options) this.options = options this.loose = !!options.loose this.parse(comp) if (this.semver === ANY) { this.value = '' } else { this.value = this.operator + this.semver.version } debug('comp', this) } parse (comp) { const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] const m = comp.match(r) if (!m) { throw new TypeError(`Invalid comparator: ${comp}`) } this.operator = m[1] !== undefined ? m[1] : '' if (this.operator === '=') { this.operator = '' } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY } else { this.semver = new SemVer(m[2], this.options.loose) } } toString () { return this.value } test (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY || version === ANY) { return true } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } return cmp(version, this.operator, this.semver, this.options) } intersects (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (this.operator === '') { if (this.value === '') { return true } return new Range(comp.value, options).test(this.value) } else if (comp.operator === '') { if (comp.value === '') { return true } return new Range(this.value, options).test(comp.semver) } options = parseOptions(options) // Special cases where nothing can possibly be lower if (options.includePrerelease && (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { return false } if (!options.includePrerelease && (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { return false } // Same direction increasing (> or >=) if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { return true } // Same direction decreasing (< or <=) if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { return true } // same SemVer and both sides are inclusive (<= or >=) if ( (this.semver.version === comp.semver.version) && this.operator.includes('=') && comp.operator.includes('=')) { return true } // opposite directions less than if (cmp(this.semver, '<', comp.semver, options) && this.operator.startsWith('>') && comp.operator.startsWith('<')) { return true } // opposite directions greater than if (cmp(this.semver, '>', comp.semver, options) && this.operator.startsWith('<') && comp.operator.startsWith('>')) { return true } return false } } module.exports = Comparator const parseOptions = __webpack_require__(13520) const { safeRe: re, t } = __webpack_require__(70823) const cmp = __webpack_require__(12498) const debug = __webpack_require__(717) const SemVer = __webpack_require__(94498) const Range = __webpack_require__(19032) /***/ }), /***/ 19032: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SPACE_CHARACTERS = /\s+/g // hoisted class for cyclic dependency class Range { constructor (range, options) { options = parseOptions(options) if (range instanceof Range) { if ( range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease ) { return range } else { return new Range(range.raw, options) } } if (range instanceof Comparator) { // just put it in the set and return this.raw = range.value this.set = [[range]] this.formatted = undefined return this } this.options = options this.loose = !!options.loose this.includePrerelease = !!options.includePrerelease // First reduce all whitespace as much as possible so we do not have to rely // on potentially slow regexes like \s*. This is then stored and used for // future error messages as well. this.raw = range.trim().replace(SPACE_CHARACTERS, ' ') // First, split on || this.set = this.raw .split('||') // map the range to a 2d array of comparators .map(r => this.parseRange(r.trim())) // throw out any comparator lists that are empty // this generally means that it was not a valid range, which is allowed // in loose mode, but will still throw if the WHOLE range is invalid. .filter(c => c.length) if (!this.set.length) { throw new TypeError(`Invalid SemVer Range: ${this.raw}`) } // if we have any that are not the null set, throw out null sets. if (this.set.length > 1) { // keep the first one, in case they're all null sets const first = this.set[0] this.set = this.set.filter(c => !isNullSet(c[0])) if (this.set.length === 0) { this.set = [first] } else if (this.set.length > 1) { // if we have any that are *, then the range is just * for (const c of this.set) { if (c.length === 1 && isAny(c[0])) { this.set = [c] break } } } } this.formatted = undefined } get range () { if (this.formatted === undefined) { this.formatted = '' for (let i = 0; i < this.set.length; i++) { if (i > 0) { this.formatted += '||' } const comps = this.set[i] for (let k = 0; k < comps.length; k++) { if (k > 0) { this.formatted += ' ' } this.formatted += comps[k].toString().trim() } } } return this.formatted } format () { return this.range } toString () { return this.range } parseRange (range) { // memoize range parsing for performance. // this is a very hot path, and fully deterministic. const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE) const memoKey = memoOpts + ':' + range const cached = cache.get(memoKey) if (cached) { return cached } const loose = this.options.loose // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range) // `~ 1.2.3` => `~1.2.3` range = range.replace(re[t.TILDETRIM], tildeTrimReplace) debug('tilde trim', range) // `^ 1.2.3` => `^1.2.3` range = range.replace(re[t.CARETTRIM], caretTrimReplace) debug('caret trim', range) // At this point, the range is completely trimmed and // ready to be split into comparators. let rangeList = range .split(' ') .map(comp => parseComparator(comp, this.options)) .join(' ') .split(/\s+/) // >=0.0.0 is equivalent to * .map(comp => replaceGTE0(comp, this.options)) if (loose) { // in loose mode, throw out any that are not valid comparators rangeList = rangeList.filter(comp => { debug('loose invalid filter', comp, this.options) return !!comp.match(re[t.COMPARATORLOOSE]) }) } debug('range list', rangeList) // if any comparators are the null set, then replace with JUST null set // if more than one comparator, remove any * comparators // also, don't include the same comparator more than once const rangeMap = new Map() const comparators = rangeList.map(comp => new Comparator(comp, this.options)) for (const comp of comparators) { if (isNullSet(comp)) { return [comp] } rangeMap.set(comp.value, comp) } if (rangeMap.size > 1 && rangeMap.has('')) { rangeMap.delete('') } const result = [...rangeMap.values()] cache.set(memoKey, result) return result } intersects (range, options) { if (!(range instanceof Range)) { throw new TypeError('a Range is required') } return this.set.some((thisComparators) => { return ( isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => { return ( isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { return rangeComparators.every((rangeComparator) => { return thisComparator.intersects(rangeComparator, options) }) }) ) }) ) }) } // if ANY of the sets match ALL of its comparators, then pass test (version) { if (!version) { return false } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } for (let i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true } } return false } } module.exports = Range const LRU = __webpack_require__(81790) const cache = new LRU() const parseOptions = __webpack_require__(13520) const Comparator = __webpack_require__(29973) const debug = __webpack_require__(717) const SemVer = __webpack_require__(94498) const { safeRe: re, t, comparatorTrimReplace, tildeTrimReplace, caretTrimReplace, } = __webpack_require__(70823) const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __webpack_require__(79573) const isNullSet = c => c.value === '<0.0.0-0' const isAny = c => c.value === '' // take a set of comparators and determine whether there // exists a version which can satisfy it const isSatisfiable = (comparators, options) => { let result = true const remainingComparators = comparators.slice() let testComparator = remainingComparators.pop() while (result && remainingComparators.length) { result = remainingComparators.every((otherComparator) => { return testComparator.intersects(otherComparator, options) }) testComparator = remainingComparators.pop() } return result } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. const parseComparator = (comp, options) => { debug('comp', comp, options) comp = replaceCarets(comp, options) debug('caret', comp) comp = replaceTildes(comp, options) debug('tildes', comp) comp = replaceXRanges(comp, options) debug('xrange', comp) comp = replaceStars(comp, options) debug('stars', comp) return comp } const isX = id => !id || id.toLowerCase() === 'x' || id === '*' // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 // ~0.0.1 --> >=0.0.1 <0.1.0-0 const replaceTildes = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceTilde(c, options)) .join(' ') } const replaceTilde = (comp, options) => { const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] return comp.replace(r, (_, M, m, p, pr) => { debug('tilde', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0 <${+M + 1}.0.0-0` } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0-0 ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` } else if (pr) { debug('replaceTilde pr', pr) ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } else { // ~1.2.3 == >=1.2.3 <1.3.0-0 ret = `>=${M}.${m}.${p } <${M}.${+m + 1}.0-0` } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 // ^1.2.3 --> >=1.2.3 <2.0.0-0 // ^1.2.0 --> >=1.2.0 <2.0.0-0 // ^0.0.1 --> >=0.0.1 <0.0.2-0 // ^0.1.0 --> >=0.1.0 <0.2.0-0 const replaceCarets = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceCaret(c, options)) .join(' ') } const replaceCaret = (comp, options) => { debug('caret', comp, options) const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] const z = options.includePrerelease ? '-0' : '' return comp.replace(r, (_, M, m, p, pr) => { debug('caret', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` } else if (isX(p)) { if (M === '0') { ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` } else { ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p}-${pr } <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p}-${pr } <${+M + 1}.0.0-0` } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p }${z} <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p }${z} <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p } <${+M + 1}.0.0-0` } } debug('caret return', ret) return ret }) } const replaceXRanges = (comp, options) => { debug('replaceXRanges', comp, options) return comp .split(/\s+/) .map((c) => replaceXRange(c, options)) .join(' ') } const replaceXRange = (comp, options) => { comp = comp.trim() const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] return comp.replace(r, (ret, gtlt, M, m, p, pr) => { debug('xRange', comp, ret, gtlt, M, m, p, pr) const xM = isX(M) const xm = xM || isX(m) const xp = xm || isX(p) const anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } // if we're including prereleases in the match, then we need // to fix this to -0, the lowest possible prerelease value pr = options.includePrerelease ? '-0' : '' if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0-0' } else { // nothing is forbidden ret = '*' } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0 } p = 0 if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 gtlt = '>=' if (xm) { M = +M + 1 m = 0 p = 0 } else { m = +m + 1 p = 0 } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<' if (xm) { M = +M + 1 } else { m = +m + 1 } } if (gtlt === '<') { pr = '-0' } ret = `${gtlt + M}.${m}.${p}${pr}` } else if (xm) { ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` } else if (xp) { ret = `>=${M}.${m}.0${pr } <${M}.${+m + 1}.0-0` } debug('xRange return', ret) return ret }) } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. const replaceStars = (comp, options) => { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp .trim() .replace(re[t.STAR], '') } const replaceGTE0 = (comp, options) => { debug('replaceGTE0', comp, options) return comp .trim() .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') } // This function is passed to string.replace(re[t.HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 // TODO build? const hyphenReplace = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => { if (isX(fM)) { from = '' } else if (isX(fm)) { from = `>=${fM}.0.0${incPr ? '-0' : ''}` } else if (isX(fp)) { from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` } else if (fpr) { from = `>=${from}` } else { from = `>=${from}${incPr ? '-0' : ''}` } if (isX(tM)) { to = '' } else if (isX(tm)) { to = `<${+tM + 1}.0.0-0` } else if (isX(tp)) { to = `<${tM}.${+tm + 1}.0-0` } else if (tpr) { to = `<=${tM}.${tm}.${tp}-${tpr}` } else if (incPr) { to = `<${tM}.${tm}.${+tp + 1}-0` } else { to = `<=${to}` } return `${from} ${to}`.trim() } const testSet = (set, version, options) => { for (let i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (let i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === Comparator.ANY) { continue } if (set[i].semver.prerelease.length > 0) { const allowed = set[i].semver if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } /***/ }), /***/ 94498: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const debug = __webpack_require__(717) const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(79573) const { safeRe: re, t } = __webpack_require__(70823) const parseOptions = __webpack_require__(13520) const { compareIdentifiers } = __webpack_require__(49296) class SemVer { constructor (version, options) { options = parseOptions(options) if (version instanceof SemVer) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) } if (version.length > MAX_LENGTH) { throw new TypeError( `version is longer than ${MAX_LENGTH} characters` ) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose // this isn't actually relevant for versions, but keep it so that we // don't run into trouble passing this.options around. this.includePrerelease = !!options.includePrerelease const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) if (!m) { throw new TypeError(`Invalid Version: ${version}`) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map((id) => { if (/^[0-9]+$/.test(id)) { const num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } format () { this.version = `${this.major}.${this.minor}.${this.patch}` if (this.prerelease.length) { this.version += `-${this.prerelease.join('.')}` } return this.version } toString () { return this.version } compare (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { if (typeof other === 'string' && other === this.version) { return 0 } other = new SemVer(other, this.options) } if (other.version === this.version) { return 0 } return this.compareMain(other) || this.comparePre(other) } compareMain (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return ( compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) ) } comparePre (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } let i = 0 do { const a = this.prerelease[i] const b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } compareBuild (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } let i = 0 do { const a = this.build[i] const b = other.build[i] debug('build compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc (release, identifier, identifierBase) { switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier, identifierBase) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier, identifierBase) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier, identifierBase) this.inc('pre', identifier, identifierBase) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier, identifierBase) } this.inc('pre', identifier, identifierBase) break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if ( this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0 ) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. case 'pre': { const base = Number(identifierBase) ? 1 : 0 if (!identifier && identifierBase === false) { throw new Error('invalid increment argument: identifier is empty') } if (this.prerelease.length === 0) { this.prerelease = [base] } else { let i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything if (identifier === this.prerelease.join('.') && identifierBase === false) { throw new Error('invalid increment argument: identifier already exists') } this.prerelease.push(base) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 let prerelease = [identifier, base] if (identifierBase === false) { prerelease = [identifier] } if (compareIdentifiers(this.prerelease[0], identifier) === 0) { if (isNaN(this.prerelease[1])) { this.prerelease = prerelease } } else { this.prerelease = prerelease } } break } default: throw new Error(`invalid increment argument: ${release}`) } this.raw = this.format() if (this.build.length) { this.raw += `+${this.build.join('.')}` } return this } } module.exports = SemVer /***/ }), /***/ 98284: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(29951) const clean = (version, options) => { const s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } module.exports = clean /***/ }), /***/ 12498: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const eq = __webpack_require__(95983) const neq = __webpack_require__(45291) const gt = __webpack_require__(53338) const gte = __webpack_require__(38544) const lt = __webpack_require__(63328) const lte = __webpack_require__(48577) const cmp = (a, op, b, loose) => { switch (op) { case '===': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a === b case '!==': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError(`Invalid operator: ${op}`) } } module.exports = cmp /***/ }), /***/ 96131: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(94498) const parse = __webpack_require__(29951) const { safeRe: re, t } = __webpack_require__(70823) const coerce = (version, options) => { if (version instanceof SemVer) { return version } if (typeof version === 'number') { version = String(version) } if (typeof version !== 'string') { return null } options = options || {} let match = null if (!options.rtl) { match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]) } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4' // // Walk through the string checking with a /g regexp // Manually set the index so as to pick up overlapping matches. // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL] let next while ((next = coerceRtlRegex.exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next } coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length } // leave it in a clean state coerceRtlRegex.lastIndex = -1 } if (match === null) { return null } const major = match[2] const minor = match[3] || '0' const patch = match[4] || '0' const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '' const build = options.includePrerelease && match[6] ? `+${match[6]}` : '' return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options) } module.exports = coerce /***/ }), /***/ 19131: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(94498) const compareBuild = (a, b, loose) => { const versionA = new SemVer(a, loose) const versionB = new SemVer(b, loose) return versionA.compare(versionB) || versionA.compareBuild(versionB) } module.exports = compareBuild /***/ }), /***/ 74035: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(80993) const compareLoose = (a, b) => compare(a, b, true) module.exports = compareLoose /***/ }), /***/ 80993: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(94498) const compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)) module.exports = compare /***/ }), /***/ 37826: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(29951) const diff = (version1, version2) => { const v1 = parse(version1, null, true) const v2 = parse(version2, null, true) const comparison = v1.compare(v2) if (comparison === 0) { return null } const v1Higher = comparison > 0 const highVersion = v1Higher ? v1 : v2 const lowVersion = v1Higher ? v2 : v1 const highHasPre = !!highVersion.prerelease.length const lowHasPre = !!lowVersion.prerelease.length if (lowHasPre && !highHasPre) { // Going from prerelease -> no prerelease requires some special casing // If the low version has only a major, then it will always be a major // Some examples: // 1.0.0-1 -> 1.0.0 // 1.0.0-1 -> 1.1.1 // 1.0.0-1 -> 2.0.0 if (!lowVersion.patch && !lowVersion.minor) { return 'major' } // Otherwise it can be determined by checking the high version if (highVersion.patch) { // anything higher than a patch bump would result in the wrong version return 'patch' } if (highVersion.minor) { // anything higher than a minor bump would result in the wrong version return 'minor' } // bumping major/minor/patch all have same result return 'major' } // add the `pre` prefix if we are going to a prerelease version const prefix = highHasPre ? 'pre' : '' if (v1.major !== v2.major) { return prefix + 'major' } if (v1.minor !== v2.minor) { return prefix + 'minor' } if (v1.patch !== v2.patch) { return prefix + 'patch' } // high and low are preleases return 'prerelease' } module.exports = diff /***/ }), /***/ 95983: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(80993) const eq = (a, b, loose) => compare(a, b, loose) === 0 module.exports = eq /***/ }), /***/ 53338: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(80993) const gt = (a, b, loose) => compare(a, b, loose) > 0 module.exports = gt /***/ }), /***/ 38544: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(80993) const gte = (a, b, loose) => compare(a, b, loose) >= 0 module.exports = gte /***/ }), /***/ 97383: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(94498) const inc = (version, release, options, identifier, identifierBase) => { if (typeof (options) === 'string') { identifierBase = identifier identifier = options options = undefined } try { return new SemVer( version instanceof SemVer ? version.version : version, options ).inc(release, identifier, identifierBase).version } catch (er) { return null } } module.exports = inc /***/ }), /***/ 63328: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(80993) const lt = (a, b, loose) => compare(a, b, loose) < 0 module.exports = lt /***/ }), /***/ 48577: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(80993) const lte = (a, b, loose) => compare(a, b, loose) <= 0 module.exports = lte /***/ }), /***/ 60425: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(94498) const major = (a, loose) => new SemVer(a, loose).major module.exports = major /***/ }), /***/ 39855: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(94498) const minor = (a, loose) => new SemVer(a, loose).minor module.exports = minor /***/ }), /***/ 45291: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(80993) const neq = (a, b, loose) => compare(a, b, loose) !== 0 module.exports = neq /***/ }), /***/ 29951: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(94498) const parse = (version, options, throwErrors = false) => { if (version instanceof SemVer) { return version } try { return new SemVer(version, options) } catch (er) { if (!throwErrors) { return null } throw er } } module.exports = parse /***/ }), /***/ 98205: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(94498) const patch = (a, loose) => new SemVer(a, loose).patch module.exports = patch /***/ }), /***/ 61031: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(29951) const prerelease = (version, options) => { const parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } module.exports = prerelease /***/ }), /***/ 70939: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(80993) const rcompare = (a, b, loose) => compare(b, a, loose) module.exports = rcompare /***/ }), /***/ 87679: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(19131) const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) module.exports = rsort /***/ }), /***/ 10298: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(19032) const satisfies = (version, range, options) => { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } module.exports = satisfies /***/ }), /***/ 77970: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(19131) const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) module.exports = sort /***/ }), /***/ 49270: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(29951) const valid = (version, options) => { const v = parse(version, options) return v ? v.version : null } module.exports = valid /***/ }), /***/ 73245: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // just pre-load all the stuff that index.js lazily exports const internalRe = __webpack_require__(70823) const constants = __webpack_require__(79573) const SemVer = __webpack_require__(94498) const identifiers = __webpack_require__(49296) const parse = __webpack_require__(29951) const valid = __webpack_require__(49270) const clean = __webpack_require__(98284) const inc = __webpack_require__(97383) const diff = __webpack_require__(37826) const major = __webpack_require__(60425) const minor = __webpack_require__(39855) const patch = __webpack_require__(98205) const prerelease = __webpack_require__(61031) const compare = __webpack_require__(80993) const rcompare = __webpack_require__(70939) const compareLoose = __webpack_require__(74035) const compareBuild = __webpack_require__(19131) const sort = __webpack_require__(77970) const rsort = __webpack_require__(87679) const gt = __webpack_require__(53338) const lt = __webpack_require__(63328) const eq = __webpack_require__(95983) const neq = __webpack_require__(45291) const gte = __webpack_require__(38544) const lte = __webpack_require__(48577) const cmp = __webpack_require__(12498) const coerce = __webpack_require__(96131) const Comparator = __webpack_require__(29973) const Range = __webpack_require__(19032) const satisfies = __webpack_require__(10298) const toComparators = __webpack_require__(31824) const maxSatisfying = __webpack_require__(15572) const minSatisfying = __webpack_require__(75167) const minVersion = __webpack_require__(19501) const validRange = __webpack_require__(84532) const outside = __webpack_require__(94665) const gtr = __webpack_require__(6631) const ltr = __webpack_require__(47714) const intersects = __webpack_require__(69586) const simplifyRange = __webpack_require__(75543) const subset = __webpack_require__(29073) module.exports = { parse, valid, clean, inc, diff, major, minor, patch, prerelease, compare, rcompare, compareLoose, compareBuild, sort, rsort, gt, lt, eq, neq, gte, lte, cmp, coerce, Comparator, Range, satisfies, toComparators, maxSatisfying, minSatisfying, minVersion, validRange, outside, gtr, ltr, intersects, simplifyRange, subset, SemVer, re: internalRe.re, src: internalRe.src, tokens: internalRe.t, SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, RELEASE_TYPES: constants.RELEASE_TYPES, compareIdentifiers: identifiers.compareIdentifiers, rcompareIdentifiers: identifiers.rcompareIdentifiers, } /***/ }), /***/ 79573: /***/ ((module) => { // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. const SEMVER_SPEC_VERSION = '2.0.0' const MAX_LENGTH = 256 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. const MAX_SAFE_COMPONENT_LENGTH = 16 // Max safe length for a build identifier. The max length minus 6 characters for // the shortest version with a build 0.0.0+BUILD. const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 const RELEASE_TYPES = [ 'major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease', ] module.exports = { MAX_LENGTH, MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_SAFE_INTEGER, RELEASE_TYPES, SEMVER_SPEC_VERSION, FLAG_INCLUDE_PRERELEASE: 0b001, FLAG_LOOSE: 0b010, } /***/ }), /***/ 717: /***/ ((module) => { const debug = ( typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ) ? (...args) => console.error('SEMVER', ...args) : () => {} module.exports = debug /***/ }), /***/ 49296: /***/ ((module) => { const numeric = /^[0-9]+$/ const compareIdentifiers = (a, b) => { const anum = numeric.test(a) const bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) module.exports = { compareIdentifiers, rcompareIdentifiers, } /***/ }), /***/ 81790: /***/ ((module) => { class LRUCache { constructor () { this.max = 1000 this.map = new Map() } get (key) { const value = this.map.get(key) if (value === undefined) { return undefined } else { // Remove the key from the map and add it to the end this.map.delete(key) this.map.set(key, value) return value } } delete (key) { return this.map.delete(key) } set (key, value) { const deleted = this.delete(key) if (!deleted && value !== undefined) { // If cache is full, delete the least recently used item if (this.map.size >= this.max) { const firstKey = this.map.keys().next().value this.delete(firstKey) } this.map.set(key, value) } return this } } module.exports = LRUCache /***/ }), /***/ 13520: /***/ ((module) => { // parse out just the options we care about const looseOption = Object.freeze({ loose: true }) const emptyOpts = Object.freeze({ }) const parseOptions = options => { if (!options) { return emptyOpts } if (typeof options !== 'object') { return looseOption } return options } module.exports = parseOptions /***/ }), /***/ 70823: /***/ ((module, exports, __webpack_require__) => { const { MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_LENGTH, } = __webpack_require__(79573) const debug = __webpack_require__(717) exports = module.exports = {} // The actual regexps go on exports.re const re = exports.re = [] const safeRe = exports.safeRe = [] const src = exports.src = [] const t = exports.t = {} let R = 0 const LETTERDASHNUMBER = '[a-zA-Z0-9-]' // Replace some greedy regex tokens to prevent regex dos issues. These regex are // used internally via the safeRe object since all inputs in this library get // normalized first to trim and collapse all extra whitespace. The original // regexes are exported for userland consumption and lower level usage. A // future breaking change could export the safer regex only with a note that // all input should have extra whitespace removed. const safeRegexReplacements = [ ['\\s', 1], ['\\d', MAX_LENGTH], [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], ] const makeSafeRegex = (value) => { for (const [token, max] of safeRegexReplacements) { value = value .split(`${token}*`).join(`${token}{0,${max}}`) .split(`${token}+`).join(`${token}{1,${max}}`) } return value } const createToken = (name, value, isGlobal) => { const safe = makeSafeRegex(value) const index = R++ debug(name, index, value) t[name] = index src[index] = value re[index] = new RegExp(value, isGlobal ? 'g' : undefined) safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) } // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') createToken('NUMERICIDENTIFIERLOOSE', '\\d+') // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) // ## Main Version // Three dot-separated numeric identifiers. createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`) createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] }|${src[t.NONNUMERICIDENTIFIER]})`) createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] }|${src[t.NONNUMERICIDENTIFIER]})`) // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] }(?:\\.${src[t.BUILDIDENTIFIER]})*))`) // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. createToken('FULLPLAIN', `v?${src[t.MAINVERSION] }${src[t.PRERELEASE]}?${ src[t.BUILD]}?`) createToken('FULL', `^${src[t.FULLPLAIN]}$`) // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] }${src[t.PRERELEASELOOSE]}?${ src[t.BUILD]}?`) createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) createToken('GTLT', '((?:<|>)?=?)') // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) // Coercion. // Extract anything that could conceivably be a part of a valid semver createToken('COERCEPLAIN', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`) createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`) createToken('COERCEFULL', src[t.COERCEPLAIN] + `(?:${src[t.PRERELEASE]})?` + `(?:${src[t.BUILD]})?` + `(?:$|[^\\d])`) createToken('COERCERTL', src[t.COERCE], true) createToken('COERCERTLFULL', src[t.COERCEFULL], true) // Tilde ranges. // Meaning is "reasonably at or greater than" createToken('LONETILDE', '(?:~>?)') createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) exports.tildeTrimReplace = '$1~' createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) // Caret ranges. // Meaning is "at least and backwards compatible with" createToken('LONECARET', '(?:\\^)') createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) exports.caretTrimReplace = '$1^' createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) // A simple gt/lt/eq thing, or just "" to indicate "any version" createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) exports.comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`) createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`) // Star ranges basically just allow anything at all. createToken('STAR', '(<|>)?=?\\s*\\*') // >=0.0.0 is like a star createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') /***/ }), /***/ 6631: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Determine if version is greater than all the versions possible in the range. const outside = __webpack_require__(94665) const gtr = (version, range, options) => outside(version, range, '>', options) module.exports = gtr /***/ }), /***/ 69586: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(19032) const intersects = (r1, r2, options) => { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2, options) } module.exports = intersects /***/ }), /***/ 47714: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const outside = __webpack_require__(94665) // Determine if version is less than all the versions possible in the range const ltr = (version, range, options) => outside(version, range, '<', options) module.exports = ltr /***/ }), /***/ 15572: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(94498) const Range = __webpack_require__(19032) const maxSatisfying = (versions, range, options) => { let max = null let maxSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } module.exports = maxSatisfying /***/ }), /***/ 75167: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(94498) const Range = __webpack_require__(19032) const minSatisfying = (versions, range, options) => { let min = null let minSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } module.exports = minSatisfying /***/ }), /***/ 19501: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(94498) const Range = __webpack_require__(19032) const gt = __webpack_require__(53338) const minVersion = (range, loose) => { range = new Range(range, loose) let minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let setMin = null comparators.forEach((comparator) => { // Clone to avoid manipulating the comparator's semver object. const compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!setMin || gt(compver, setMin)) { setMin = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error(`Unexpected operation: ${comparator.operator}`) } }) if (setMin && (!minver || gt(minver, setMin))) { minver = setMin } } if (minver && range.test(minver)) { return minver } return null } module.exports = minVersion /***/ }), /***/ 94665: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(94498) const Comparator = __webpack_require__(29973) const { ANY } = Comparator const Range = __webpack_require__(19032) const satisfies = __webpack_require__(10298) const gt = __webpack_require__(53338) const lt = __webpack_require__(63328) const lte = __webpack_require__(48577) const gte = __webpack_require__(38544) const outside = (version, range, hilo, options) => { version = new SemVer(version, options) range = new Range(range, options) let gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisfies the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let high = null let low = null comparators.forEach((comparator) => { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } module.exports = outside /***/ }), /***/ 75543: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // given a set of versions and a range, create a "simplified" range // that includes the same versions that the original range does // If the original range is shorter than the simplified one, return that. const satisfies = __webpack_require__(10298) const compare = __webpack_require__(80993) module.exports = (versions, range, options) => { const set = [] let first = null let prev = null const v = versions.sort((a, b) => compare(a, b, options)) for (const version of v) { const included = satisfies(version, range, options) if (included) { prev = version if (!first) { first = version } } else { if (prev) { set.push([first, prev]) } prev = null first = null } } if (first) { set.push([first, null]) } const ranges = [] for (const [min, max] of set) { if (min === max) { ranges.push(min) } else if (!max && min === v[0]) { ranges.push('*') } else if (!max) { ranges.push(`>=${min}`) } else if (min === v[0]) { ranges.push(`<=${max}`) } else { ranges.push(`${min} - ${max}`) } } const simplified = ranges.join(' || ') const original = typeof range.raw === 'string' ? range.raw : String(range) return simplified.length < original.length ? simplified : range } /***/ }), /***/ 29073: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(19032) const Comparator = __webpack_require__(29973) const { ANY } = Comparator const satisfies = __webpack_require__(10298) const compare = __webpack_require__(80993) // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: // - Every simple range `r1, r2, ...` is a null set, OR // - Every simple range `r1, r2, ...` which is not a null set is a subset of // some `R1, R2, ...` // // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: // - If c is only the ANY comparator // - If C is only the ANY comparator, return true // - Else if in prerelease mode, return false // - else replace c with `[>=0.0.0]` // - If C is only the ANY comparator // - if in prerelease mode, return true // - else replace C with `[>=0.0.0]` // - Let EQ be the set of = comparators in c // - If EQ is more than one, return true (null set) // - Let GT be the highest > or >= comparator in c // - Let LT be the lowest < or <= comparator in c // - If GT and LT, and GT.semver > LT.semver, return true (null set) // - If any C is a = range, and GT or LT are set, return false // - If EQ // - If GT, and EQ does not satisfy GT, return true (null set) // - If LT, and EQ does not satisfy LT, return true (null set) // - If EQ satisfies every C, return true // - Else return false // - If GT // - If GT.semver is lower than any > or >= comp in C, return false // - If GT is >=, and GT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the GT.semver tuple, return false // - If LT // - If LT.semver is greater than any < or <= comp in C, return false // - If LT is <=, and LT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the LT.semver tuple, return false // - Else return true const subset = (sub, dom, options = {}) => { if (sub === dom) { return true } sub = new Range(sub, options) dom = new Range(dom, options) let sawNonNull = false OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { const isSub = simpleSubset(simpleSub, simpleDom, options) sawNonNull = sawNonNull || isSub !== null if (isSub) { continue OUTER } } // the null set is a subset of everything, but null simple ranges in // a complex range should be ignored. so if we saw a non-null range, // then we know this isn't a subset, but if EVERY simple range was null, // then it is a subset. if (sawNonNull) { return false } } return true } const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] const minimumVersion = [new Comparator('>=0.0.0')] const simpleSubset = (sub, dom, options) => { if (sub === dom) { return true } if (sub.length === 1 && sub[0].semver === ANY) { if (dom.length === 1 && dom[0].semver === ANY) { return true } else if (options.includePrerelease) { sub = minimumVersionWithPreRelease } else { sub = minimumVersion } } if (dom.length === 1 && dom[0].semver === ANY) { if (options.includePrerelease) { return true } else { dom = minimumVersion } } const eqSet = new Set() let gt, lt for (const c of sub) { if (c.operator === '>' || c.operator === '>=') { gt = higherGT(gt, c, options) } else if (c.operator === '<' || c.operator === '<=') { lt = lowerLT(lt, c, options) } else { eqSet.add(c.semver) } } if (eqSet.size > 1) { return null } let gtltComp if (gt && lt) { gtltComp = compare(gt.semver, lt.semver, options) if (gtltComp > 0) { return null } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { return null } } // will iterate one or zero times for (const eq of eqSet) { if (gt && !satisfies(eq, String(gt), options)) { return null } if (lt && !satisfies(eq, String(lt), options)) { return null } for (const c of dom) { if (!satisfies(eq, String(c), options)) { return false } } return true } let higher, lower let hasDomLT, hasDomGT // if the subset has a prerelease, we need a comparator in the superset // with the same tuple and a prerelease, or it's not a subset let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false // exception: <1.2.3-0 is the same as <1.2.3 if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { needDomLTPre = false } for (const c of dom) { hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' if (gt) { if (needDomGTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { needDomGTPre = false } } if (c.operator === '>' || c.operator === '>=') { higher = higherGT(gt, c, options) if (higher === c && higher !== gt) { return false } } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { return false } } if (lt) { if (needDomLTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { needDomLTPre = false } } if (c.operator === '<' || c.operator === '<=') { lower = lowerLT(lt, c, options) if (lower === c && lower !== lt) { return false } } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { return false } } if (!c.operator && (lt || gt) && gtltComp !== 0) { return false } } // if there was a < or >, and nothing in the dom, then must be false // UNLESS it was limited by another range in the other direction. // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 if (gt && hasDomLT && !lt && gtltComp !== 0) { return false } if (lt && hasDomGT && !gt && gtltComp !== 0) { return false } // we needed a prerelease range in a specific tuple, but didn't get one // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, // because it includes prereleases in the 1.2.3 tuple if (needDomGTPre || needDomLTPre) { return false } return true } // >=1.2.3 is lower than >1.2.3 const higherGT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp > 0 ? a : comp < 0 ? b : b.operator === '>' && a.operator === '>=' ? b : a } // <=1.2.3 is higher than <1.2.3 const lowerLT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp < 0 ? a : comp > 0 ? b : b.operator === '<' && a.operator === '<=' ? b : a } module.exports = subset /***/ }), /***/ 31824: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(19032) // Mostly just for testing and legacy API reasons const toComparators = (range, options) => new Range(range, options).set .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) module.exports = toComparators /***/ }), /***/ 84532: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(19032) const validRange = (range, options) => { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } module.exports = validRange /***/ }), /***/ 77997: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /*! * Tmp * * Copyright (c) 2011-2017 KARASZI Istvan * * MIT Licensed */ /* * Module dependencies. */ const fs = __webpack_require__(57147); const os = __webpack_require__(22037); const path = __webpack_require__(71017); const crypto = __webpack_require__(6113); const _c = { fs: fs.constants, os: os.constants }; /* * The working inner variables. */ const // the random characters to choose from RANDOM_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', TEMPLATE_PATTERN = /XXXXXX/, DEFAULT_TRIES = 3, CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR), // constants are off on the windows platform and will not match the actual errno codes IS_WIN32 = os.platform() === 'win32', EBADF = _c.EBADF || _c.os.errno.EBADF, ENOENT = _c.ENOENT || _c.os.errno.ENOENT, DIR_MODE = 0o700 /* 448 */, FILE_MODE = 0o600 /* 384 */, EXIT = 'exit', // this will hold the objects need to be removed on exit _removeObjects = [], // API change in fs.rmdirSync leads to error when passing in a second parameter, e.g. the callback FN_RMDIR_SYNC = fs.rmdirSync.bind(fs); let _gracefulCleanup = false; /** * Recursively remove a directory and its contents. * * @param {string} dirPath path of directory to remove * @param {Function} callback * @private */ function rimraf(dirPath, callback) { return fs.rm(dirPath, { recursive: true }, callback); } /** * Recursively remove a directory and its contents, synchronously. * * @param {string} dirPath path of directory to remove * @private */ function FN_RIMRAF_SYNC(dirPath) { return fs.rmSync(dirPath, { recursive: true }); } /** * Gets a temporary file name. * * @param {(Options|tmpNameCallback)} options options or callback * @param {?tmpNameCallback} callback the callback function */ function tmpName(options, callback) { const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; try { _assertAndSanitizeOptions(opts); } catch (err) { return cb(err); } let tries = opts.tries; (function _getUniqueName() { try { const name = _generateTmpName(opts); // check whether the path exists then retry if needed fs.stat(name, function (err) { /* istanbul ignore else */ if (!err) { /* istanbul ignore else */ if (tries-- > 0) return _getUniqueName(); return cb(new Error('Could not get a unique tmp filename, max tries reached ' + name)); } cb(null, name); }); } catch (err) { cb(err); } }()); } /** * Synchronous version of tmpName. * * @param {Object} options * @returns {string} the generated random name * @throws {Error} if the options are invalid or could not generate a filename */ function tmpNameSync(options) { const args = _parseArguments(options), opts = args[0]; _assertAndSanitizeOptions(opts); let tries = opts.tries; do { const name = _generateTmpName(opts); try { fs.statSync(name); } catch (e) { return name; } } while (tries-- > 0); throw new Error('Could not get a unique tmp filename, max tries reached'); } /** * Creates and opens a temporary file. * * @param {(Options|null|undefined|fileCallback)} options the config options or the callback function or null or undefined * @param {?fileCallback} callback */ function file(options, callback) { const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; // gets a temporary filename tmpName(opts, function _tmpNameCreated(err, name) { /* istanbul ignore else */ if (err) return cb(err); // create and open the file fs.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err, fd) { /* istanbu ignore else */ if (err) return cb(err); if (opts.discardDescriptor) { return fs.close(fd, function _discardCallback(possibleErr) { // the chance of getting an error on close here is rather low and might occur in the most edgiest cases only return cb(possibleErr, name, undefined, _prepareTmpFileRemoveCallback(name, -1, opts, false)); }); } else { // detachDescriptor passes the descriptor whereas discardDescriptor closes it, either way, we no longer care // about the descriptor const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; cb(null, name, fd, _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, false)); } }); }); } /** * Synchronous version of file. * * @param {Options} options * @returns {FileSyncObject} object consists of name, fd and removeCallback * @throws {Error} if cannot create a file */ function fileSync(options) { const args = _parseArguments(options), opts = args[0]; const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; const name = tmpNameSync(opts); var fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); /* istanbul ignore else */ if (opts.discardDescriptor) { fs.closeSync(fd); fd = undefined; } return { name: name, fd: fd, removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, true) }; } /** * Creates a temporary directory. * * @param {(Options|dirCallback)} options the options or the callback function * @param {?dirCallback} callback */ function dir(options, callback) { const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; // gets a temporary filename tmpName(opts, function _tmpNameCreated(err, name) { /* istanbul ignore else */ if (err) return cb(err); // create the directory fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err) { /* istanbul ignore else */ if (err) return cb(err); cb(null, name, _prepareTmpDirRemoveCallback(name, opts, false)); }); }); } /** * Synchronous version of dir. * * @param {Options} options * @returns {DirSyncObject} object consists of name and removeCallback * @throws {Error} if it cannot create a directory */ function dirSync(options) { const args = _parseArguments(options), opts = args[0]; const name = tmpNameSync(opts); fs.mkdirSync(name, opts.mode || DIR_MODE); return { name: name, removeCallback: _prepareTmpDirRemoveCallback(name, opts, true) }; } /** * Removes files asynchronously. * * @param {Object} fdPath * @param {Function} next * @private */ function _removeFileAsync(fdPath, next) { const _handler = function (err) { if (err && !_isENOENT(err)) { // reraise any unanticipated error return next(err); } next(); }; if (0 <= fdPath[0]) fs.close(fdPath[0], function () { fs.unlink(fdPath[1], _handler); }); else fs.unlink(fdPath[1], _handler); } /** * Removes files synchronously. * * @param {Object} fdPath * @private */ function _removeFileSync(fdPath) { let rethrownException = null; try { if (0 <= fdPath[0]) fs.closeSync(fdPath[0]); } catch (e) { // reraise any unanticipated error if (!_isEBADF(e) && !_isENOENT(e)) throw e; } finally { try { fs.unlinkSync(fdPath[1]); } catch (e) { // reraise any unanticipated error if (!_isENOENT(e)) rethrownException = e; } } if (rethrownException !== null) { throw rethrownException; } } /** * Prepares the callback for removal of the temporary file. * * Returns either a sync callback or a async callback depending on whether * fileSync or file was called, which is expressed by the sync parameter. * * @param {string} name the path of the file * @param {number} fd file descriptor * @param {Object} opts * @param {boolean} sync * @returns {fileCallback | fileCallbackSync} * @private */ function _prepareTmpFileRemoveCallback(name, fd, opts, sync) { const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name], sync); const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], sync, removeCallbackSync); if (!opts.keep) _removeObjects.unshift(removeCallbackSync); return sync ? removeCallbackSync : removeCallback; } /** * Prepares the callback for removal of the temporary directory. * * Returns either a sync callback or a async callback depending on whether * tmpFileSync or tmpFile was called, which is expressed by the sync parameter. * * @param {string} name * @param {Object} opts * @param {boolean} sync * @returns {Function} the callback * @private */ function _prepareTmpDirRemoveCallback(name, opts, sync) { const removeFunction = opts.unsafeCleanup ? rimraf : fs.rmdir.bind(fs); const removeFunctionSync = opts.unsafeCleanup ? FN_RIMRAF_SYNC : FN_RMDIR_SYNC; const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name, sync); const removeCallback = _prepareRemoveCallback(removeFunction, name, sync, removeCallbackSync); if (!opts.keep) _removeObjects.unshift(removeCallbackSync); return sync ? removeCallbackSync : removeCallback; } /** * Creates a guarded function wrapping the removeFunction call. * * The cleanup callback is save to be called multiple times. * Subsequent invocations will be ignored. * * @param {Function} removeFunction * @param {string} fileOrDirName * @param {boolean} sync * @param {cleanupCallbackSync?} cleanupCallbackSync * @returns {cleanupCallback | cleanupCallbackSync} * @private */ function _prepareRemoveCallback(removeFunction, fileOrDirName, sync, cleanupCallbackSync) { let called = false; // if sync is true, the next parameter will be ignored return function _cleanupCallback(next) { /* istanbul ignore else */ if (!called) { // remove cleanupCallback from cache const toRemove = cleanupCallbackSync || _cleanupCallback; const index = _removeObjects.indexOf(toRemove); /* istanbul ignore else */ if (index >= 0) _removeObjects.splice(index, 1); called = true; if (sync || removeFunction === FN_RMDIR_SYNC || removeFunction === FN_RIMRAF_SYNC) { return removeFunction(fileOrDirName); } else { return removeFunction(fileOrDirName, next || function() {}); } } }; } /** * The garbage collector. * * @private */ function _garbageCollector() { /* istanbul ignore else */ if (!_gracefulCleanup) return; // the function being called removes itself from _removeObjects, // loop until _removeObjects is empty while (_removeObjects.length) { try { _removeObjects[0](); } catch (e) { // already removed? } } } /** * Random name generator based on crypto. * Adapted from http://blog.tompawlak.org/how-to-generate-random-values-nodejs-javascript * * @param {number} howMany * @returns {string} the generated random name * @private */ function _randomChars(howMany) { let value = [], rnd = null; // make sure that we do not fail because we ran out of entropy try { rnd = crypto.randomBytes(howMany); } catch (e) { rnd = crypto.pseudoRandomBytes(howMany); } for (var i = 0; i < howMany; i++) { value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]); } return value.join(''); } /** * Helper which determines whether a string s is blank, that is undefined, or empty or null. * * @private * @param {string} s * @returns {Boolean} true whether the string s is blank, false otherwise */ function _isBlank(s) { return s === null || _isUndefined(s) || !s.trim(); } /** * Checks whether the `obj` parameter is defined or not. * * @param {Object} obj * @returns {boolean} true if the object is undefined * @private */ function _isUndefined(obj) { return typeof obj === 'undefined'; } /** * Parses the function arguments. * * This function helps to have optional arguments. * * @param {(Options|null|undefined|Function)} options * @param {?Function} callback * @returns {Array} parsed arguments * @private */ function _parseArguments(options, callback) { /* istanbul ignore else */ if (typeof options === 'function') { return [{}, options]; } /* istanbul ignore else */ if (_isUndefined(options)) { return [{}, callback]; } // copy options so we do not leak the changes we make internally const actualOptions = {}; for (const key of Object.getOwnPropertyNames(options)) { actualOptions[key] = options[key]; } return [actualOptions, callback]; } /** * Generates a new temporary name. * * @param {Object} opts * @returns {string} the new random name according to opts * @private */ function _generateTmpName(opts) { const tmpDir = opts.tmpdir; /* istanbul ignore else */ if (!_isUndefined(opts.name)) return path.join(tmpDir, opts.dir, opts.name); /* istanbul ignore else */ if (!_isUndefined(opts.template)) return path.join(tmpDir, opts.dir, opts.template).replace(TEMPLATE_PATTERN, _randomChars(6)); // prefix and postfix const name = [ opts.prefix ? opts.prefix : 'tmp', '-', process.pid, '-', _randomChars(12), opts.postfix ? '-' + opts.postfix : '' ].join(''); return path.join(tmpDir, opts.dir, name); } /** * Asserts whether the specified options are valid, also sanitizes options and provides sane defaults for missing * options. * * @param {Options} options * @private */ function _assertAndSanitizeOptions(options) { options.tmpdir = _getTmpDir(options); const tmpDir = options.tmpdir; /* istanbul ignore else */ if (!_isUndefined(options.name)) _assertIsRelative(options.name, 'name', tmpDir); /* istanbul ignore else */ if (!_isUndefined(options.dir)) _assertIsRelative(options.dir, 'dir', tmpDir); /* istanbul ignore else */ if (!_isUndefined(options.template)) { _assertIsRelative(options.template, 'template', tmpDir); if (!options.template.match(TEMPLATE_PATTERN)) throw new Error(`Invalid template, found "${options.template}".`); } /* istanbul ignore else */ if (!_isUndefined(options.tries) && isNaN(options.tries) || options.tries < 0) throw new Error(`Invalid tries, found "${options.tries}".`); // if a name was specified we will try once options.tries = _isUndefined(options.name) ? options.tries || DEFAULT_TRIES : 1; options.keep = !!options.keep; options.detachDescriptor = !!options.detachDescriptor; options.discardDescriptor = !!options.discardDescriptor; options.unsafeCleanup = !!options.unsafeCleanup; // sanitize dir, also keep (multiple) blanks if the user, purportedly sane, requests us to options.dir = _isUndefined(options.dir) ? '' : path.relative(tmpDir, _resolvePath(options.dir, tmpDir)); options.template = _isUndefined(options.template) ? undefined : path.relative(tmpDir, _resolvePath(options.template, tmpDir)); // sanitize further if template is relative to options.dir options.template = _isBlank(options.template) ? undefined : path.relative(options.dir, options.template); // for completeness' sake only, also keep (multiple) blanks if the user, purportedly sane, requests us to options.name = _isUndefined(options.name) ? undefined : options.name; options.prefix = _isUndefined(options.prefix) ? '' : options.prefix; options.postfix = _isUndefined(options.postfix) ? '' : options.postfix; } /** * Resolve the specified path name in respect to tmpDir. * * The specified name might include relative path components, e.g. ../ * so we need to resolve in order to be sure that is is located inside tmpDir * * @param name * @param tmpDir * @returns {string} * @private */ function _resolvePath(name, tmpDir) { if (name.startsWith(tmpDir)) { return path.resolve(name); } else { return path.resolve(path.join(tmpDir, name)); } } /** * Asserts whether specified name is relative to the specified tmpDir. * * @param {string} name * @param {string} option * @param {string} tmpDir * @throws {Error} * @private */ function _assertIsRelative(name, option, tmpDir) { if (option === 'name') { // assert that name is not absolute and does not contain a path if (path.isAbsolute(name)) throw new Error(`${option} option must not contain an absolute path, found "${name}".`); // must not fail on valid . or .. or similar such constructs let basename = path.basename(name); if (basename === '..' || basename === '.' || basename !== name) throw new Error(`${option} option must not contain a path, found "${name}".`); } else { // if (option === 'dir' || option === 'template') { // assert that dir or template are relative to tmpDir if (path.isAbsolute(name) && !name.startsWith(tmpDir)) { throw new Error(`${option} option must be relative to "${tmpDir}", found "${name}".`); } let resolvedPath = _resolvePath(name, tmpDir); if (!resolvedPath.startsWith(tmpDir)) throw new Error(`${option} option must be relative to "${tmpDir}", found "${resolvedPath}".`); } } /** * Helper for testing against EBADF to compensate changes made to Node 7.x under Windows. * * @private */ function _isEBADF(error) { return _isExpectedError(error, -EBADF, 'EBADF'); } /** * Helper for testing against ENOENT to compensate changes made to Node 7.x under Windows. * * @private */ function _isENOENT(error) { return _isExpectedError(error, -ENOENT, 'ENOENT'); } /** * Helper to determine whether the expected error code matches the actual code and errno, * which will differ between the supported node versions. * * - Node >= 7.0: * error.code {string} * error.errno {number} any numerical value will be negated * * CAVEAT * * On windows, the errno for EBADF is -4083 but os.constants.errno.EBADF is different and we must assume that ENOENT * is no different here. * * @param {SystemError} error * @param {number} errno * @param {string} code * @private */ function _isExpectedError(error, errno, code) { return IS_WIN32 ? error.code === code : error.code === code && error.errno === errno; } /** * Sets the graceful cleanup. * * If graceful cleanup is set, tmp will remove all controlled temporary objects on process exit, otherwise the * temporary objects will remain in place, waiting to be cleaned up on system restart or otherwise scheduled temporary * object removals. */ function setGracefulCleanup() { _gracefulCleanup = true; } /** * Returns the currently configured tmp dir from os.tmpdir(). * * @private * @param {?Options} options * @returns {string} the currently configured tmp dir */ function _getTmpDir(options) { return path.resolve(options && options.tmpdir || os.tmpdir()); } // Install process exit listener process.addListener(EXIT, _garbageCollector); /** * Configuration options. * * @typedef {Object} Options * @property {?boolean} keep the temporary object (file or dir) will not be garbage collected * @property {?number} tries the number of tries before give up the name generation * @property (?int) mode the access mode, defaults are 0o700 for directories and 0o600 for files * @property {?string} template the "mkstemp" like filename template * @property {?string} name fixed name relative to tmpdir or the specified dir option * @property {?string} dir tmp directory relative to the root tmp directory in use * @property {?string} prefix prefix for the generated name * @property {?string} postfix postfix for the generated name * @property {?string} tmpdir the root tmp directory which overrides the os tmpdir * @property {?boolean} unsafeCleanup recursively removes the created temporary directory, even when it's not empty * @property {?boolean} detachDescriptor detaches the file descriptor, caller is responsible for closing the file, tmp will no longer try closing the file during garbage collection * @property {?boolean} discardDescriptor discards the file descriptor (closes file, fd is -1), tmp will no longer try closing the file during garbage collection */ /** * @typedef {Object} FileSyncObject * @property {string} name the name of the file * @property {string} fd the file descriptor or -1 if the fd has been discarded * @property {fileCallback} removeCallback the callback function to remove the file */ /** * @typedef {Object} DirSyncObject * @property {string} name the name of the directory * @property {fileCallback} removeCallback the callback function to remove the directory */ /** * @callback tmpNameCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name */ /** * @callback fileCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {number} fd the file descriptor or -1 if the fd had been discarded * @param {cleanupCallback} fn the cleanup callback function */ /** * @callback fileCallbackSync * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {number} fd the file descriptor or -1 if the fd had been discarded * @param {cleanupCallbackSync} fn the cleanup callback function */ /** * @callback dirCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {cleanupCallback} fn the cleanup callback function */ /** * @callback dirCallbackSync * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {cleanupCallbackSync} fn the cleanup callback function */ /** * Removes the temporary created file or directory. * * @callback cleanupCallback * @param {simpleCallback} [next] function to call whenever the tmp object needs to be removed */ /** * Removes the temporary created file or directory. * * @callback cleanupCallbackSync */ /** * Callback function for function composition. * @see {@link https://github.com/raszi/node-tmp/issues/57|raszi/node-tmp#57} * * @callback simpleCallback */ // exporting all the needed methods // evaluate _getTmpDir() lazily, mainly for simplifying testing but it also will // allow users to reconfigure the temporary directory Object.defineProperty(module.exports, "tmpdir", ({ enumerable: true, configurable: false, get: function () { return _getTmpDir(); } })); module.exports.dir = dir; module.exports.dirSync = dirSync; module.exports.file = file; module.exports.fileSync = fileSync; module.exports.tmpName = tmpName; module.exports.tmpNameSync = tmpNameSync; module.exports.setGracefulCleanup = setGracefulCleanup; /***/ }), /***/ 18793: /***/ ((module) => { "use strict"; // TODO(kyegupov): add a return type for this function // Dependency types. // We don't call out all of them, only the ones relevant to our behavior. // extraneous means not found in package.json files, prod means not dev ATM function depTypes(depName, pkg) { let type = null; let from = 'unknown'; if (pkg.devDependencies && pkg.devDependencies[depName]) { type = depTypes.DEV; from = pkg.devDependencies[depName]; } if (pkg.optionalDependencies && pkg.optionalDependencies[depName]) { type = depTypes.OPTIONAL; from = pkg.optionalDependencies[depName]; } // production deps trump all if (pkg.dependencies && pkg.dependencies[depName]) { type = depTypes.PROD; from = pkg.dependencies[depName]; } let bundled = !!(pkg.bundleDependencies && pkg.bundleDependencies[depName]); return { type: type, from: from, bundled: bundled, }; } depTypes.EXTRANEOUS = 'extraneous'; depTypes.OPTIONAL = 'optional'; depTypes.PROD = 'prod'; depTypes.DEV = 'dev'; module.exports = depTypes; //# sourceMappingURL=dep-types.js.map /***/ }), /***/ 88435: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; const depTypes = __webpack_require__(18793); const fs = __webpack_require__(75575); const lodash_1 = __webpack_require__(96486); const lodash_2 = __webpack_require__(96486); const lodash_3 = __webpack_require__(96486); const lodash_4 = __webpack_require__(96486); const lodash_5 = __webpack_require__(96486); const debugModule = __webpack_require__(15158); const path = __webpack_require__(71017); const semver = __webpack_require__(48938); const resolve = __webpack_require__(7320); const tryRequire = __webpack_require__(14402); const debug = debugModule('snyk:resolve:deps'); function applyExtraFields(src, dest, extraFields) { if (!extraFields || !extraFields.length) { return; } extraFields.forEach(function applyExtraField(field) { (0, lodash_2.set)(dest, field, (0, lodash_1.get)(src, field) || null); }); } // FIXME: only supports dependencies & dev deps not opt-deps function loadModules(root, depType, options) { return __awaiter(this, void 0, void 0, function* () { tryRequire.cache.reset(); // reset the package cache on re-run let opt = (0, lodash_3.clone)(options || {}); let pkgRoot = root; if (opt.file) { const pathInfo = path.parse(opt.file); pkgRoot = path.resolve(pkgRoot, pathInfo.dir); opt.file = pathInfo.base; } const tree = yield loadModulesInternal(pkgRoot, depType || null, null, opt); // ensure there's no missing packages our known root deps let missing = []; if (tree.__dependencies) { Object.keys(tree.__dependencies).forEach(function (name) { if (!tree.dependencies[name]) { missing.push(resolve(name, pkgRoot).then(function (dir) { return loadModulesInternal(dir, depTypes.PROD, { __from: [tree.name + '@' + tree.version, name], }); }).catch(function (e) { if (e.code === 'NO_PACKAGE_FOUND') { return false; } })); } }); } if (missing.length) { return Promise.all(missing).then(function (packages) { packages.filter(Boolean).forEach(function (pkg) { pkg.dep = tree.__dependencies[pkg.name]; tree.dependencies[pkg.name] = pkg; }); return tree; }); } return tree; }); } function loadModulesInternal(root, rootDepType, parent, options) { options = options || {}; if (!rootDepType) { rootDepType = depTypes.EXTRANEOUS; } if (typeof root !== 'string') { return Promise.reject(new Error('module path must be a string')); } let modules = {}; let dir = path.resolve(root, options.file || 'package.json'); // 1. read package.json for written deps let promise = tryRequire(dir).then(function (pkg) { // if there's a package found, collect this information too if (pkg) { let full = pkg.name + '@' + (pkg.version || '0.0.0'); modules = {}; applyExtraFields(pkg, modules, options.extraFields); (0, lodash_4.assign)(modules, { name: pkg.name, version: pkg.version || null, license: pkg.license || 'none', depType: rootDepType, hasDevDependencies: !!pkg.devDependencies, full: full, __from: (parent || { __from: [] }).__from, __devDependencies: pkg.devDependencies, __dependencies: pkg.dependencies, __optionalDependencies: pkg.optionalDependencies, __bundleDependencies: pkg.bundleDependencies, __filename: pkg.__filename, }); // allows us to add to work out the full path that the package was // introduced via pkg.__from = modules.__from.concat(full); pkg.full = modules.full; // flag and track where a shrinkwrapped package comes from if (!pkg.shrinkwrap && parent && parent.shrinkwrap) { pkg.shrinkwrap = parent.shrinkwrap; } else if (pkg.shrinkwrap) { pkg.shrinkwrap = pkg.full; } // this is a special case for the root package to get a consistent // __from path, so that the complete path (including it's own pkg name) if (modules.__from.length === 0) { modules.__from.push(full); } } else { throw new Error(dir + ' is not a node project'); } modules.dependencies = {}; // 2. check actual installed deps return fs.readdir(path.resolve(root, 'node_modules')).then(function (dirs) { let res = dirs.map(function (directory) { // completely ignore `.bin` npm helper dir // ~ can be a symlink to node_modules itself // (https://www.npmjs.com/package/link-tilde) if (['.bin', '.DS_Store', '~'].indexOf(directory) >= 0) { return null; } // this is a scoped namespace, and we'd expect to find directories // inside *this* `dir`, so treat differently if (directory.indexOf('@') === 0) { debug('scoped reset on %s', directory); directory = path.resolve(root, 'node_modules', directory); return fs.readdir(directory).then(function (directories) { return Promise.all(directories.map(function (scopedDir) { return tryRequire(path.resolve(directory, scopedDir, 'package.json')); })); }); } // otherwise try to load a package.json from this node_module dir directory = path.resolve(root, 'node_modules', directory); return fs.realpath(directory).then(function (realDirectory) { if (realDirectory === root) { return null; } else { return tryRequire(path.resolve(directory, 'package.json')); } }); }); return Promise.all(res).then(function (response) { response = (0, lodash_5.flatten)(response).filter(Boolean); // if res.length === 0 we used to throw MISSING_NODE_MODULES but we're // not doing that now, and I think it's okay. // TODO: convert reduces to more readable code throughout response.reduce(function (acc, curr) { let license; let licenses = curr.license || curr.licenses; if (Array.isArray(licenses)) { license = licenses.reduce(function (accumulator, current) { accumulator.push((current || {}).type || current); return accumulator; }, []).join('/'); } else { license = (licenses || {}).type || licenses; } let depInfo = depTypes(curr.name, pkg); let depType = depInfo.type || rootDepType; let depFrom = depInfo.from; let valid = false; if (depFrom) { valid = semver.satisfies(curr.version, depFrom); } let full = curr.name + '@' + (curr.version || '0.0.0'); acc[curr.name] = {}; applyExtraFields(curr, acc[curr.name], options.extraFields); (0, lodash_4.assign)(acc[curr.name], { name: curr.name, version: curr.version || null, full: full, valid: valid, depType: depType, snyk: curr.snyk, license: license || 'none', dep: depFrom || null, __from: pkg.__from.concat(full), __devDependencies: curr.devDependencies, __dependencies: curr.dependencies, __optionalDependencies: curr.optionalDependencies, __bundleDependencies: curr.bundleDependencies, __filename: curr.__filename, }); if (depInfo.bundled) { acc[curr.name].bundled = acc[curr.name].__from.slice(0); } if (pkg.shrinkwrap) { acc[curr.name].shrinkwrap = pkg.shrinkwrap; } return acc; }, modules.dependencies); return modules; }); }).then(function (mods) { let deps = Object.keys(mods.dependencies); let promises = deps.map(function (dep) { let depType = mods.dependencies[dep].depType; let directory = path.dirname(mods.dependencies[dep].__filename); return loadModulesInternal(directory, depType, pkg); }); return Promise.all(promises).then(function (res) { res.forEach(function (mod) { mods.dependencies[mod.name].dependencies = mod.dependencies; }); return mods; }); }).catch(function (error) { // TODO decide whether it's okay that we keep throwing errors // will this process get faster without it? (possibly...) /* istanbul ignore else */ if (error.code === 'ENOENT') { // there's no node_modules directory, that's fine, there's no deps modules.dependencies = {}; return modules; } /* istanbul ignore next */ throw error; }); }); return promise; } module.exports = loadModules; //# sourceMappingURL=deps.js.map /***/ }), /***/ 40068: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const physicalTree = __webpack_require__(88435); const logicalTree = __webpack_require__(42164); const walk = __webpack_require__(20565); const prune = __webpack_require__(27855); const pluck = __webpack_require__(6039); const unique = __webpack_require__(23215); function resolveDeps(dir, options) { return physicalTree(dir, null, options).then((res) => logicalTree(res, options)); } resolveDeps.physicalTree = physicalTree; resolveDeps.logicalTree = logicalTree; resolveDeps.walk = walk; resolveDeps.prune = prune; resolveDeps.pluck = pluck; resolveDeps.unique = unique; module.exports = resolveDeps; //# sourceMappingURL=index.js.map /***/ }), /***/ 42164: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const pluck = __webpack_require__(6039); const walk = __webpack_require__(20565); const unique = __webpack_require__(23215); const lodash_1 = __webpack_require__(96486); const path = __webpack_require__(71017); const depTypes = __webpack_require__(18793); const colour = __webpack_require__(48811); const snyk_module_1 = __webpack_require__(63307); const util = __webpack_require__(73837); const format = util.format; const ext = colour.bgBlack(colour.green('extraneous')); /** * This code will build up the logical tree representation of a node package * and it's dependencies. This is based initially on reading the directory * structure and the package.json files found in each directory. * * After which, we parse the tree and read the `__dependencies` looking for * their actual location on disk (or if it's missing, etc) - marking as we * go along that the leaf has been used. * * After that, we need to search for the original tree for unused leafs, and * these will be marked as extraneous and carried through to the logical * tree at the same depth. * * Important: some extraneous modules will actually be from devDependencies * from the root level, so we need to handle these carefully. */ function logicalTree(fileTree, options) { if (!options) { options = {}; } let problems = []; let logicalRoot = copy(fileTree, fileTree.__from); logicalRoot.dependencies = walkDeps(fileTree, fileTree, undefined, problems); let removedPaths = []; if (!options.dev) { // do a shallow pass on the deps and strip out dev deps Object.keys(fileTree.dependencies).forEach(function (name) { let dep = fileTree.dependencies[name]; // if we're not interested in devDeps, then strip them out if (dep.depType === depTypes.DEV) { // since dev deps are only ever on the root, we know we can remove it // directly from the logicalRoot.dependencies removedPaths.push(dep.__from); delete logicalRoot.dependencies[dep.name]; return; } }); } logicalRoot.numFileDependencies = 0; walk(fileTree.dependencies, function (dep) { logicalRoot.numFileDependencies++; if (!dep.__used) { let deppath = dep.__from.slice(0, -1).toString(); let removed = removedPaths.filter(function (removedPath) { return deppath.indexOf(removedPath) === 0; }).length; if (removed) { return false; // this was from a dev dep, so let's lose it } let leaf = copy(dep); let issue = format('%s: %s@%s (from %s) > %s', ext, leaf.name, leaf.version, leaf.dep, path.relative('.', leaf.__filename)); leaf.problems = [issue]; problems.push(issue); leaf.extraneous = true; leaf.depType = depTypes.EXTRANEOUS; leaf.dependencies = walkDeps(fileTree, dep, undefined, problems); walk(leaf.dependencies, function (extraDep) { extraDep.extraneous = true; extraDep.depType = depTypes.EXTRANEOUS; }); insertLeaf(logicalRoot, leaf, dep.__from); } }); logicalRoot.numDependencies = Object.keys(unique(logicalRoot).dependencies).length; logicalRoot.pluck = pluck.bind(null, fileTree); logicalRoot.unique = unique.bind(null, logicalRoot); logicalRoot.problems = problems.slice(0); if (options.noFromArrays) { logicalRoot = removeFromPaths(logicalRoot); } return logicalRoot; } function insertLeaf(tree, leaf, from) { // remove the root of the path and covert to names only let leafPath = (from || []).slice(1, -1).map(function (pkg) { return (0, snyk_module_1.parsePackageString)(pkg).name; }); let entry = tree.dependencies; for (let i = 0; i < leafPath.length; i++) { if (entry[leafPath[i]]) { entry = entry[leafPath[i]].dependencies; } } entry[leaf.name] = leaf; } function walkDeps(root, tree, suppliedFrom, problems) { let from = suppliedFrom || tree.__from; // only include the devDeps on the root level package let deps = (0, lodash_1.assignIn)({}, tree.__dependencies, tree.__from && from.length === 1 ? tree.__devDependencies : {}); deps = (0, lodash_1.assignIn)(deps, tree.__optionalDependencies); return Object.keys(deps).reduce(function walkDepsPicker(acc, curr) { // only attempt to walk this dep if it's not in our path already if (tree.__from.indexOf(curr) === -1) { let version = deps[curr]; let dep = pluck(root, tree.__from, curr, version); if (!dep) { problems.push(format('missing: %s@%s, required by %s', curr, version, from.join(' > '))); return acc; } if (from.indexOf(dep.full) === -1) { let pkg = acc[dep.name] = copy(dep, from.concat(dep.full)); dep.__used = true; let info = depTypes(dep.name, { dependencies: tree.__dependencies, devDependencies: tree.__devDependencies, bundleDependencies: tree.__bundleDependencies, optionalDependencies: tree.__optionalDependencies, }); pkg.depType = info.type; pkg.dep = info.from; if (tree.bundled) { // carry the bundled flag down from the parent dep.bundled = pkg.bundled = tree.bundled; } pkg.dependencies = walkDeps(root, dep, pkg.from, problems); } } return acc; }, {}); } function copy(leaf, from) { if (!from) { from = leaf.__from; } let res = Object.keys(leaf).reduce(function copyIterator(acc, curr) { if (leaf[curr] !== undefined && curr.indexOf('__') !== 0) { if (curr !== 'dependencies') { acc[curr] = leaf[curr]; } } return acc; }, {}); res.from = from.slice(0); res.__filename = leaf.__filename; return res; } function removeFromPaths(tree) { delete tree.from; let deps = tree.dependencies; Object.keys(deps).forEach(function (name) { removeFromPaths(deps[name]); }); return tree; } module.exports = logicalTree; //# sourceMappingURL=logical.js.map /***/ }), /***/ 6039: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const semver = __webpack_require__(48938); const snyk_module_1 = __webpack_require__(63307); const debugModule = __webpack_require__(15158); const debug = debugModule('snyk:resolve:pluck'); const parseOptions = { loose: true }; function pluck(root, path, name, range) { if (range === 'latest') { range = '*'; } // Cycle through the tree path via the root tree object **ala node require**. // note that we don't need the first item in the path (which is the root // package name). let from = path.slice(0); let rootPath = (0, snyk_module_1.parsePackageString)(from.shift(), parseOptions).name; // if the root of the virtual tree doesn't even match our path, bail out if (rootPath !== root.name) { return false; } // do a check to see if the last item in the path is actually the package // we're looking for, and if it's not, push it on if (from.length !== 0 && (0, snyk_module_1.parsePackageString)(from.slice(-1).pop(), parseOptions).name === name) { from.pop(); } // then we always put the target package on the end of the chain // to ensure it's in exactly the right format to be used in `getMatch` from.push(name + '@' + range); debug('using forward search %s@%s in %s', from.join(' > ')); let match = false; let leaf = root; let realPath = []; while (from.length) { let pkg = (0, snyk_module_1.parsePackageString)(from[0], parseOptions); let test = getMatch(leaf, pkg.name, pkg.version); if (test) { from.shift(); realPath.push(leaf); leaf = test; } else { let maybeLeaf = realPath.pop(); if (!maybeLeaf) { return false; } leaf = maybeLeaf; } } return leaf.name === name ? leaf : false; } function getMatch(root, name, range) { let dep = root.dependencies && root.dependencies[name]; if (!dep) { return false; } let version = dep.version; debug('pluck match on name...checking version: %s ~= %s', version, range); // make sure it matches our range let semverMatch = semver.validRange(range) && semver.valid(version) && semver.satisfies(version, range); let externalPackage = !semver.validRange(range) && range.indexOf(':/') !== -1; if (semverMatch || externalPackage) { debug('pluck match'); if (!dep.dep) { dep.dep = range; } return dep; } return false; } module.exports = pluck; //# sourceMappingURL=pluck.js.map /***/ }), /***/ 27855: /***/ ((module) => { "use strict"; function prune(pkg, shouldPrune) { let remove = shouldPrune(pkg); if (!remove) { pkg.dependencies = {}; } let deps = Object.keys(pkg.dependencies || {}); if (deps.length) { remove = deps.filter(function (name) { if (prune(pkg.dependencies[name], shouldPrune)) { delete pkg.dependencies[name]; return false; } return true; }).length; remove = remove === 0; } return remove; } module.exports = prune; //# sourceMappingURL=prune.js.map /***/ }), /***/ 23215: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const walk = __webpack_require__(20565); function unique(deps) { let res = copy(deps); res.dependencies = {}; walk(deps, function (dep) { let shallowCopy = copy(dep); res.dependencies[dep.name + '@' + dep.version] = shallowCopy; }); return res; } // TODO: rename to withoutDeps, don't use reduce function copy(dep) { return Object.keys(dep).filter(function (key) { return key.toLowerCase().indexOf('dependencies') === -1; }).reduce(function (acc, curr) { acc[curr] = dep[curr]; return acc; }, {}); } module.exports = unique; //# sourceMappingURL=unique.js.map /***/ }), /***/ 20565: /***/ ((module) => { "use strict"; function walk(depsOrPkg, filter) { if (!depsOrPkg) { return []; } let deps = (depsOrPkg.dependencies ? depsOrPkg.dependencies : depsOrPkg); Object.keys(deps).forEach(function (name) { let res = filter(deps[name], name, deps); if (!res && deps[name] && deps[name].dep) { walk(deps[name].dependencies, filter); } }); } module.exports = walk; //# sourceMappingURL=walk.js.map /***/ }), /***/ 72232: /***/ ((module) => { "use strict"; const maybeJoin = (...args) => args.every(arg => arg) ? args.join('') : '' const maybeEncode = (arg) => arg ? encodeURIComponent(arg) : '' const defaults = { sshtemplate: ({ domain, user, project, committish }) => `git@${domain}:${user}/${project}.git${maybeJoin('#', committish)}`, sshurltemplate: ({ domain, user, project, committish }) => `git+ssh://git@${domain}/${user}/${project}.git${maybeJoin('#', committish)}`, browsetemplate: ({ domain, user, project, committish, treepath }) => `https://${domain}/${user}/${project}${maybeJoin('/', treepath, '/', maybeEncode(committish))}`, browsefiletemplate: ({ domain, user, project, committish, treepath, path, fragment, hashformat }) => `https://${domain}/${user}/${project}/${treepath}/${maybeEncode(committish || 'master')}/${path}${maybeJoin('#', hashformat(fragment || ''))}`, docstemplate: ({ domain, user, project, treepath, committish }) => `https://${domain}/${user}/${project}${maybeJoin('/', treepath, '/', maybeEncode(committish))}#readme`, httpstemplate: ({ auth, domain, user, project, committish }) => `git+https://${maybeJoin(auth, '@')}${domain}/${user}/${project}.git${maybeJoin('#', committish)}`, filetemplate: ({ domain, user, project, committish, path }) => `https://${domain}/${user}/${project}/raw/${maybeEncode(committish) || 'master'}/${path}`, shortcuttemplate: ({ type, user, project, committish }) => `${type}:${user}/${project}${maybeJoin('#', committish)}`, pathtemplate: ({ user, project, committish }) => `${user}/${project}${maybeJoin('#', committish)}`, bugstemplate: ({ domain, user, project }) => `https://${domain}/${user}/${project}/issues`, hashformat: formatHashFragment } const gitHosts = {} gitHosts.github = Object.assign({}, defaults, { // First two are insecure and generally shouldn't be used any more, but // they are still supported. protocols: ['git:', 'http:', 'git+ssh:', 'git+https:', 'ssh:', 'https:'], domain: 'github.com', treepath: 'tree', filetemplate: ({ auth, user, project, committish, path }) => `https://${maybeJoin(auth, '@')}raw.githubusercontent.com/${user}/${project}/${maybeEncode(committish) || 'master'}/${path}`, gittemplate: ({ auth, domain, user, project, committish }) => `git://${maybeJoin(auth, '@')}${domain}/${user}/${project}.git${maybeJoin('#', committish)}`, tarballtemplate: ({ domain, user, project, committish }) => `https://codeload.${domain}/${user}/${project}/tar.gz/${maybeEncode(committish) || 'master'}`, extract: (url) => { let [, user, project, type, committish] = url.pathname.split('/', 5) if (type && type !== 'tree') { return } if (!type) { committish = url.hash.slice(1) } if (project && project.endsWith('.git')) { project = project.slice(0, -4) } if (!user || !project) { return } return { user, project, committish } } }) gitHosts.bitbucket = Object.assign({}, defaults, { protocols: ['git+ssh:', 'git+https:', 'ssh:', 'https:'], domain: 'bitbucket.org', treepath: 'src', tarballtemplate: ({ domain, user, project, committish }) => `https://${domain}/${user}/${project}/get/${maybeEncode(committish) || 'master'}.tar.gz`, extract: (url) => { let [, user, project, aux] = url.pathname.split('/', 4) if (['get'].includes(aux)) { return } if (project && project.endsWith('.git')) { project = project.slice(0, -4) } if (!user || !project) { return } return { user, project, committish: url.hash.slice(1) } } }) gitHosts.gitlab = Object.assign({}, defaults, { protocols: ['git+ssh:', 'git+https:', 'ssh:', 'https:'], domain: 'gitlab.com', treepath: 'tree', httpstemplate: ({ auth, domain, user, project, committish }) => `git+https://${maybeJoin(auth, '@')}${domain}/${user}/${project}.git${maybeJoin('#', committish)}`, tarballtemplate: ({ domain, user, project, committish }) => `https://${domain}/${user}/${project}/repository/archive.tar.gz?ref=${maybeEncode(committish) || 'master'}`, extract: (url) => { const path = url.pathname.slice(1) if (path.includes('/-/') || path.includes('/archive.tar.gz')) { return } const segments = path.split('/') let project = segments.pop() if (project.endsWith('.git')) { project = project.slice(0, -4) } const user = segments.join('/') if (!user || !project) { return } return { user, project, committish: url.hash.slice(1) } } }) gitHosts.gist = Object.assign({}, defaults, { protocols: ['git:', 'git+ssh:', 'git+https:', 'ssh:', 'https:'], domain: 'gist.github.com', sshtemplate: ({ domain, project, committish }) => `git@${domain}:${project}.git${maybeJoin('#', committish)}`, sshurltemplate: ({ domain, project, committish }) => `git+ssh://git@${domain}/${project}.git${maybeJoin('#', committish)}`, browsetemplate: ({ domain, project, committish }) => `https://${domain}/${project}${maybeJoin('/', maybeEncode(committish))}`, browsefiletemplate: ({ domain, project, committish, path, hashformat }) => `https://${domain}/${project}${maybeJoin('/', maybeEncode(committish))}${maybeJoin('#', hashformat(path))}`, docstemplate: ({ domain, project, committish }) => `https://${domain}/${project}${maybeJoin('/', maybeEncode(committish))}`, httpstemplate: ({ domain, project, committish }) => `git+https://${domain}/${project}.git${maybeJoin('#', committish)}`, filetemplate: ({ user, project, committish, path }) => `https://gist.githubusercontent.com/${user}/${project}/raw${maybeJoin('/', maybeEncode(committish))}/${path}`, shortcuttemplate: ({ type, project, committish }) => `${type}:${project}${maybeJoin('#', committish)}`, pathtemplate: ({ project, committish }) => `${project}${maybeJoin('#', committish)}`, bugstemplate: ({ domain, project }) => `https://${domain}/${project}`, gittemplate: ({ domain, project, committish }) => `git://${domain}/${project}.git${maybeJoin('#', committish)}`, tarballtemplate: ({ project, committish }) => `https://codeload.github.com/gist/${project}/tar.gz/${maybeEncode(committish) || 'master'}`, extract: (url) => { let [, user, project, aux] = url.pathname.split('/', 4) if (aux === 'raw') { return } if (!project) { if (!user) { return } project = user user = null } if (project.endsWith('.git')) { project = project.slice(0, -4) } return { user, project, committish: url.hash.slice(1) } }, hashformat: function (fragment) { return fragment && 'file-' + formatHashFragment(fragment) } }) gitHosts.sourcehut = Object.assign({}, defaults, { protocols: ['git+ssh:', 'https:'], domain: 'git.sr.ht', treepath: 'tree', browsefiletemplate: ({ domain, user, project, committish, treepath, path, fragment, hashformat }) => `https://${domain}/${user}/${project}/${treepath}/${maybeEncode(committish || 'main')}/${path}${maybeJoin('#', hashformat(fragment || ''))}`, filetemplate: ({ domain, user, project, committish, path }) => `https://${domain}/${user}/${project}/blob/${maybeEncode(committish) || 'main'}/${path}`, httpstemplate: ({ domain, user, project, committish }) => `https://${domain}/${user}/${project}.git${maybeJoin('#', committish)}`, tarballtemplate: ({ domain, user, project, committish }) => `https://${domain}/${user}/${project}/archive/${maybeEncode(committish) || 'main'}.tar.gz`, bugstemplate: ({ domain, user, project }) => `https://todo.sr.ht/${user}/${project}`, docstemplate: ({ domain, user, project, treepath, committish }) => `https://${domain}/${user}/${project}${maybeJoin('/', treepath, '/', maybeEncode(committish))}#readme`, extract: (url) => { let [, user, project, aux] = url.pathname.split('/', 4) // tarball url if (['archive'].includes(aux)) { return } if (project && project.endsWith('.git')) { project = project.slice(0, -4) } if (!user || !project) { return } return { user, project, committish: url.hash.slice(1) } } }) const names = Object.keys(gitHosts) gitHosts.byShortcut = {} gitHosts.byDomain = {} for (const name of names) { gitHosts.byShortcut[`${name}:`] = name gitHosts.byDomain[gitHosts[name].domain] = name } function formatHashFragment (fragment) { return fragment.toLowerCase().replace(/^\W+|\/|\W+$/g, '').replace(/\W+/g, '-') } module.exports = gitHosts /***/ }), /***/ 99155: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const gitHosts = __webpack_require__(72232) class GitHost { constructor (type, user, auth, project, committish, defaultRepresentation, opts = {}) { Object.assign(this, gitHosts[type]) this.type = type this.user = user this.auth = auth this.project = project this.committish = committish this.default = defaultRepresentation this.opts = opts } hash () { return this.committish ? `#${this.committish}` : '' } ssh (opts) { return this._fill(this.sshtemplate, opts) } _fill (template, opts) { if (typeof template === 'function') { const options = { ...this, ...this.opts, ...opts } // the path should always be set so we don't end up with 'undefined' in urls if (!options.path) { options.path = '' } // template functions will insert the leading slash themselves if (options.path.startsWith('/')) { options.path = options.path.slice(1) } if (options.noCommittish) { options.committish = null } const result = template(options) return options.noGitPlus && result.startsWith('git+') ? result.slice(4) : result } return null } sshurl (opts) { return this._fill(this.sshurltemplate, opts) } browse (path, fragment, opts) { // not a string, treat path as opts if (typeof path !== 'string') { return this._fill(this.browsetemplate, path) } if (typeof fragment !== 'string') { opts = fragment fragment = null } return this._fill(this.browsefiletemplate, { ...opts, fragment, path }) } docs (opts) { return this._fill(this.docstemplate, opts) } bugs (opts) { return this._fill(this.bugstemplate, opts) } https (opts) { return this._fill(this.httpstemplate, opts) } git (opts) { return this._fill(this.gittemplate, opts) } shortcut (opts) { return this._fill(this.shortcuttemplate, opts) } path (opts) { return this._fill(this.pathtemplate, opts) } tarball (opts) { return this._fill(this.tarballtemplate, { ...opts, noCommittish: false }) } file (path, opts) { return this._fill(this.filetemplate, { ...opts, path }) } getDefaultRepresentation () { return this.default } toString (opts) { if (this.default && typeof this[this.default] === 'function') { return this[this.default](opts) } return this.sshurl(opts) } } module.exports = GitHost /***/ }), /***/ 11034: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const url = __webpack_require__(57310) const gitHosts = __webpack_require__(72232) const GitHost = module.exports = __webpack_require__(99155) const LRU = __webpack_require__(24695) const cache = new LRU({ max: 1000 }) const protocolToRepresentationMap = { 'git+ssh:': 'sshurl', 'git+https:': 'https', 'ssh:': 'sshurl', 'git:': 'git' } function protocolToRepresentation (protocol) { return protocolToRepresentationMap[protocol] || protocol.slice(0, -1) } const authProtocols = { 'git:': true, 'https:': true, 'git+https:': true, 'http:': true, 'git+http:': true } const knownProtocols = Object.keys(gitHosts.byShortcut).concat(['http:', 'https:', 'git:', 'git+ssh:', 'git+https:', 'ssh:']) module.exports.fromUrl = function (giturl, opts) { if (typeof giturl !== 'string') { return } const key = giturl + JSON.stringify(opts || {}) if (!cache.has(key)) { cache.set(key, fromUrl(giturl, opts)) } return cache.get(key) } function fromUrl (giturl, opts) { if (!giturl) { return } const url = isGitHubShorthand(giturl) ? 'github:' + giturl : correctProtocol(giturl) const parsed = parseGitUrl(url) if (!parsed) { return parsed } const gitHostShortcut = gitHosts.byShortcut[parsed.protocol] const gitHostDomain = gitHosts.byDomain[parsed.hostname.startsWith('www.') ? parsed.hostname.slice(4) : parsed.hostname] const gitHostName = gitHostShortcut || gitHostDomain if (!gitHostName) { return } const gitHostInfo = gitHosts[gitHostShortcut || gitHostDomain] let auth = null if (authProtocols[parsed.protocol] && (parsed.username || parsed.password)) { auth = `${parsed.username}${parsed.password ? ':' + parsed.password : ''}` } let committish = null let user = null let project = null let defaultRepresentation = null try { if (gitHostShortcut) { let pathname = parsed.pathname.startsWith('/') ? parsed.pathname.slice(1) : parsed.pathname const firstAt = pathname.indexOf('@') // we ignore auth for shortcuts, so just trim it out if (firstAt > -1) { pathname = pathname.slice(firstAt + 1) } const lastSlash = pathname.lastIndexOf('/') if (lastSlash > -1) { user = decodeURIComponent(pathname.slice(0, lastSlash)) // we want nulls only, never empty strings if (!user) { user = null } project = decodeURIComponent(pathname.slice(lastSlash + 1)) } else { project = decodeURIComponent(pathname) } if (project.endsWith('.git')) { project = project.slice(0, -4) } if (parsed.hash) { committish = decodeURIComponent(parsed.hash.slice(1)) } defaultRepresentation = 'shortcut' } else { if (!gitHostInfo.protocols.includes(parsed.protocol)) { return } const segments = gitHostInfo.extract(parsed) if (!segments) { return } user = segments.user && decodeURIComponent(segments.user) project = decodeURIComponent(segments.project) committish = decodeURIComponent(segments.committish) defaultRepresentation = protocolToRepresentation(parsed.protocol) } } catch (err) { /* istanbul ignore else */ if (err instanceof URIError) { return } else { throw err } } return new GitHost(gitHostName, user, auth, project, committish, defaultRepresentation, opts) } // accepts input like git:github.com:user/repo and inserts the // after the first : const correctProtocol = (arg) => { const firstColon = arg.indexOf(':') const proto = arg.slice(0, firstColon + 1) if (knownProtocols.includes(proto)) { return arg } const firstAt = arg.indexOf('@') if (firstAt > -1) { if (firstAt > firstColon) { return `git+ssh://${arg}` } else { return arg } } const doubleSlash = arg.indexOf('//') if (doubleSlash === firstColon + 1) { return arg } return arg.slice(0, firstColon + 1) + '//' + arg.slice(firstColon + 1) } // look for github shorthand inputs, such as npm/cli const isGitHubShorthand = (arg) => { // it cannot contain whitespace before the first # // it cannot start with a / because that's probably an absolute file path // but it must include a slash since repos are username/repository // it cannot start with a . because that's probably a relative file path // it cannot start with an @ because that's a scoped package if it passes the other tests // it cannot contain a : before a # because that tells us that there's a protocol // a second / may not exist before a # const firstHash = arg.indexOf('#') const firstSlash = arg.indexOf('/') const secondSlash = arg.indexOf('/', firstSlash + 1) const firstColon = arg.indexOf(':') const firstSpace = /\s/.exec(arg) const firstAt = arg.indexOf('@') const spaceOnlyAfterHash = !firstSpace || (firstHash > -1 && firstSpace.index > firstHash) const atOnlyAfterHash = firstAt === -1 || (firstHash > -1 && firstAt > firstHash) const colonOnlyAfterHash = firstColon === -1 || (firstHash > -1 && firstColon > firstHash) const secondSlashOnlyAfterHash = secondSlash === -1 || (firstHash > -1 && secondSlash > firstHash) const hasSlash = firstSlash > 0 // if a # is found, what we really want to know is that the character immediately before # is not a / const doesNotEndWithSlash = firstHash > -1 ? arg[firstHash - 1] !== '/' : !arg.endsWith('/') const doesNotStartWithDot = !arg.startsWith('.') return spaceOnlyAfterHash && hasSlash && doesNotEndWithSlash && doesNotStartWithDot && atOnlyAfterHash && colonOnlyAfterHash && secondSlashOnlyAfterHash } // attempt to correct an scp style url so that it will parse with `new URL()` const correctUrl = (giturl) => { const firstAt = giturl.indexOf('@') const lastHash = giturl.lastIndexOf('#') let firstColon = giturl.indexOf(':') let lastColon = giturl.lastIndexOf(':', lastHash > -1 ? lastHash : Infinity) let corrected if (lastColon > firstAt) { // the last : comes after the first @ (or there is no @) // like it would in: // proto://hostname.com:user/repo // username@hostname.com:user/repo // :password@hostname.com:user/repo // username:password@hostname.com:user/repo // proto://username@hostname.com:user/repo // proto://:password@hostname.com:user/repo // proto://username:password@hostname.com:user/repo // then we replace the last : with a / to create a valid path corrected = giturl.slice(0, lastColon) + '/' + giturl.slice(lastColon + 1) // // and we find our new : positions firstColon = corrected.indexOf(':') lastColon = corrected.lastIndexOf(':') } if (firstColon === -1 && giturl.indexOf('//') === -1) { // we have no : at all // as it would be in: // username@hostname.com/user/repo // then we prepend a protocol corrected = `git+ssh://${corrected}` } return corrected } // try to parse the url as its given to us, if that throws // then we try to clean the url and parse that result instead // THIS FUNCTION SHOULD NEVER THROW const parseGitUrl = (giturl) => { let result try { result = new url.URL(giturl) } catch (err) {} if (result) { return result } const correctedUrl = correctUrl(giturl) try { result = new url.URL(correctedUrl) } catch (err) {} return result } /***/ }), /***/ 24695: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // A linked list to keep track of recently-used-ness const Yallist = __webpack_require__(80014) const MAX = Symbol('max') const LENGTH = Symbol('length') const LENGTH_CALCULATOR = Symbol('lengthCalculator') const ALLOW_STALE = Symbol('allowStale') const MAX_AGE = Symbol('maxAge') const DISPOSE = Symbol('dispose') const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') const LRU_LIST = Symbol('lruList') const CACHE = Symbol('cache') const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') const naiveLength = () => 1 // lruList is a yallist where the head is the youngest // item, and the tail is the oldest. the list contains the Hit // objects as the entries. // Each Hit object has a reference to its Yallist.Node. This // never changes. // // cache is a Map (or PseudoMap) that matches the keys to // the Yallist.Node object. class LRUCache { constructor (options) { if (typeof options === 'number') options = { max: options } if (!options) options = {} if (options.max && (typeof options.max !== 'number' || options.max < 0)) throw new TypeError('max must be a non-negative number') // Kind of weird to have a default max of Infinity, but oh well. const max = this[MAX] = options.max || Infinity const lc = options.length || naiveLength this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc this[ALLOW_STALE] = options.stale || false if (options.maxAge && typeof options.maxAge !== 'number') throw new TypeError('maxAge must be a number') this[MAX_AGE] = options.maxAge || 0 this[DISPOSE] = options.dispose this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false this.reset() } // resize the cache when the max changes. set max (mL) { if (typeof mL !== 'number' || mL < 0) throw new TypeError('max must be a non-negative number') this[MAX] = mL || Infinity trim(this) } get max () { return this[MAX] } set allowStale (allowStale) { this[ALLOW_STALE] = !!allowStale } get allowStale () { return this[ALLOW_STALE] } set maxAge (mA) { if (typeof mA !== 'number') throw new TypeError('maxAge must be a non-negative number') this[MAX_AGE] = mA trim(this) } get maxAge () { return this[MAX_AGE] } // resize the cache when the lengthCalculator changes. set lengthCalculator (lC) { if (typeof lC !== 'function') lC = naiveLength if (lC !== this[LENGTH_CALCULATOR]) { this[LENGTH_CALCULATOR] = lC this[LENGTH] = 0 this[LRU_LIST].forEach(hit => { hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) this[LENGTH] += hit.length }) } trim(this) } get lengthCalculator () { return this[LENGTH_CALCULATOR] } get length () { return this[LENGTH] } get itemCount () { return this[LRU_LIST].length } rforEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].tail; walker !== null;) { const prev = walker.prev forEachStep(this, fn, walker, thisp) walker = prev } } forEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].head; walker !== null;) { const next = walker.next forEachStep(this, fn, walker, thisp) walker = next } } keys () { return this[LRU_LIST].toArray().map(k => k.key) } values () { return this[LRU_LIST].toArray().map(k => k.value) } reset () { if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) { this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) } this[CACHE] = new Map() // hash of items by key this[LRU_LIST] = new Yallist() // list of items in order of use recency this[LENGTH] = 0 // length of items in the list } dump () { return this[LRU_LIST].map(hit => isStale(this, hit) ? false : { k: hit.key, v: hit.value, e: hit.now + (hit.maxAge || 0) }).toArray().filter(h => h) } dumpLru () { return this[LRU_LIST] } set (key, value, maxAge) { maxAge = maxAge || this[MAX_AGE] if (maxAge && typeof maxAge !== 'number') throw new TypeError('maxAge must be a number') const now = maxAge ? Date.now() : 0 const len = this[LENGTH_CALCULATOR](value, key) if (this[CACHE].has(key)) { if (len > this[MAX]) { del(this, this[CACHE].get(key)) return false } const node = this[CACHE].get(key) const item = node.value // dispose of the old one before overwriting // split out into 2 ifs for better coverage tracking if (this[DISPOSE]) { if (!this[NO_DISPOSE_ON_SET]) this[DISPOSE](key, item.value) } item.now = now item.maxAge = maxAge item.value = value this[LENGTH] += len - item.length item.length = len this.get(key) trim(this) return true } const hit = new Entry(key, value, len, now, maxAge) // oversized objects fall out of cache automatically. if (hit.length > this[MAX]) { if (this[DISPOSE]) this[DISPOSE](key, value) return false } this[LENGTH] += hit.length this[LRU_LIST].unshift(hit) this[CACHE].set(key, this[LRU_LIST].head) trim(this) return true } has (key) { if (!this[CACHE].has(key)) return false const hit = this[CACHE].get(key).value return !isStale(this, hit) } get (key) { return get(this, key, true) } peek (key) { return get(this, key, false) } pop () { const node = this[LRU_LIST].tail if (!node) return null del(this, node) return node.value } del (key) { del(this, this[CACHE].get(key)) } load (arr) { // reset the cache this.reset() const now = Date.now() // A previous serialized cache has the most recent items first for (let l = arr.length - 1; l >= 0; l--) { const hit = arr[l] const expiresAt = hit.e || 0 if (expiresAt === 0) // the item was created without expiration in a non aged cache this.set(hit.k, hit.v) else { const maxAge = expiresAt - now // dont add already expired items if (maxAge > 0) { this.set(hit.k, hit.v, maxAge) } } } } prune () { this[CACHE].forEach((value, key) => get(this, key, false)) } } const get = (self, key, doUse) => { const node = self[CACHE].get(key) if (node) { const hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) return undefined } else { if (doUse) { if (self[UPDATE_AGE_ON_GET]) node.value.now = Date.now() self[LRU_LIST].unshiftNode(node) } } return hit.value } } const isStale = (self, hit) => { if (!hit || (!hit.maxAge && !self[MAX_AGE])) return false const diff = Date.now() - hit.now return hit.maxAge ? diff > hit.maxAge : self[MAX_AGE] && (diff > self[MAX_AGE]) } const trim = self => { if (self[LENGTH] > self[MAX]) { for (let walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) { // We know that we're about to delete this one, and also // what the next least recently used key will be, so just // go ahead and set it now. const prev = walker.prev del(self, walker) walker = prev } } } const del = (self, node) => { if (node) { const hit = node.value if (self[DISPOSE]) self[DISPOSE](hit.key, hit.value) self[LENGTH] -= hit.length self[CACHE].delete(hit.key) self[LRU_LIST].removeNode(node) } } class Entry { constructor (key, value, length, now, maxAge) { this.key = key this.value = value this.length = length this.now = now this.maxAge = maxAge || 0 } } const forEachStep = (self, fn, node, thisp) => { let hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) hit = undefined } if (hit) fn.call(thisp, hit.value, hit.key, self) } module.exports = LRUCache /***/ }), /***/ 16572: /***/ ((module) => { "use strict"; module.exports = function (Yallist) { Yallist.prototype[Symbol.iterator] = function* () { for (let walker = this.head; walker; walker = walker.next) { yield walker.value } } } /***/ }), /***/ 80014: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = Yallist Yallist.Node = Node Yallist.create = Yallist function Yallist (list) { var self = this if (!(self instanceof Yallist)) { self = new Yallist() } self.tail = null self.head = null self.length = 0 if (list && typeof list.forEach === 'function') { list.forEach(function (item) { self.push(item) }) } else if (arguments.length > 0) { for (var i = 0, l = arguments.length; i < l; i++) { self.push(arguments[i]) } } return self } Yallist.prototype.removeNode = function (node) { if (node.list !== this) { throw new Error('removing node which does not belong to this list') } var next = node.next var prev = node.prev if (next) { next.prev = prev } if (prev) { prev.next = next } if (node === this.head) { this.head = next } if (node === this.tail) { this.tail = prev } node.list.length-- node.next = null node.prev = null node.list = null return next } Yallist.prototype.unshiftNode = function (node) { if (node === this.head) { return } if (node.list) { node.list.removeNode(node) } var head = this.head node.list = this node.next = head if (head) { head.prev = node } this.head = node if (!this.tail) { this.tail = node } this.length++ } Yallist.prototype.pushNode = function (node) { if (node === this.tail) { return } if (node.list) { node.list.removeNode(node) } var tail = this.tail node.list = this node.prev = tail if (tail) { tail.next = node } this.tail = node if (!this.head) { this.head = node } this.length++ } Yallist.prototype.push = function () { for (var i = 0, l = arguments.length; i < l; i++) { push(this, arguments[i]) } return this.length } Yallist.prototype.unshift = function () { for (var i = 0, l = arguments.length; i < l; i++) { unshift(this, arguments[i]) } return this.length } Yallist.prototype.pop = function () { if (!this.tail) { return undefined } var res = this.tail.value this.tail = this.tail.prev if (this.tail) { this.tail.next = null } else { this.head = null } this.length-- return res } Yallist.prototype.shift = function () { if (!this.head) { return undefined } var res = this.head.value this.head = this.head.next if (this.head) { this.head.prev = null } else { this.tail = null } this.length-- return res } Yallist.prototype.forEach = function (fn, thisp) { thisp = thisp || this for (var walker = this.head, i = 0; walker !== null; i++) { fn.call(thisp, walker.value, i, this) walker = walker.next } } Yallist.prototype.forEachReverse = function (fn, thisp) { thisp = thisp || this for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { fn.call(thisp, walker.value, i, this) walker = walker.prev } } Yallist.prototype.get = function (n) { for (var i = 0, walker = this.head; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.next } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.getReverse = function (n) { for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.prev } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.map = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.head; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.next } return res } Yallist.prototype.mapReverse = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.tail; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.prev } return res } Yallist.prototype.reduce = function (fn, initial) { var acc var walker = this.head if (arguments.length > 1) { acc = initial } else if (this.head) { walker = this.head.next acc = this.head.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = 0; walker !== null; i++) { acc = fn(acc, walker.value, i) walker = walker.next } return acc } Yallist.prototype.reduceReverse = function (fn, initial) { var acc var walker = this.tail if (arguments.length > 1) { acc = initial } else if (this.tail) { walker = this.tail.prev acc = this.tail.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = this.length - 1; walker !== null; i--) { acc = fn(acc, walker.value, i) walker = walker.prev } return acc } Yallist.prototype.toArray = function () { var arr = new Array(this.length) for (var i = 0, walker = this.head; walker !== null; i++) { arr[i] = walker.value walker = walker.next } return arr } Yallist.prototype.toArrayReverse = function () { var arr = new Array(this.length) for (var i = 0, walker = this.tail; walker !== null; i++) { arr[i] = walker.value walker = walker.prev } return arr } Yallist.prototype.slice = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = 0, walker = this.head; walker !== null && i < from; i++) { walker = walker.next } for (; walker !== null && i < to; i++, walker = walker.next) { ret.push(walker.value) } return ret } Yallist.prototype.sliceReverse = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { walker = walker.prev } for (; walker !== null && i > from; i--, walker = walker.prev) { ret.push(walker.value) } return ret } Yallist.prototype.splice = function (start, deleteCount, ...nodes) { if (start > this.length) { start = this.length - 1 } if (start < 0) { start = this.length + start; } for (var i = 0, walker = this.head; walker !== null && i < start; i++) { walker = walker.next } var ret = [] for (var i = 0; walker && i < deleteCount; i++) { ret.push(walker.value) walker = this.removeNode(walker) } if (walker === null) { walker = this.tail } if (walker !== this.head && walker !== this.tail) { walker = walker.prev } for (var i = 0; i < nodes.length; i++) { walker = insert(this, walker, nodes[i]) } return ret; } Yallist.prototype.reverse = function () { var head = this.head var tail = this.tail for (var walker = head; walker !== null; walker = walker.prev) { var p = walker.prev walker.prev = walker.next walker.next = p } this.head = tail this.tail = head return this } function insert (self, node, value) { var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self) if (inserted.next === null) { self.tail = inserted } if (inserted.prev === null) { self.head = inserted } self.length++ return inserted } function push (self, item) { self.tail = new Node(item, self.tail, null, self) if (!self.head) { self.head = self.tail } self.length++ } function unshift (self, item) { self.head = new Node(item, null, self.head, self) if (!self.tail) { self.tail = self.head } self.length++ } function Node (value, prev, next, list) { if (!(this instanceof Node)) { return new Node(value, prev, next, list) } this.list = list this.value = value if (prev) { prev.next = this this.prev = prev } else { this.prev = null } if (next) { next.prev = this this.next = next } else { this.next = null } } try { // add if support for Symbol.iterator is present __webpack_require__(16572)(Yallist) } catch (er) {} /***/ }), /***/ 48938: /***/ ((module, exports) => { exports = module.exports = SemVer var debug /* istanbul ignore next */ if (typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) { debug = function () { var args = Array.prototype.slice.call(arguments, 0) args.unshift('SEMVER') console.log.apply(console, args) } } else { debug = function () {} } // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. exports.SEMVER_SPEC_VERSION = '2.0.0' var MAX_LENGTH = 256 var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. var MAX_SAFE_COMPONENT_LENGTH = 16 var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 // The actual regexps go on exports.re var re = exports.re = [] var safeRe = exports.safeRe = [] var src = exports.src = [] var R = 0 var LETTERDASHNUMBER = '[a-zA-Z0-9-]' // Replace some greedy regex tokens to prevent regex dos issues. These regex are // used internally via the safeRe object since all inputs in this library get // normalized first to trim and collapse all extra whitespace. The original // regexes are exported for userland consumption and lower level usage. A // future breaking change could export the safer regex only with a note that // all input should have extra whitespace removed. var safeRegexReplacements = [ ['\\s', 1], ['\\d', MAX_LENGTH], [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], ] function makeSafeRe (value) { for (var i = 0; i < safeRegexReplacements.length; i++) { var token = safeRegexReplacements[i][0] var max = safeRegexReplacements[i][1] value = value .split(token + '*').join(token + '{0,' + max + '}') .split(token + '+').join(token + '{1,' + max + '}') } return value } // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. var NUMERICIDENTIFIER = R++ src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' var NUMERICIDENTIFIERLOOSE = R++ src[NUMERICIDENTIFIERLOOSE] = '\\d+' // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. var NONNUMERICIDENTIFIER = R++ src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-]' + LETTERDASHNUMBER + '*' // ## Main Version // Three dot-separated numeric identifiers. var MAINVERSION = R++ src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')' var MAINVERSIONLOOSE = R++ src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')' // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. var PRERELEASEIDENTIFIER = R++ src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + '|' + src[NONNUMERICIDENTIFIER] + ')' var PRERELEASEIDENTIFIERLOOSE = R++ src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + '|' + src[NONNUMERICIDENTIFIER] + ')' // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. var PRERELEASE = R++ src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' var PRERELEASELOOSE = R++ src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. var BUILDIDENTIFIER = R++ src[BUILDIDENTIFIER] = LETTERDASHNUMBER + '+' // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. var BUILD = R++ src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. var FULL = R++ var FULLPLAIN = 'v?' + src[MAINVERSION] + src[PRERELEASE] + '?' + src[BUILD] + '?' src[FULL] = '^' + FULLPLAIN + '$' // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + src[PRERELEASELOOSE] + '?' + src[BUILD] + '?' var LOOSE = R++ src[LOOSE] = '^' + LOOSEPLAIN + '$' var GTLT = R++ src[GTLT] = '((?:<|>)?=?)' // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. var XRANGEIDENTIFIERLOOSE = R++ src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' var XRANGEIDENTIFIER = R++ src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' var XRANGEPLAIN = R++ src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:' + src[PRERELEASE] + ')?' + src[BUILD] + '?' + ')?)?' var XRANGEPLAINLOOSE = R++ src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[PRERELEASELOOSE] + ')?' + src[BUILD] + '?' + ')?)?' var XRANGE = R++ src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' var XRANGELOOSE = R++ src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' // Coercion. // Extract anything that could conceivably be a part of a valid semver var COERCE = R++ src[COERCE] = '(?:^|[^\\d])' + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:$|[^\\d])' // Tilde ranges. // Meaning is "reasonably at or greater than" var LONETILDE = R++ src[LONETILDE] = '(?:~>?)' var TILDETRIM = R++ src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') safeRe[TILDETRIM] = new RegExp(makeSafeRe(src[TILDETRIM]), 'g') var tildeTrimReplace = '$1~' var TILDE = R++ src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' var TILDELOOSE = R++ src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' // Caret ranges. // Meaning is "at least and backwards compatible with" var LONECARET = R++ src[LONECARET] = '(?:\\^)' var CARETTRIM = R++ src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') safeRe[CARETTRIM] = new RegExp(makeSafeRe(src[CARETTRIM]), 'g') var caretTrimReplace = '$1^' var CARET = R++ src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' var CARETLOOSE = R++ src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' // A simple gt/lt/eq thing, or just "" to indicate "any version" var COMPARATORLOOSE = R++ src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' var COMPARATOR = R++ src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` var COMPARATORTRIM = R++ src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' // this one has to use the /g flag re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') safeRe[COMPARATORTRIM] = new RegExp(makeSafeRe(src[COMPARATORTRIM]), 'g') var comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. var HYPHENRANGE = R++ src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAIN] + ')' + '\\s*$' var HYPHENRANGELOOSE = R++ src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAINLOOSE] + ')' + '\\s*$' // Star ranges basically just allow anything at all. var STAR = R++ src[STAR] = '(<|>)?=?\\s*\\*' // Compile to actual regexp objects. // All are flag-free, unless they were created above with a flag. for (var i = 0; i < R; i++) { debug(i, src[i]) if (!re[i]) { re[i] = new RegExp(src[i]) // Replace all greedy whitespace to prevent regex dos issues. These regex are // used internally via the safeRe object since all inputs in this library get // normalized first to trim and collapse all extra whitespace. The original // regexes are exported for userland consumption and lower level usage. A // future breaking change could export the safer regex only with a note that // all input should have extra whitespace removed. safeRe[i] = new RegExp(makeSafeRe(src[i])) } } exports.parse = parse function parse (version, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (version instanceof SemVer) { return version } if (typeof version !== 'string') { return null } if (version.length > MAX_LENGTH) { return null } var r = options.loose ? safeRe[LOOSE] : safeRe[FULL] if (!r.test(version)) { return null } try { return new SemVer(version, options) } catch (er) { return null } } exports.valid = valid function valid (version, options) { var v = parse(version, options) return v ? v.version : null } exports.clean = clean function clean (version, options) { var s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } exports.SemVer = SemVer function SemVer (version, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (version instanceof SemVer) { if (version.loose === options.loose) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError('Invalid Version: ' + version) } if (version.length > MAX_LENGTH) { throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') } if (!(this instanceof SemVer)) { return new SemVer(version, options) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose var m = version.trim().match(options.loose ? safeRe[LOOSE] : safeRe[FULL]) if (!m) { throw new TypeError('Invalid Version: ' + version) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map(function (id) { if (/^[0-9]+$/.test(id)) { var num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } SemVer.prototype.format = function () { this.version = this.major + '.' + this.minor + '.' + this.patch if (this.prerelease.length) { this.version += '-' + this.prerelease.join('.') } return this.version } SemVer.prototype.toString = function () { return this.version } SemVer.prototype.compare = function (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return this.compareMain(other) || this.comparePre(other) } SemVer.prototype.compareMain = function (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) } SemVer.prototype.comparePre = function (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } var i = 0 do { var a = this.prerelease[i] var b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. SemVer.prototype.inc = function (release, identifier) { switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier) this.inc('pre', identifier) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier) } this.inc('pre', identifier) break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. case 'pre': if (this.prerelease.length === 0) { this.prerelease = [0] } else { var i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything this.prerelease.push(0) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 if (this.prerelease[0] === identifier) { if (isNaN(this.prerelease[1])) { this.prerelease = [identifier, 0] } } else { this.prerelease = [identifier, 0] } } break default: throw new Error('invalid increment argument: ' + release) } this.format() this.raw = this.version return this } exports.inc = inc function inc (version, release, loose, identifier) { if (typeof (loose) === 'string') { identifier = loose loose = undefined } try { return new SemVer(version, loose).inc(release, identifier).version } catch (er) { return null } } exports.diff = diff function diff (version1, version2) { if (eq(version1, version2)) { return null } else { var v1 = parse(version1) var v2 = parse(version2) var prefix = '' if (v1.prerelease.length || v2.prerelease.length) { prefix = 'pre' var defaultResult = 'prerelease' } for (var key in v1) { if (key === 'major' || key === 'minor' || key === 'patch') { if (v1[key] !== v2[key]) { return prefix + key } } } return defaultResult // may be undefined } } exports.compareIdentifiers = compareIdentifiers var numeric = /^[0-9]+$/ function compareIdentifiers (a, b) { var anum = numeric.test(a) var bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } exports.rcompareIdentifiers = rcompareIdentifiers function rcompareIdentifiers (a, b) { return compareIdentifiers(b, a) } exports.major = major function major (a, loose) { return new SemVer(a, loose).major } exports.minor = minor function minor (a, loose) { return new SemVer(a, loose).minor } exports.patch = patch function patch (a, loose) { return new SemVer(a, loose).patch } exports.compare = compare function compare (a, b, loose) { return new SemVer(a, loose).compare(new SemVer(b, loose)) } exports.compareLoose = compareLoose function compareLoose (a, b) { return compare(a, b, true) } exports.rcompare = rcompare function rcompare (a, b, loose) { return compare(b, a, loose) } exports.sort = sort function sort (list, loose) { return list.sort(function (a, b) { return exports.compare(a, b, loose) }) } exports.rsort = rsort function rsort (list, loose) { return list.sort(function (a, b) { return exports.rcompare(a, b, loose) }) } exports.gt = gt function gt (a, b, loose) { return compare(a, b, loose) > 0 } exports.lt = lt function lt (a, b, loose) { return compare(a, b, loose) < 0 } exports.eq = eq function eq (a, b, loose) { return compare(a, b, loose) === 0 } exports.neq = neq function neq (a, b, loose) { return compare(a, b, loose) !== 0 } exports.gte = gte function gte (a, b, loose) { return compare(a, b, loose) >= 0 } exports.lte = lte function lte (a, b, loose) { return compare(a, b, loose) <= 0 } exports.cmp = cmp function cmp (a, op, b, loose) { switch (op) { case '===': if (typeof a === 'object') a = a.version if (typeof b === 'object') b = b.version return a === b case '!==': if (typeof a === 'object') a = a.version if (typeof b === 'object') b = b.version return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError('Invalid operator: ' + op) } } exports.Comparator = Comparator function Comparator (comp, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } if (!(this instanceof Comparator)) { return new Comparator(comp, options) } comp = comp.trim().split(/\s+/).join(' ') debug('comparator', comp, options) this.options = options this.loose = !!options.loose this.parse(comp) if (this.semver === ANY) { this.value = '' } else { this.value = this.operator + this.semver.version } debug('comp', this) } var ANY = {} Comparator.prototype.parse = function (comp) { var r = this.options.loose ? safeRe[COMPARATORLOOSE] : safeRe[COMPARATOR] var m = comp.match(r) if (!m) { throw new TypeError('Invalid comparator: ' + comp) } this.operator = m[1] if (this.operator === '=') { this.operator = '' } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY } else { this.semver = new SemVer(m[2], this.options.loose) } } Comparator.prototype.toString = function () { return this.value } Comparator.prototype.test = function (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY) { return true } if (typeof version === 'string') { version = new SemVer(version, this.options) } return cmp(version, this.operator, this.semver, this.options) } Comparator.prototype.intersects = function (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } var rangeTmp if (this.operator === '') { rangeTmp = new Range(comp.value, options) return satisfies(this.value, rangeTmp, options) } else if (comp.operator === '') { rangeTmp = new Range(this.value, options) return satisfies(comp.semver, rangeTmp, options) } var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>') var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<') var sameSemVer = this.semver.version === comp.semver.version var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<=') var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && ((this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<')) var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && ((this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>')) return sameDirectionIncreasing || sameDirectionDecreasing || (sameSemVer && differentDirectionsInclusive) || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan } exports.Range = Range function Range (range, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (range instanceof Range) { if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { return range } else { return new Range(range.raw, options) } } if (range instanceof Comparator) { return new Range(range.value, options) } if (!(this instanceof Range)) { return new Range(range, options) } this.options = options this.loose = !!options.loose this.includePrerelease = !!options.includePrerelease // First reduce all whitespace as much as possible so we do not have to rely // on potentially slow regexes like \s*. This is then stored and used for // future error messages as well. this.raw = range .trim() .split(/\s+/) .join(' ') // First, split based on boolean or || this.set = this.raw.split('||').map(function (range) { return this.parseRange(range.trim()) }, this).filter(function (c) { // throw out any that are not relevant for whatever reason return c.length }) if (!this.set.length) { throw new TypeError('Invalid SemVer Range: ' + this.raw) } this.format() } Range.prototype.format = function () { this.range = this.set.map(function (comps) { return comps.join(' ').trim() }).join('||').trim() return this.range } Range.prototype.toString = function () { return this.range } Range.prototype.parseRange = function (range) { var loose = this.options.loose // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` var hr = loose ? safeRe[HYPHENRANGELOOSE] : safeRe[HYPHENRANGE] range = range.replace(hr, hyphenReplace) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(safeRe[COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range, safeRe[COMPARATORTRIM]) // `~ 1.2.3` => `~1.2.3` range = range.replace(safeRe[TILDETRIM], tildeTrimReplace) // `^ 1.2.3` => `^1.2.3` range = range.replace(safeRe[CARETTRIM], caretTrimReplace) // At this point, the range is completely trimmed and // ready to be split into comparators. var compRe = loose ? safeRe[COMPARATORLOOSE] : safeRe[COMPARATOR] var set = range.split(' ').map(function (comp) { return parseComparator(comp, this.options) }, this).join(' ').split(/\s+/) if (this.options.loose) { // in loose mode, throw out any that are not valid comparators set = set.filter(function (comp) { return !!comp.match(compRe) }) } set = set.map(function (comp) { return new Comparator(comp, this.options) }, this) return set } Range.prototype.intersects = function (range, options) { if (!(range instanceof Range)) { throw new TypeError('a Range is required') } return this.set.some(function (thisComparators) { return thisComparators.every(function (thisComparator) { return range.set.some(function (rangeComparators) { return rangeComparators.every(function (rangeComparator) { return thisComparator.intersects(rangeComparator, options) }) }) }) }) } // Mostly just for testing and legacy API reasons exports.toComparators = toComparators function toComparators (range, options) { return new Range(range, options).set.map(function (comp) { return comp.map(function (c) { return c.value }).join(' ').trim().split(' ') }) } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. function parseComparator (comp, options) { debug('comp', comp, options) comp = replaceCarets(comp, options) debug('caret', comp) comp = replaceTildes(comp, options) debug('tildes', comp) comp = replaceXRanges(comp, options) debug('xrange', comp) comp = replaceStars(comp, options) debug('stars', comp) return comp } function isX (id) { return !id || id.toLowerCase() === 'x' || id === '*' } // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 function replaceTildes (comp, options) { return comp.trim().split(/\s+/).map(function (comp) { return replaceTilde(comp, options) }).join(' ') } function replaceTilde (comp, options) { var r = options.loose ? safeRe[TILDELOOSE] : safeRe[TILDE] return comp.replace(r, function (_, M, m, p, pr) { debug('tilde', comp, _, M, m, p, pr) var ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' } else if (pr) { debug('replaceTilde pr', pr) ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0' } else { // ~1.2.3 == >=1.2.3 <1.3.0 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0' } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 // ^1.2.3 --> >=1.2.3 <2.0.0 // ^1.2.0 --> >=1.2.0 <2.0.0 function replaceCarets (comp, options) { return comp.trim().split(/\s+/).map(function (comp) { return replaceCaret(comp, options) }).join(' ') } function replaceCaret (comp, options) { debug('caret', comp, options) var r = options.loose ? safeRe[CARETLOOSE] : safeRe[CARET] return comp.replace(r, function (_, M, m, p, pr) { debug('caret', comp, _, M, m, p, pr) var ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' } else if (isX(p)) { if (M === '0') { ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' } else { ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + m + '.' + (+p + 1) } else { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0' } } else { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + (+M + 1) + '.0.0' } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1) } else { ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0' } } else { ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0' } } debug('caret return', ret) return ret }) } function replaceXRanges (comp, options) { debug('replaceXRanges', comp, options) return comp.split(/\s+/).map(function (comp) { return replaceXRange(comp, options) }).join(' ') } function replaceXRange (comp, options) { comp = comp.trim() var r = options.loose ? safeRe[XRANGELOOSE] : safeRe[XRANGE] return comp.replace(r, function (ret, gtlt, M, m, p, pr) { debug('xRange', comp, ret, gtlt, M, m, p, pr) var xM = isX(M) var xm = xM || isX(m) var xp = xm || isX(p) var anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0' } else { // nothing is forbidden ret = '*' } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0 } p = 0 if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 // >1.2.3 => >= 1.2.4 gtlt = '>=' if (xm) { M = +M + 1 m = 0 p = 0 } else { m = +m + 1 p = 0 } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<' if (xm) { M = +M + 1 } else { m = +m + 1 } } ret = gtlt + M + '.' + m + '.' + p } else if (xm) { ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' } else if (xp) { ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' } debug('xRange return', ret) return ret }) } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. function replaceStars (comp, options) { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp.trim().replace(safeRe[STAR], '') } // This function is passed to string.replace(safeRe[HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0 function hyphenReplace ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) { if (isX(fM)) { from = '' } else if (isX(fm)) { from = '>=' + fM + '.0.0' } else if (isX(fp)) { from = '>=' + fM + '.' + fm + '.0' } else { from = '>=' + from } if (isX(tM)) { to = '' } else if (isX(tm)) { to = '<' + (+tM + 1) + '.0.0' } else if (isX(tp)) { to = '<' + tM + '.' + (+tm + 1) + '.0' } else if (tpr) { to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr } else { to = '<=' + to } return (from + ' ' + to).trim() } // if ANY of the sets match ALL of its comparators, then pass Range.prototype.test = function (version) { if (!version) { return false } if (typeof version === 'string') { version = new SemVer(version, this.options) } for (var i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true } } return false } function testSet (set, version, options) { for (var i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === ANY) { continue } if (set[i].semver.prerelease.length > 0) { var allowed = set[i].semver if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } exports.satisfies = satisfies function satisfies (version, range, options) { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } exports.maxSatisfying = maxSatisfying function maxSatisfying (versions, range, options) { var max = null var maxSV = null try { var rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach(function (v) { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } exports.minSatisfying = minSatisfying function minSatisfying (versions, range, options) { var min = null var minSV = null try { var rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach(function (v) { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } exports.minVersion = minVersion function minVersion (range, loose) { range = new Range(range, loose) var minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (var i = 0; i < range.set.length; ++i) { var comparators = range.set[i] comparators.forEach(function (comparator) { // Clone to avoid manipulating the comparator's semver object. var compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!minver || gt(minver, compver)) { minver = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error('Unexpected operation: ' + comparator.operator) } }) } if (minver && range.test(minver)) { return minver } return null } exports.validRange = validRange function validRange (range, options) { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } // Determine if version is less than all the versions possible in the range exports.ltr = ltr function ltr (version, range, options) { return outside(version, range, '<', options) } // Determine if version is greater than all the versions possible in the range. exports.gtr = gtr function gtr (version, range, options) { return outside(version, range, '>', options) } exports.outside = outside function outside (version, range, hilo, options) { version = new SemVer(version, options) range = new Range(range, options) var gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisifes the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (var i = 0; i < range.set.length; ++i) { var comparators = range.set[i] var high = null var low = null comparators.forEach(function (comparator) { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } exports.prerelease = prerelease function prerelease (version, options) { var parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } exports.intersects = intersects function intersects (r1, r2, options) { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2) } exports.coerce = coerce function coerce (version) { if (version instanceof SemVer) { return version } if (typeof version !== 'string') { return null } var match = version.match(safeRe[COERCE]) if (match == null) { return null } return parse(match[1] + '.' + (match[2] || '0') + '.' + (match[3] || '0')) } /***/ }), /***/ 63307: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.encode = exports.parsePackageString = void 0; const debug = __webpack_require__(15158)('snyk:module'); const gitHost = __webpack_require__(11034); exports["default"] = parsePackageString; /** * Parses a string package id (name + optional version) to an object. * * This method used to be named `moduleToObject`. */ function parsePackageString(nameAndMaybeVersion, versionOrOptions, options) { if (!nameAndMaybeVersion) { throw new Error('requires string to parse into module'); } let version; if (versionOrOptions && !options && typeof versionOrOptions === 'object') { options = versionOrOptions; } else { version = versionOrOptions; } let str = nameAndMaybeVersion; // first, try the common case; there's no version, and it's a normal package name if (!version) { // foo, foo-bar, @foo/bar, com.example:test // none of these can be URLs, or versions const fastPath = /^(?:(?:[a-z-]+)|(?:@[a-z-]+\/[a-z-]+)|(?:[a-z-]+\.[.a-z-]+:[a-z-]+))$/; if (fastPath.test(str)) { return supported(str, { name: str, version: '*' }, options); } } if (version && str.lastIndexOf('@') < 1) { debug('appending version onto string'); str += '@' + version; } // first try with regular git urls const gitObject = looksLikeUrl(str); if (gitObject) { // then the string looks like a url, let's try to parse it return supported(str, fromGitObject(gitObject), options); } let parts = str.split('@'); if (str.indexOf('@') === 0) { // put the scoped package name back together parts = parts.slice(1); parts[0] = '@' + parts[0]; } // then as a backup, try pkg@giturl const maybeGitObject = parts[1] && looksLikeUrl(parts[1]); if (maybeGitObject) { // then the string looks like a url, let's try to parse it return supported(str, fromGitObject(maybeGitObject), options); } if (parts.length === 1) { // no version parts.push('*'); } const module = { name: parts[0], version: parts.slice(1).join('@'), }; return supported(str, module, options); } exports.parsePackageString = parsePackageString; // git host from URL function looksLikeUrl(str) { if (str.slice(-1) === '/') { // strip the trailing slash since we can't parse it properly anyway str = str.slice(0, -1); } if (str.toLowerCase().indexOf('://github.com/') !== -1 && str.indexOf('http') === 0) { // attempt to get better compat with our parser by stripping the github // and url parts // examples: // - https://github.com/Snyk/snyk/releases/tag/v1.14.2 // - https://github.com/Snyk/vulndb/tree/snapshots // - https://github.com/Snyk/snyk/commit/75477b18 const parts = str.replace(/https?:\/\/github.com\//, '').split('/'); str = parts.shift() + '/' + parts.shift(); if (parts.length) { str += '#' + parts.pop(); } } const obj = gitHost.fromUrl(str); return obj; } function fromGitObject(obj) { // debug('parsed from hosted-git-info'); /* istanbul ignore if */ if (!obj.project || !obj.user) { // this should never actually occur const error = new Error('not supported: failed to fully parse'); error.code = 501; throw error; } const module = { name: obj.project, version: obj.user + '/' + obj.project, }; if (obj.committish) { module.version += '#' + obj.committish; } return module; } function encode(name) { return name[0] + encodeURIComponent(name.slice(1)); } exports.encode = encode; function supported(str, module, options) { if (!options) { options = {}; } if (options.packageManager === 'maven') { if (str.indexOf(':') === -1) { throw new Error('invalid Maven package name: ' + str); } return module; } const protocolMatch = module.version.match(/^(https?:)|(git[:+])/i); if (protocolMatch || module.name.indexOf('://') !== -1) { // we don't support non-npm modules atm debug('not supported %s@%s (ext)', module.name, module.version); if (options.loose) { delete module.version; } else { debug('external module: ' + toString(module)); } } if (module.version === 'latest' || !module.version) { module.version = '*'; } debug('%s => { name: "%s", version: "%s" }', str, module.name, module.version); return module; } function toString(module) { return module.name + '@' + module.version; } //# sourceMappingURL=index.js.map /***/ }), /***/ 7320: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = resolvePkg; module.exports.sync = sync; var fs = __webpack_require__(91729); var path = __webpack_require__(71017); var debug = __webpack_require__(15158)('snyk:resolve'); function resolvePkg(name, basedir) { if (!basedir) { basedir = process.cwd(); } var filename = path.resolve(basedir, 'node_modules', name, 'package.json'); debug('%s: %s', name, filename); return fs.stat(filename).then(function (stat) { if (stat.isFile()) { return path.dirname(filename); } }).catch(function (error) { debug('%s: not found on %s (root? %s)', name, basedir, isRoot(basedir)); if (isRoot(basedir)) { debug('at root'); error = new Error('package not found ' + name); error.code = 'NO_PACKAGE_FOUND'; throw error; } }).then(function (dir) { if (dir) { debug('%s: FOUND AT %s', name, dir); return dir; } debug('%s: cycling down', name); return resolvePkg(name, path.resolve(basedir, '..')); }); } function sync(name, basedir) { if (!basedir) { basedir = process.cwd(); } var filename = path.resolve(basedir, 'node_modules', name, 'package.json'); debug('%s: %s', name, filename); var isFile = function (file) { var stat; try { stat = fs.statSync(file); } catch (error) { if (error && error.code === 'ENOENT') { return false; } } return stat.isFile() || stat.isFIFO(); }; if (isFile(filename)) { debug('%s: FOUND AT %s', name, filename); return path.dirname(filename); } if (isRoot(basedir)) { debug('%s: not found on %s (now at root)', name, filename); var error = new Error('package not found ' + name); error.code = 'NO_PACKAGE_FOUND'; throw error; } debug('%s: cycling down', name); return sync(name, path.resolve(basedir, '..')); } function isRoot(dir) { var parsed = parse(dir); return parsed.root === parsed.dir && !parsed.base; } // FIXME determine whether this would work properly on windows in 0.10 function parse(dir) { /* istanbul ignore else */ // jscs:disable requireEarlyReturn if (path.parse) { return path.parse(dir); } else { var split = dir.split(path.sep); var root = split[0] + path.sep; return { base: split[1], root: root, dir: dir, }; } // jscs:enable requireEarlyReturn } /***/ }), /***/ 44225: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.sbtDependencyGraphPluginNameNew = exports.sbtDependencyGraphPluginName = exports.sbtCoursierPluginName = void 0; exports.sbtCoursierPluginName = 'sbt-coursier'; exports.sbtDependencyGraphPluginName = 'sbt-dependency-graph'; exports.sbtDependencyGraphPluginNameNew = 'addDependencyTreePlugin'; //# sourceMappingURL=constants.js.map /***/ }), /***/ 1444: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildArgs = exports.inspect = void 0; const path = __webpack_require__(71017); const fs = __webpack_require__(57147); const semver = __webpack_require__(36625); const debugModule = __webpack_require__(15158); // To enable debugging output, run the CLI as `DEBUG=snyk-sbt-plugin snyk ...` const debug = debugModule('snyk-sbt-plugin'); const constants_1 = __webpack_require__(44225); const subProcess = __webpack_require__(98262); const parser = __webpack_require__(9237); const plugin_search_1 = __webpack_require__(37782); const version_1 = __webpack_require__(16478); const tmp = __webpack_require__(15743); tmp.setGracefulCleanup(); const packageFormatVersion = 'mvn:0.0.1'; async function inspect(root, targetFile, options) { if (!options) { options = { dev: false }; } const isCoursierPresent = await (0, plugin_search_1.isPluginInstalled)(root, targetFile, constants_1.sbtCoursierPluginName); const isSbtDependencyGraphPresent = await (0, plugin_search_1.isPluginInstalled)(root, targetFile, constants_1.sbtDependencyGraphPluginName); const isNewSbtDependencyGraphPresent = await (0, plugin_search_1.isPluginInstalled)(root, targetFile, constants_1.sbtDependencyGraphPluginNameNew); debug(`isCoursierPresent: ${isCoursierPresent}, isSbtDependencyGraphPresent: ${isSbtDependencyGraphPresent}, isNewSbtDependencyGraphPresent: ${isNewSbtDependencyGraphPresent}`); // If coursier is present, use it because it gives different results to sbt dependencyTree let result; if (isCoursierPresent) { try { options.useCoursier = true; result = await legacyInspect(root, targetFile, options); return result; } catch (err) { debug('Coursier failed with error: ', err); } } // TODO:Legacy path creates a large output that can cause RangeError in bigger projects // We would prefer to use plugin inspect by default but currently it requires sbt-dep-graph plugin if (isSbtDependencyGraphPresent) { try { debug('Applying plugin inspect'); result = await pluginInspect(root, targetFile, options); } catch (err) { debug('pluginInspect failed with error: ', err); } if (result) { result.package.packageFormatVersion = packageFormatVersion; return result; } } options.useCoursier = false; try { result = await legacyInspect(root, targetFile, options); return result; } catch (err) { const hintMsg = buildHintMessage(options); err.message = err.message + '\n' + hintMsg; throw new Error(err); } } exports.inspect = inspect; async function legacyInspect(root, targetFile, options) { const targetFilePath = path.dirname(path.resolve(root, targetFile)); if (!fs.existsSync(targetFilePath)) { debug(`build.sbt not found at location: ${targetFilePath}. This may result in no dependencies`); } const useCoursier = options.useCoursier; const sbtArgs = buildArgs(options.args, useCoursier); debug(`running command: sbt ${sbtArgs.join(' ')}`); const result = { sbtOutput: await subProcess.execute('sbt', sbtArgs, { cwd: targetFilePath, }), coursier: useCoursier, }; const packageName = path.basename(root); const packageVersion = '0.0.0'; const depTree = parser.parse(result.sbtOutput, packageName, packageVersion, result.coursier); depTree.packageFormatVersion = packageFormatVersion; return { plugin: { name: 'bundled:sbt', runtime: 'unknown', }, package: depTree, }; } async function injectSbtScript(sbtPluginPath, targetFolderPath) { try { // We could be running from a bundled CLI generated by `pkg`. // The Node filesystem in that case is not real: https://github.com/zeit/pkg#snapshot-filesystem // Copying the injectable script into a temp file. let projectFolderPath = path.resolve(targetFolderPath, 'project/'); debug(`injectSbtScript: injecting snyk sbt plugin "${sbtPluginPath}" in "${projectFolderPath}"`); if (!fs.existsSync(projectFolderPath)) { debug(`injectSbtScript: "${projectFolderPath}" does not exist`); projectFolderPath = path.resolve(targetFolderPath, '..', 'project/'); debug(`injectSbtScript: will try "${projectFolderPath}"`); } const tmpSbtPlugin = tmp.fileSync({ postfix: '-SnykSbtPlugin.scala', dir: projectFolderPath, }); fs.createReadStream(sbtPluginPath).pipe(fs.createWriteStream(tmpSbtPlugin.name)); debug(`successfully injected plugin at "${tmpSbtPlugin.name}"`); return { path: tmpSbtPlugin.name, remove: tmpSbtPlugin.removeCallback }; } catch (error) { error.message = error.message + '\n\n' + 'Failed to create a temporary file to host Snyk script for SBT build analysis.'; throw error; } } function generateSbtPluginPath(sbtVersion) { let pluginName = 'SnykSbtPlugin-1.2x.scala'; if (semver.lt(sbtVersion, '0.1.0')) { throw new Error('Snyk does not support sbt with version less than 0.1.0'); } if (semver.gte(sbtVersion, '0.1.0') && semver.lt(sbtVersion, '1.1.0')) { pluginName = 'SnykSbtPlugin-0.1x.scala'; } if (/index.[tj]s$/.test(__filename)) { debug('Applying ', pluginName); return path.join(__dirname, `../scala/${pluginName}`); } else { throw new Error(`Cannot locate ${pluginName} script`); } } async function pluginInspect(root, targetFile, options) { let injectedScript; try { const targetFolderPath = path.dirname(path.resolve(root, targetFile)); const sbtArgs = buildArgs(options.args, false, true); const sbtVersion = await (0, version_1.getSbtVersion)(root, targetFile); const sbtPluginPath = generateSbtPluginPath(sbtVersion); const packageName = path.basename(root); const packageVersion = '1.0.0'; injectedScript = await injectSbtScript(sbtPluginPath, targetFolderPath); debug('injectedScript.path: ' + injectedScript.path); debug('args passed to plugin inspect: ', sbtArgs.join(' ')); const stdout = await subProcess.execute('sbt', sbtArgs, { cwd: targetFolderPath, }); return { plugin: { name: 'snyk:sbt', runtime: 'unknown', meta: { versionBuildInfo: { metaBuildVersion: { sbtVersion, }, }, }, }, package: parser.parseSbtPluginResults(stdout, packageName, packageVersion), }; } catch (error) { debug('Failed to produce dependency tree with custom snyk plugin due to error: ' + error.message); return null; } finally { // in case of subProcess.execute failing, perform cleanup here, as putting it after `getInjectScriptPath` might // not be executed because of `sbt` failing if (injectedScript && injectedScript.remove) { try { injectedScript.remove(); debug(`Removed the snyk sbt plugin at '${injectedScript.path}'`); } catch (error) { // NOTE(alexmu): we don't want to kill the whole run because we can still fall back to the legacy // method, but at least tell the user to clean up after the CLI :(. // tslint:disable-next-line:no-console console.warn(`Failed to remove the snyk sbt plugin file at '${injectedScript.path}'`); } } } } function buildHintMessage(options) { const dgArgs = '`sbt ' + buildArgs(options.args, false).join(' ') + '`'; const csArgs = '`sbt ' + buildArgs(options.args, true).join(' ') + '`'; return ('\n\n' + 'Please make sure that the `sbt-dependency-graph` plugin ' + '(https://github.com/jrudolph/sbt-dependency-graph) is installed ' + 'globally or on the current project, and that ' + dgArgs + ' executes successfully on this project.\n\n' + 'Alternatively you can use `sbt-coursier` for dependency resolution ' + '(https://get-coursier.io/docs/sbt-coursier), in which case ensure ' + 'that the plugin is installed on the current project and that ' + csArgs + ' executes successfully on this project.\n\n' + 'For this project we guessed that you are using ' + (options.useCoursier ? 'sbt-coursier' : 'sbt-dependency-graph') + '.\n\n' + 'If the problem persists, collect the output of ' + dgArgs + ' or ' + csArgs + ' and contact support@snyk.io\n'); } function buildArgs(sbtArgs, isCoursierProject, isOutputGraph) { // force plain output so we don't have to parse colour codes let args = ['-Dsbt.log.noformat=true']; if (sbtArgs) { args = args.concat(sbtArgs); } if (isOutputGraph) { args.push('snykRenderTree'); // sbt-dependency-graph } else if (isCoursierProject) { args.push('coursierDependencyTree'); // coursier } else { // enhance sbt default output width from 40 chars to the max args.push('set asciiGraphWidth := 999999999'); args.push('dependencyTree'); // sbt native } return args; } exports.buildArgs = buildArgs; //# sourceMappingURL=index.js.map /***/ }), /***/ 9237: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseSbtPluginResults = exports.parse = void 0; const tabdown = __webpack_require__(856); function convertStrToTree(lines) { const newLines = lines .map((line) => { return line.replace(/\u001b\[0m/g, ''); }) .filter((line) => { if (line.indexOf('[info] ') === 0 && line.indexOf('+-') > -1) { return true; } let match = line.match(/\[info\]\s[\w_\.\-]+:[\w_\.\-]+:[\w_\.\-]+/); if (match && match[0].length === line.length) { return true; } match = line.match(/\[info\]\s[\w_\.\-]+:[\w_\.\-]+:[\w_\.\-]+\s\[S\]/); if (match && match[0].length === line.length) { return true; } return false; }) .map((line) => { return line .slice(7, line.length) // slice off '[info] ' .replace(' [S]', '') .replace(/\|/g, ' ') .replace('+-', '') .replace(/\s\s/g, '\t'); }); const tree = tabdown.parse(newLines, '\t'); return tree; } function convertCoursierStrToTree(lines) { const newLines = lines .map((line) => { return line.replace(/\u001b\[0m/g, ''); }) .filter((line) => { if (line.match(/[│├└].*/)) { return true; } if (line.match(/[^\s]+\s\(configurations.*/)) { return true; } return false; }) .map((line) => { return line .replace(/\│/g, ' ') .replace('├─ ', ' ') .replace('└─ ', ' ') .replace(/\s\s\s/g, '\t'); }); const tree = tabdown.parse(newLines, '\t'); return tree; } function walkInTree(toNode, fromNode) { if (fromNode.children && fromNode.children.length > 0) { for (const j of Object.keys(fromNode.children)) { const externalNode = getPackageNameAndVersion(fromNode.children[j].data); if (externalNode) { const newNode = { version: externalNode.version, name: externalNode.name, dependencies: [], }; toNode.dependencies.push(newNode); walkInTree(toNode.dependencies[toNode.dependencies.length - 1], fromNode.children[j]); } } } delete toNode.parent; } function getPackageNameAndVersion(packageDependency) { let version; let app; if (packageDependency.indexOf('(evicted by:') > -1) { return null; } if (packageDependency.indexOf('->') > -1) { return null; } const splited = packageDependency.split(':'); version = splited[splited.length - 1]; app = splited[0] + ':' + splited[1]; app = app.split('\t').join(''); app = app.trim(); version = version.trim(); return { name: app, version }; } function convertDepArrayToObject(depsArr) { if (!depsArr) { return null; } return depsArr.reduce((acc, dep) => { dep.dependencies = convertDepArrayToObject(dep.dependencies); acc[dep.name] = dep; return acc; }, {}); } function createSnykTree(rootTree, name, version) { let snykTree; let appTree; if (rootTree.root.length === 1) { // single build configuration // - use parsed package name and version // - use single project as root appTree = rootTree.root[0]; snykTree = getPackageNameAndVersion(Object.keys(appTree).pop()); snykTree.dependencies = []; } else { // multi build configuration // - use provided package name and version // - use complete tree as root appTree = rootTree; snykTree = { multiBuild: true, name, version, dependencies: [], }; } walkInTree(snykTree, appTree); snykTree.dependencies = convertDepArrayToObject(snykTree.dependencies); return snykTree; } function getProjectName(root) { const app = root.split(' ')[0].trim(); return { name: app }; } function createCoursierSnykTree(rootTree, name, version) { let snykTree; if (rootTree.root.length === 1) { // single build configuration // - use parsed package name - we don't have version in output // - use single project as root const appTree = rootTree.root[0]; snykTree = getProjectName(Object.keys(appTree).pop()); snykTree.dependencies = []; walkInTree(snykTree, appTree); } else { // multi build configuration // - use provided package name and version // - use complete tree as root const dependencies = rootTree.root.map((appTree) => { const subTree = getProjectName(Object.keys(appTree).pop()); subTree.dependencies = []; walkInTree(subTree, appTree); return subTree; }); snykTree = { multiBuild: true, name, version, dependencies, }; } snykTree.dependencies = convertDepArrayToObject(snykTree.dependencies); return snykTree; } function parse(text, name, version, isCoursier) { if (isCoursier) { const coursierRootTree = convertCoursierStrToTree(text); return createCoursierSnykTree(coursierRootTree, name, version); } const rootTree = convertStrToTree(text); return createSnykTree(rootTree, name, version); } exports.parse = parse; function parseSbtPluginResults(sbtOutput, packageName, packageVersion) { // remove all other output const outputStart = 'Snyk Output Start'; const outputEnd = 'Snyk Output End'; const sbtProjectOutput = sbtOutput.slice(sbtOutput.findIndex(line => line.indexOf(outputStart) != -1) + 1, sbtOutput.findIndex(line => line.indexOf(outputEnd) != -1)).join("\n"); const sbtOutputJson = JSON.parse(sbtProjectOutput); if (Object.keys(sbtOutputJson).length === 1) { const project = Object.keys(sbtOutputJson)[0]; return parseSbtPluginProjectResultToDepTree(project, sbtOutputJson[project]); } const depTree = { name: packageName, version: packageVersion, dependencies: {}, }; // iterating over different project for (const project of Object.keys(sbtOutputJson)) { depTree.dependencies[project] = parseSbtPluginProjectResultToDepTree(project, sbtOutputJson[project]); } return depTree; } exports.parseSbtPluginResults = parseSbtPluginResults; const PRODUCTION_SCOPES = ['compile', 'runtime', 'provided']; function parseSbtPluginProjectResultToDepTree(projectKey, sbtProjectOutput) { const pkgs = Object.keys(sbtProjectOutput.modules).filter((module) => { return sbtProjectOutput.modules[module].configurations.some((c) => PRODUCTION_SCOPES.includes(c)); }); const getDependenciesFor = (name) => { if (!sbtProjectOutput.dependencies[name]) { return { name, version: sbtProjectOutput.modules[name].version, }; } const dependencies = {}; for (const subDepName of sbtProjectOutput.dependencies[name]) { if (pkgs.indexOf(subDepName) > -1) { // dependency is in production configuration dependencies[subDepName] = getDependenciesFor(subDepName); } } return { name, version: sbtProjectOutput.modules[name].version, dependencies, }; }; return getDependenciesFor(projectKey); } //# sourceMappingURL=parse-sbt.js.map /***/ }), /***/ 37782: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isPluginInstalled = void 0; const path = __webpack_require__(71017); const fs = __webpack_require__(57147); const os = __webpack_require__(22037); const semver = __webpack_require__(36625); const version_1 = __webpack_require__(16478); async function isPluginInstalled(root, targetFile, plugin) { const searchGlobally = await searchGlobalFiles(root, targetFile, plugin); return searchGlobally || searchProjectFiles(root, targetFile, plugin); } exports.isPluginInstalled = isPluginInstalled; // search project and project/project relative to the root function searchProjectFiles(root, targetFile, plugin) { const basePath = path.dirname(path.resolve(root, targetFile)); const sbtFileList = sbtFiles(path.join(basePath, 'project')).concat(sbtFiles(path.join(basePath, 'project', 'project'))); const searchResults = sbtFileList.map((file) => { return searchWithFs(file, plugin); }); return searchResults.filter(Boolean).length > 0; } // search globally installed plugins (~/.sbt) async function searchGlobalFiles(root, targetFile, plugin) { const homedir = os.homedir(); const sbtVersion = await (0, version_1.getSbtVersion)(root, targetFile); // https://www.scala-sbt.org/1.x/docs/Using-Plugins.html#Global+plugins const pluginsPath = semver.lt(sbtVersion, '1.0.0') ? path.join(homedir, '.sbt', '0.13', 'plugins') : path.join(homedir, '.sbt', '1.0', 'plugins'); const sbtFileList = sbtFiles(pluginsPath); const searchResults = sbtFileList.map((file) => { return searchWithFs(file, plugin); }); return searchResults.filter(Boolean).length > 0; } // provide a list of .sbt files in the specified directory function sbtFiles(basePath) { if (fs.existsSync(basePath) && fs.lstatSync(basePath).isDirectory()) { return fs .readdirSync(basePath) .filter((fileName) => { return path.extname(fileName) === '.sbt'; }) .map((file) => { return path.join(basePath, file); }); } return []; } function searchWithFs(filename, word) { let buffer = fs.readFileSync(filename, { encoding: 'utf8' }); // remove single-line and multi-line comments const singleLineCommentPattern = /\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm; buffer = buffer.replace(singleLineCommentPattern, ''); return buffer.indexOf(word) > -1; } //# sourceMappingURL=plugin-search.js.map /***/ }), /***/ 98262: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.execute = void 0; const childProcess = __webpack_require__(32081); const treeKill = __webpack_require__(28); const debugModule = __webpack_require__(15158); const shescape_1 = __webpack_require__(79114); // To enable debugging output, run the CLI as `DEBUG=snyk-sbt-plugin snyk ...` const debugLogging = debugModule('snyk-sbt-plugin'); // Disabled by default, to set run the CLI as `PROC_TIMEOUT=100000 snyk ...` const TIMEOUT = process.env.PROC_TIMEOUT || '0'; const PROC_TIMEOUT = parseInt(TIMEOUT, 10); const execute = (command, args, options) => { const spawnOptions = { shell: true }; if (options && options.cwd) { spawnOptions.cwd = options.cwd; } args = (0, shescape_1.quoteAll)(args, spawnOptions); return new Promise((resolve, reject) => { const out = { stdout: [], stderr: '', }; let lastLine = ''; const proc = childProcess.spawn(command, args, spawnOptions); if (PROC_TIMEOUT !== 0) { setTimeout(kill(proc.pid, out), PROC_TIMEOUT); } proc.stdout.on('data', (data) => { const lines = data.toString().split('\n'); lines[0] = lastLine + lines[0]; lastLine = lines.pop(); lines.forEach((str) => { out.stdout.push(str); debugLogging(str); }); if (lastLine.includes('(q)uit')) { proc.stdin.write('q\n'); debugLogging('sbt is requiring input. Provided (q)uit signal. ' + 'There is no current workaround for this, see: https://stackoverflow.com/questions/21484166'); } }); proc.stderr.on('data', (data) => { out.stderr = out.stderr + data; data .toString() .split('\n') .forEach((str) => { debugLogging(str); }); }); proc.on('close', (code) => { out.stdout.push(lastLine); debugLogging(lastLine); lastLine = ''; if (code !== 0) { const fullCommand = command + ' ' + args.join(' '); const errorMessage = `>>> command: ${fullCommand} ` + (code ? `>>> exit code: ${code} ` : '') + `>>> stdout: ${out.stdout.join('\n')} ` + (out.stderr ? `>>> stderr: ${out.stderr}` : 'null'); return reject(new Error(errorMessage)); } if (out.stderr) { debugLogging('subprocess exit code = 0, but stderr was not empty: ' + out.stderr); } resolve(out.stdout); }); }); }; exports.execute = execute; function kill(id, out) { return () => { out.stderr = out.stderr + 'Process timed out. To set longer timeout run with `PROC_TIMEOUT=value_in_ms`\n'; return treeKill(id); }; } //# sourceMappingURL=sub-process.js.map /***/ }), /***/ 856: /***/ ((__unused_webpack_module, exports) => { exports.parse = (lines) => { function addHiddenProperties(scope, props) { for (const p of Object.keys(props)) { Object.defineProperty(scope, p, { enumerable: false, value: props[p] }); } } const TreeNode = function (data, depth) { this.parent = null; addHiddenProperties(this, { data, depth, parent: null, children: [], }); this[data || 'root'] = this.children; }; TreeNode.prototype.toString = function () { return JSON.stringify(this.children); }; const tree = new TreeNode(null, -1); const levels = [tree]; function countTabs(line) { let count = 0; for (const i of Object.keys(line)) { const ch = line[i]; if (ch === '\t') { count += 1; } else if (/[^\s]/.test(ch)) { return count; } } return -1; // no content } for (const i of Object.keys(lines)) { const line = lines[i]; const tabcount = countTabs(line); if (tabcount >= 0) { // then add node to tree while (tabcount - levels[levels.length - 1].depth <= 0) { levels.pop(); } const depth = levels.length - 1; const node = new TreeNode(line.substring(tabcount), depth); node.parent = levels[levels.length - 1]; node.parent.children.push(node); levels.push(node); } } return tree; }; exports.traverse = (tree, cb) => { function _traverse(node) { cb(node); for (const i of node.children.length) { _traverse(node.children[i]); } } for (const i of tree.children) { _traverse(tree.children[i]); } }; exports.print = (tree) => { exports.traverse(tree, (node) => { let str = ''; for (let i = 0; i < node.depth; i++) { str += '\t'; } str += node.data; }); }; exports.toJSON = (tree) => { return JSON.stringify(tree.children); }; //# sourceMappingURL=tabdown.js.map /***/ }), /***/ 16478: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getSbtVersion = void 0; const fs = __webpack_require__(57147); const path = __webpack_require__(71017); const subProcess = __webpack_require__(98262); const debugModule = __webpack_require__(15158); const debug = debugModule('snyk-sbt-plugin'); async function getSbtVersion(root, targetFile) { try { let buildPropsPath = path.join(root, path.dirname(targetFile), 'project/build.properties'); debug(`getSbtVersion: buildPropsPath=${buildPropsPath}`); if (!fs.existsSync(buildPropsPath)) { // NOTE(alexmu): We've seen this fail with the wrong path. // If the path we derived above doesn't exist, we try to build a more sensible one. // targetFile could be a path, so we need to call resolve() debug(`getSbtVersion: "${buildPropsPath}" doesn't exist`); const resolvedPath = path.resolve(root, targetFile); const targetFilePath = path.dirname(resolvedPath); buildPropsPath = path.resolve(targetFilePath, 'project/build.properties'); } if (!fs.existsSync(buildPropsPath)) { // NOTE(alexmu): Some projects don't have proper subproject structures, // e.g. don't have a project/ subfolder. This breaks snyk's assumptions // so we try to work around it here. debug(`getSbtVersion: "${buildPropsPath}" does not exist`); const resolvedPath = path.resolve(root, '..', targetFile); const targetFilePath = path.dirname(resolvedPath); buildPropsPath = path.resolve(targetFilePath, 'project/build.properties'); debug(`getSbtVersion: will try "${buildPropsPath}"`); } return fs .readFileSync(buildPropsPath, 'utf-8') .split('\n') // split into lines .find((line) => !!line.match(/sbt\.version\s*=/)) // locate version line .split(/=\s*/)[1] .trim(); // return only the version } catch (err) { debug('Failed to get sbt version from project/build.properties: ' + err.message); } try { const stdout = await subProcess.execute('sbt', ['--version'], {}); return stdout .find((line) => !!line.match(/sbt script version/)) .split(':')[1] .trim(); } catch (err) { debug('Failed to get sbt version sbt --version' + err.message); } // should never get here, but if it does // assume sbt 1.0.0 for the purposes of copying the correct scala script and global plugin search debug('Assuming sbt version is 1.0.0'); return '1.0.0'; } exports.getSbtVersion = getSbtVersion; //# sourceMappingURL=version.js.map /***/ }), /***/ 15743: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /*! * Tmp * * Copyright (c) 2011-2017 KARASZI Istvan * * MIT Licensed */ /* * Module dependencies. */ const fs = __webpack_require__(57147); const os = __webpack_require__(22037); const path = __webpack_require__(71017); const crypto = __webpack_require__(6113); const _c = fs.constants && os.constants ? { fs: fs.constants, os: os.constants } : process.binding('constants'); const rimraf = __webpack_require__(50984); /* * The working inner variables. */ const // the random characters to choose from RANDOM_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', TEMPLATE_PATTERN = /XXXXXX/, DEFAULT_TRIES = 3, CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR), EBADF = _c.EBADF || _c.os.errno.EBADF, ENOENT = _c.ENOENT || _c.os.errno.ENOENT, DIR_MODE = 448 /* 0o700 */, FILE_MODE = 384 /* 0o600 */, EXIT = 'exit', SIGINT = 'SIGINT', // this will hold the objects need to be removed on exit _removeObjects = []; var _gracefulCleanup = false; /** * Random name generator based on crypto. * Adapted from http://blog.tompawlak.org/how-to-generate-random-values-nodejs-javascript * * @param {number} howMany * @returns {string} the generated random name * @private */ function _randomChars(howMany) { var value = [], rnd = null; // make sure that we do not fail because we ran out of entropy try { rnd = crypto.randomBytes(howMany); } catch (e) { rnd = crypto.pseudoRandomBytes(howMany); } for (var i = 0; i < howMany; i++) { value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]); } return value.join(''); } /** * Checks whether the `obj` parameter is defined or not. * * @param {Object} obj * @returns {boolean} true if the object is undefined * @private */ function _isUndefined(obj) { return typeof obj === 'undefined'; } /** * Parses the function arguments. * * This function helps to have optional arguments. * * @param {(Options|Function)} options * @param {Function} callback * @returns {Array} parsed arguments * @private */ function _parseArguments(options, callback) { /* istanbul ignore else */ if (typeof options === 'function') { return [{}, options]; } /* istanbul ignore else */ if (_isUndefined(options)) { return [{}, callback]; } return [options, callback]; } /** * Generates a new temporary name. * * @param {Object} opts * @returns {string} the new random name according to opts * @private */ function _generateTmpName(opts) { const tmpDir = _getTmpDir(); // fail early on missing tmp dir if (isBlank(opts.dir) && isBlank(tmpDir)) { throw new Error('No tmp dir specified'); } /* istanbul ignore else */ if (!isBlank(opts.name)) { return path.join(opts.dir || tmpDir, opts.name); } // mkstemps like template // opts.template has already been guarded in tmpName() below /* istanbul ignore else */ if (opts.template) { var template = opts.template; // make sure that we prepend the tmp path if none was given /* istanbul ignore else */ if (path.basename(template) === template) template = path.join(opts.dir || tmpDir, template); return template.replace(TEMPLATE_PATTERN, _randomChars(6)); } // prefix and postfix const name = [ (isBlank(opts.prefix) ? 'tmp-' : opts.prefix), process.pid, _randomChars(12), (opts.postfix ? opts.postfix : '') ].join(''); return path.join(opts.dir || tmpDir, name); } /** * Gets a temporary file name. * * @param {(Options|tmpNameCallback)} options options or callback * @param {?tmpNameCallback} callback the callback function */ function tmpName(options, callback) { var args = _parseArguments(options, callback), opts = args[0], cb = args[1], tries = !isBlank(opts.name) ? 1 : opts.tries || DEFAULT_TRIES; /* istanbul ignore else */ if (isNaN(tries) || tries < 0) return cb(new Error('Invalid tries')); /* istanbul ignore else */ if (opts.template && !opts.template.match(TEMPLATE_PATTERN)) return cb(new Error('Invalid template provided')); (function _getUniqueName() { try { const name = _generateTmpName(opts); // check whether the path exists then retry if needed fs.stat(name, function (err) { /* istanbul ignore else */ if (!err) { /* istanbul ignore else */ if (tries-- > 0) return _getUniqueName(); return cb(new Error('Could not get a unique tmp filename, max tries reached ' + name)); } cb(null, name); }); } catch (err) { cb(err); } }()); } /** * Synchronous version of tmpName. * * @param {Object} options * @returns {string} the generated random name * @throws {Error} if the options are invalid or could not generate a filename */ function tmpNameSync(options) { var args = _parseArguments(options), opts = args[0], tries = !isBlank(opts.name) ? 1 : opts.tries || DEFAULT_TRIES; /* istanbul ignore else */ if (isNaN(tries) || tries < 0) throw new Error('Invalid tries'); /* istanbul ignore else */ if (opts.template && !opts.template.match(TEMPLATE_PATTERN)) throw new Error('Invalid template provided'); do { const name = _generateTmpName(opts); try { fs.statSync(name); } catch (e) { return name; } } while (tries-- > 0); throw new Error('Could not get a unique tmp filename, max tries reached'); } /** * Creates and opens a temporary file. * * @param {(Options|fileCallback)} options the config options or the callback function * @param {?fileCallback} callback */ function file(options, callback) { var args = _parseArguments(options, callback), opts = args[0], cb = args[1]; // gets a temporary filename tmpName(opts, function _tmpNameCreated(err, name) { /* istanbul ignore else */ if (err) return cb(err); // create and open the file fs.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err, fd) { /* istanbul ignore else */ if (err) return cb(err); if (opts.discardDescriptor) { return fs.close(fd, function _discardCallback(err) { /* istanbul ignore else */ if (err) { // Low probability, and the file exists, so this could be // ignored. If it isn't we certainly need to unlink the // file, and if that fails too its error is more // important. try { fs.unlinkSync(name); } catch (e) { if (!isENOENT(e)) { err = e; } } return cb(err); } cb(null, name, undefined, _prepareTmpFileRemoveCallback(name, -1, opts)); }); } /* istanbul ignore else */ if (opts.detachDescriptor) { return cb(null, name, fd, _prepareTmpFileRemoveCallback(name, -1, opts)); } cb(null, name, fd, _prepareTmpFileRemoveCallback(name, fd, opts)); }); }); } /** * Synchronous version of file. * * @param {Options} options * @returns {FileSyncObject} object consists of name, fd and removeCallback * @throws {Error} if cannot create a file */ function fileSync(options) { var args = _parseArguments(options), opts = args[0]; const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; const name = tmpNameSync(opts); var fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); /* istanbul ignore else */ if (opts.discardDescriptor) { fs.closeSync(fd); fd = undefined; } return { name: name, fd: fd, removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts) }; } /** * Creates a temporary directory. * * @param {(Options|dirCallback)} options the options or the callback function * @param {?dirCallback} callback */ function dir(options, callback) { var args = _parseArguments(options, callback), opts = args[0], cb = args[1]; // gets a temporary filename tmpName(opts, function _tmpNameCreated(err, name) { /* istanbul ignore else */ if (err) return cb(err); // create the directory fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err) { /* istanbul ignore else */ if (err) return cb(err); cb(null, name, _prepareTmpDirRemoveCallback(name, opts)); }); }); } /** * Synchronous version of dir. * * @param {Options} options * @returns {DirSyncObject} object consists of name and removeCallback * @throws {Error} if it cannot create a directory */ function dirSync(options) { var args = _parseArguments(options), opts = args[0]; const name = tmpNameSync(opts); fs.mkdirSync(name, opts.mode || DIR_MODE); return { name: name, removeCallback: _prepareTmpDirRemoveCallback(name, opts) }; } /** * Removes files asynchronously. * * @param {Object} fdPath * @param {Function} next * @private */ function _removeFileAsync(fdPath, next) { const _handler = function (err) { if (err && !isENOENT(err)) { // reraise any unanticipated error return next(err); } next(); } if (0 <= fdPath[0]) fs.close(fdPath[0], function (err) { fs.unlink(fdPath[1], _handler); }); else fs.unlink(fdPath[1], _handler); } /** * Removes files synchronously. * * @param {Object} fdPath * @private */ function _removeFileSync(fdPath) { try { if (0 <= fdPath[0]) fs.closeSync(fdPath[0]); } catch (e) { // reraise any unanticipated error if (!isEBADF(e) && !isENOENT(e)) throw e; } finally { try { fs.unlinkSync(fdPath[1]); } catch (e) { // reraise any unanticipated error if (!isENOENT(e)) throw e; } } } /** * Prepares the callback for removal of the temporary file. * * @param {string} name the path of the file * @param {number} fd file descriptor * @param {Object} opts * @returns {fileCallback} * @private */ function _prepareTmpFileRemoveCallback(name, fd, opts) { const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name]); const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], removeCallbackSync); if (!opts.keep) _removeObjects.unshift(removeCallbackSync); return removeCallback; } /** * Simple wrapper for rimraf. * * @param {string} dirPath * @param {Function} next * @private */ function _rimrafRemoveDirWrapper(dirPath, next) { rimraf(dirPath, next); } /** * Simple wrapper for rimraf.sync. * * @param {string} dirPath * @private */ function _rimrafRemoveDirSyncWrapper(dirPath, next) { try { return next(null, rimraf.sync(dirPath)); } catch (err) { return next(err); } } /** * Prepares the callback for removal of the temporary directory. * * @param {string} name * @param {Object} opts * @returns {Function} the callback * @private */ function _prepareTmpDirRemoveCallback(name, opts) { const removeFunction = opts.unsafeCleanup ? _rimrafRemoveDirWrapper : fs.rmdir.bind(fs); const removeFunctionSync = opts.unsafeCleanup ? _rimrafRemoveDirSyncWrapper : fs.rmdirSync.bind(fs); const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name); const removeCallback = _prepareRemoveCallback(removeFunction, name, removeCallbackSync); if (!opts.keep) _removeObjects.unshift(removeCallbackSync); return removeCallback; } /** * Creates a guarded function wrapping the removeFunction call. * * @param {Function} removeFunction * @param {Object} arg * @returns {Function} * @private */ function _prepareRemoveCallback(removeFunction, arg, cleanupCallbackSync) { var called = false; return function _cleanupCallback(next) { next = next || function () {}; if (!called) { const toRemove = cleanupCallbackSync || _cleanupCallback; const index = _removeObjects.indexOf(toRemove); /* istanbul ignore else */ if (index >= 0) _removeObjects.splice(index, 1); called = true; // sync? if (removeFunction.length === 1) { try { removeFunction(arg); return next(null); } catch (err) { // if no next is provided and since we are // in silent cleanup mode on process exit, // we will ignore the error return next(err); } } else return removeFunction(arg, next); } else return next(new Error('cleanup callback has already been called')); }; } /** * The garbage collector. * * @private */ function _garbageCollector() { /* istanbul ignore else */ if (!_gracefulCleanup) return; // the function being called removes itself from _removeObjects, // loop until _removeObjects is empty while (_removeObjects.length) { try { _removeObjects[0](); } catch (e) { // already removed? } } } /** * Helper for testing against EBADF to compensate changes made to Node 7.x under Windows. */ function isEBADF(error) { return isExpectedError(error, -EBADF, 'EBADF'); } /** * Helper for testing against ENOENT to compensate changes made to Node 7.x under Windows. */ function isENOENT(error) { return isExpectedError(error, -ENOENT, 'ENOENT'); } /** * Helper to determine whether the expected error code matches the actual code and errno, * which will differ between the supported node versions. * * - Node >= 7.0: * error.code {string} * error.errno {string|number} any numerical value will be negated * * - Node >= 6.0 < 7.0: * error.code {string} * error.errno {number} negated * * - Node >= 4.0 < 6.0: introduces SystemError * error.code {string} * error.errno {number} negated * * - Node >= 0.10 < 4.0: * error.code {number} negated * error.errno n/a */ function isExpectedError(error, code, errno) { return error.code === code || error.code === errno; } /** * Helper which determines whether a string s is blank, that is undefined, or empty or null. * * @private * @param {string} s * @returns {Boolean} true whether the string s is blank, false otherwise */ function isBlank(s) { return s === null || s === undefined || !s.trim(); } /** * Sets the graceful cleanup. */ function setGracefulCleanup() { _gracefulCleanup = true; } /** * Returns the currently configured tmp dir from os.tmpdir(). * * @private * @returns {string} the currently configured tmp dir */ function _getTmpDir() { return os.tmpdir(); } /** * If there are multiple different versions of tmp in place, make sure that * we recognize the old listeners. * * @param {Function} listener * @private * @returns {Boolean} true whether listener is a legacy listener */ function _is_legacy_listener(listener) { return (listener.name === '_exit' || listener.name === '_uncaughtExceptionThrown') && listener.toString().indexOf('_garbageCollector();') > -1; } /** * Safely install SIGINT listener. * * NOTE: this will only work on OSX and Linux. * * @private */ function _safely_install_sigint_listener() { const listeners = process.listeners(SIGINT); const existingListeners = []; for (let i = 0, length = listeners.length; i < length; i++) { const lstnr = listeners[i]; /* istanbul ignore else */ if (lstnr.name === '_tmp$sigint_listener') { existingListeners.push(lstnr); process.removeListener(SIGINT, lstnr); } } process.on(SIGINT, function _tmp$sigint_listener(doExit) { for (let i = 0, length = existingListeners.length; i < length; i++) { // let the existing listener do the garbage collection (e.g. jest sandbox) try { existingListeners[i](false); } catch (err) { // ignore } } try { // force the garbage collector even it is called again in the exit listener _garbageCollector(); } finally { if (!!doExit) { process.exit(0); } } }); } /** * Safely install process exit listener. * * @private */ function _safely_install_exit_listener() { const listeners = process.listeners(EXIT); // collect any existing listeners const existingListeners = []; for (let i = 0, length = listeners.length; i < length; i++) { const lstnr = listeners[i]; /* istanbul ignore else */ // TODO: remove support for legacy listeners once release 1.0.0 is out if (lstnr.name === '_tmp$safe_listener' || _is_legacy_listener(lstnr)) { // we must forget about the uncaughtException listener, hopefully it is ours if (lstnr.name !== '_uncaughtExceptionThrown') { existingListeners.push(lstnr); } process.removeListener(EXIT, lstnr); } } // TODO: what was the data parameter good for? process.addListener(EXIT, function _tmp$safe_listener(data) { for (let i = 0, length = existingListeners.length; i < length; i++) { // let the existing listener do the garbage collection (e.g. jest sandbox) try { existingListeners[i](data); } catch (err) { // ignore } } _garbageCollector(); }); } _safely_install_exit_listener(); _safely_install_sigint_listener(); /** * Configuration options. * * @typedef {Object} Options * @property {?number} tries the number of tries before give up the name generation * @property {?string} template the "mkstemp" like filename template * @property {?string} name fix name * @property {?string} dir the tmp directory to use * @property {?string} prefix prefix for the generated name * @property {?string} postfix postfix for the generated name * @property {?boolean} unsafeCleanup recursively removes the created temporary directory, even when it's not empty */ /** * @typedef {Object} FileSyncObject * @property {string} name the name of the file * @property {string} fd the file descriptor * @property {fileCallback} removeCallback the callback function to remove the file */ /** * @typedef {Object} DirSyncObject * @property {string} name the name of the directory * @property {fileCallback} removeCallback the callback function to remove the directory */ /** * @callback tmpNameCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name */ /** * @callback fileCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {number} fd the file descriptor * @param {cleanupCallback} fn the cleanup callback function */ /** * @callback dirCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {cleanupCallback} fn the cleanup callback function */ /** * Removes the temporary created file or directory. * * @callback cleanupCallback * @param {simpleCallback} [next] function to call after entry was removed */ /** * Callback function for function composition. * @see {@link https://github.com/raszi/node-tmp/issues/57|raszi/node-tmp#57} * * @callback simpleCallback */ // exporting all the needed methods // evaluate os.tmpdir() lazily, mainly for simplifying testing but it also will // allow users to reconfigure the temporary directory Object.defineProperty(module.exports, "tmpdir", ({ enumerable: true, configurable: false, get: function () { return _getTmpDir(); } })); module.exports.dir = dir; module.exports.dirSync = dirSync; module.exports.file = file; module.exports.fileSync = fileSync; module.exports.tmpName = tmpName; module.exports.tmpNameSync = tmpNameSync; module.exports.setGracefulCleanup = setGracefulCleanup; /***/ }), /***/ 76098: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.computeDepGraph = void 0; const dep_graph_1 = __webpack_require__(71479); const subprocess_1 = __webpack_require__(11512); const path = __webpack_require__(71017); const errors_1 = __webpack_require__(93127); const SWIFT_BUILD_FOLDER = '.build'; const SWIFT_PACKAGE_RESOLVED = 'Package.resolved'; async function computeDepGraph(root, targetFile, additionalArgs) { const args = ['package']; if (additionalArgs) { args.push(...additionalArgs); } args.push(...[ '--package-path', path.dirname(targetFile), 'show-dependencies', '--format', 'json', ]); try { const result = await (0, subprocess_1.execute)('swift', args, { cwd: root }); const depTree = JSON.parse(result); return convertToGraph(depTree); } catch (err) { const errAsString = err; throw new errors_1.SwiftError('Unable to generate dependency tree', errAsString); } } exports.computeDepGraph = computeDepGraph; function traverseTree(rootNode, builder, rootNodeId) { const childNodes = rootNode.dependencies; childNodes === null || childNodes === void 0 ? void 0 : childNodes.forEach((node) => { const { url, version } = node; const name = url .replace(/https:\/\//g, '') .replace(/http:\/\//g, '') .replace(/.git/g, ''); const parentName = rootNodeId || rootNode.url .replace(/https:\/\//g, '') .replace(/http:\/\//g, '') .replace(/.git/g, ''); const nodeId = `${name}@${version}`; const parentNodeId = `${parentName}@${rootNode.version}`; builder.addPkgNode({ name, version }, nodeId); builder.connectDep(rootNodeId || parentNodeId, nodeId); traverseTree(node, builder); }); } function convertToGraph(rootNode) { const { name, version } = rootNode; const depGraphBuilder = new dep_graph_1.DepGraphBuilder({ name: 'swift' }, { name, version }); traverseTree(rootNode, depGraphBuilder, depGraphBuilder.rootNodeId); return depGraphBuilder.build(); } //# sourceMappingURL=compute-depgraph.js.map /***/ }), /***/ 93127: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SwiftError = void 0; class SwiftError extends Error { constructor(message, swiftErrStack) { super(message); this.stack = swiftErrStack; } } exports.SwiftError = SwiftError; //# sourceMappingURL=errors.js.map /***/ }), /***/ 42939: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.inspect = void 0; const compute_depgraph_1 = __webpack_require__(76098); const lookpath_1 = __webpack_require__(77103); const path = __webpack_require__(71017); // eslint-disable-next-line @typescript-eslint/no-unused-vars async function inspect(root, targetFile, options) { const swiftPath = await (0, lookpath_1.lookpath)('swift'); //Review whether we should check for this or for xcode // const xctestPath = await lookpath('xctest'); const filename = targetFile.split(path.sep).slice(-1)[0]; if (filename !== 'Package.swift') { throw new Error(`${filename} is not supported by Swift Package Manager. Please provide with path to Package.swift`); } if (!swiftPath) { throw new Error('The "swift" command is not available on your system. To scan your dependencies in the CLI, you must ensure you have first installed the relevant package manager.'); } const depGraph = await (0, compute_depgraph_1.computeDepGraph)(root, targetFile, options === null || options === void 0 ? void 0 : options.args); if (!depGraph) { throw new Error('Failed to scan this Swift PM project.'); } return { plugin: { name: 'snyk-swiftpm-plugin', runtime: 'unknown', targetFile: `${pathToPosix(targetFile)}Package.swift`, }, dependencyGraph: depGraph, }; } exports.inspect = inspect; // we assume that swift considers folders as packages instead of manifest files function pathToPosix(fpath) { const parts = fpath.split(path.sep); parts.pop(); if (parts.length === 0) { return './'; } return parts.join(path.posix.sep); } //# sourceMappingURL=index.js.map /***/ }), /***/ 11512: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.execute = void 0; const child_process_1 = __webpack_require__(32081); function makeSpawnOptions(options) { const spawnOptions = { shell: false, env: Object.assign({}, process.env), }; if (options === null || options === void 0 ? void 0 : options.cwd) { spawnOptions.cwd = options.cwd; } if (options === null || options === void 0 ? void 0 : options.env) { spawnOptions.env = Object.assign(Object.assign({}, spawnOptions.env), options.env); } else { spawnOptions.env = Object.assign({}, spawnOptions.env); } // Before spawning an external process, we check if we need to // restore the system proxy configuration, which overrides the CLI internal proxy configuration. if (process.env.SNYK_SYSTEM_HTTP_PROXY !== undefined) { spawnOptions.env.HTTP_PROXY = process.env.SNYK_SYSTEM_HTTP_PROXY; } if (process.env.SNYK_SYSTEM_HTTPS_PROXY !== undefined) { spawnOptions.env.HTTPS_PROXY = process.env.SNYK_SYSTEM_HTTPS_PROXY; } if (process.env.SNYK_SYSTEM_NO_PROXY !== undefined) { spawnOptions.env.NO_PROXY = process.env.SNYK_SYSTEM_NO_PROXY; } return spawnOptions; } function execute(command, args, options) { const spawnOptions = makeSpawnOptions(options); return new Promise((resolve, reject) => { var _a, _b; let stdout = ''; let stderr = ''; const proc = (0, child_process_1.spawn)(command, args, spawnOptions); (_a = proc.stdout) === null || _a === void 0 ? void 0 : _a.on('data', (data) => { stdout = stdout + data; }); (_b = proc.stderr) === null || _b === void 0 ? void 0 : _b.on('data', (data) => { stderr = stderr + data; }); proc.on('close', (code) => { if (code !== 0) { return reject(stdout || stderr); } resolve(stdout || stderr); }); }); } exports.execute = execute; //# sourceMappingURL=subprocess.js.map /***/ }), /***/ 14402: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = tryRequire; const fsModule = __webpack_require__(57147); const util = __webpack_require__(73837); const path = __webpack_require__(71017); const debug = __webpack_require__(15158)('snyk:resolve:try-require'); const cloneDeep = __webpack_require__(83465); const LRU = __webpack_require__(28486); const options = { max: 100, maxAge: 1000 * 60 * 60 }; const cache = new LRU(options); const fs = { readFile: util.promisify(fsModule.readFile), stat: util.promisify(fsModule.stat), }; module.exports.cache = cache; // allows for a reset function tryRequire(filename) { const cached = cache.get(filename); if (cached) { const res = cloneDeep(cached); /* istanbul ignore else */ if (process.env.TAP) { res.__cached = true; } return Promise.resolve(res); } return fs .readFile(filename, 'utf8') .then(function (pkgStr) { let leadingBOM = ''; if (pkgStr && pkgStr[0] === '\ufeff') { // String starts with UTF BOM. Remove it so that JSON.parse doesn't // stumble, but remember it for later use. pkgStr = pkgStr.slice(1); leadingBOM = '\ufeff'; } const pkg = JSON.parse(pkgStr); pkg.leading = leadingBOM + pkgStr.match(/^(\s*){/)[1]; pkg.trailing = pkgStr.match(/}(\s*)$/)[1]; return pkg; }) .catch(function (e) { debug('tryRequire silently failing on %s', e.message); return null; }) .then(function (pkg) { if (!pkg) { return pkg; } // fixes potential issues later on if (!pkg.devDependencies) { pkg.devDependencies = {}; } if (!pkg.dependencies) { pkg.dependencies = {}; } if (!pkg.name) { pkg.name = path.basename(path.dirname(filename)); } pkg.__filename = filename; // test for npm-shrinkwrap and find a .snyk policy file whilst we're at it const dir = path.dirname(filename); const promises = [ fs.stat(path.resolve(dir, '.snyk')).catch(pass), fs.stat(path.resolve(dir, 'npm-shrinkwrap.json')).catch(pass), ]; return Promise.all(promises).then(function (res) { if (!pkg.snyk) { pkg.snyk = res[0].isFile(); } if (pkg.snyk) { pkg.snyk = dir; } if (res[1].isFile()) { pkg.shrinkwrap = true; } return pkg; }); }) .then(function (pkg) { cache.set(filename, pkg); return cloneDeep(pkg); }); } const pass = function () { return { isFile: function () { return false; }, }; }; /***/ }), /***/ 20406: /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { __webpack_require__(76252).install(); /***/ }), /***/ 76252: /***/ ((module, exports, __webpack_require__) => { /* module decorator */ module = __webpack_require__.nmd(module); var SourceMapConsumer = __webpack_require__(49125).SourceMapConsumer; var path = __webpack_require__(71017); var fs; try { fs = __webpack_require__(57147); if (!fs.existsSync || !fs.readFileSync) { // fs doesn't have all methods we need fs = null; } } catch (err) { /* nop */ } var bufferFrom = __webpack_require__(55420); /** * Requires a module which is protected against bundler minification. * * @param {NodeModule} mod * @param {string} request */ function dynamicRequire(mod, request) { return mod.require(request); } // Only install once if called multiple times var errorFormatterInstalled = false; var uncaughtShimInstalled = false; // If true, the caches are reset before a stack trace formatting operation var emptyCacheBetweenOperations = false; // Supports {browser, node, auto} var environment = "auto"; // Maps a file path to a string containing the file contents var fileContentsCache = {}; // Maps a file path to a source map for that file var sourceMapCache = {}; // Regex for detecting source maps var reSourceMap = /^data:application\/json[^,]+base64,/; // Priority list of retrieve handlers var retrieveFileHandlers = []; var retrieveMapHandlers = []; function isInBrowser() { if (environment === "browser") return true; if (environment === "node") return false; return ((typeof window !== 'undefined') && (typeof XMLHttpRequest === 'function') && !(window.require && window.module && window.process && window.process.type === "renderer")); } function hasGlobalProcessEventEmitter() { return ((typeof process === 'object') && (process !== null) && (typeof process.on === 'function')); } function globalProcessVersion() { if ((typeof process === 'object') && (process !== null)) { return process.version; } else { return ''; } } function globalProcessStderr() { if ((typeof process === 'object') && (process !== null)) { return process.stderr; } } function globalProcessExit(code) { if ((typeof process === 'object') && (process !== null) && (typeof process.exit === 'function')) { return process.exit(code); } } function handlerExec(list) { return function(arg) { for (var i = 0; i < list.length; i++) { var ret = list[i](arg); if (ret) { return ret; } } return null; }; } var retrieveFile = handlerExec(retrieveFileHandlers); retrieveFileHandlers.push(function(path) { // Trim the path to make sure there is no extra whitespace. path = path.trim(); if (/^file:/.test(path)) { // existsSync/readFileSync can't handle file protocol, but once stripped, it works path = path.replace(/file:\/\/\/(\w:)?/, function(protocol, drive) { return drive ? '' : // file:///C:/dir/file -> C:/dir/file '/'; // file:///root-dir/file -> /root-dir/file }); } if (path in fileContentsCache) { return fileContentsCache[path]; } var contents = ''; try { if (!fs) { // Use SJAX if we are in the browser var xhr = new XMLHttpRequest(); xhr.open('GET', path, /** async */ false); xhr.send(null); if (xhr.readyState === 4 && xhr.status === 200) { contents = xhr.responseText; } } else if (fs.existsSync(path)) { // Otherwise, use the filesystem contents = fs.readFileSync(path, 'utf8'); } } catch (er) { /* ignore any errors */ } return fileContentsCache[path] = contents; }); // Support URLs relative to a directory, but be careful about a protocol prefix // in case we are in the browser (i.e. directories may start with "http://" or "file:///") function supportRelativeURL(file, url) { if (!file) return url; var dir = path.dirname(file); var match = /^\w+:\/\/[^\/]*/.exec(dir); var protocol = match ? match[0] : ''; var startPath = dir.slice(protocol.length); if (protocol && /^\/\w\:/.test(startPath)) { // handle file:///C:/ paths protocol += '/'; return protocol + path.resolve(dir.slice(protocol.length), url).replace(/\\/g, '/'); } return protocol + path.resolve(dir.slice(protocol.length), url); } function retrieveSourceMapURL(source) { var fileData; if (isInBrowser()) { try { var xhr = new XMLHttpRequest(); xhr.open('GET', source, false); xhr.send(null); fileData = xhr.readyState === 4 ? xhr.responseText : null; // Support providing a sourceMappingURL via the SourceMap header var sourceMapHeader = xhr.getResponseHeader("SourceMap") || xhr.getResponseHeader("X-SourceMap"); if (sourceMapHeader) { return sourceMapHeader; } } catch (e) { } } // Get the URL of the source map fileData = retrieveFile(source); var re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg; // Keep executing the search to find the *last* sourceMappingURL to avoid // picking up sourceMappingURLs from comments, strings, etc. var lastMatch, match; while (match = re.exec(fileData)) lastMatch = match; if (!lastMatch) return null; return lastMatch[1]; }; // Can be overridden by the retrieveSourceMap option to install. Takes a // generated source filename; returns a {map, optional url} object, or null if // there is no source map. The map field may be either a string or the parsed // JSON object (ie, it must be a valid argument to the SourceMapConsumer // constructor). var retrieveSourceMap = handlerExec(retrieveMapHandlers); retrieveMapHandlers.push(function(source) { var sourceMappingURL = retrieveSourceMapURL(source); if (!sourceMappingURL) return null; // Read the contents of the source map var sourceMapData; if (reSourceMap.test(sourceMappingURL)) { // Support source map URL as a data url var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1); sourceMapData = bufferFrom(rawData, "base64").toString(); sourceMappingURL = source; } else { // Support source map URLs relative to the source URL sourceMappingURL = supportRelativeURL(source, sourceMappingURL); sourceMapData = retrieveFile(sourceMappingURL); } if (!sourceMapData) { return null; } return { url: sourceMappingURL, map: sourceMapData }; }); function mapSourcePosition(position) { var sourceMap = sourceMapCache[position.source]; if (!sourceMap) { // Call the (overrideable) retrieveSourceMap function to get the source map. var urlAndMap = retrieveSourceMap(position.source); if (urlAndMap) { sourceMap = sourceMapCache[position.source] = { url: urlAndMap.url, map: new SourceMapConsumer(urlAndMap.map) }; // Load all sources stored inline with the source map into the file cache // to pretend like they are already loaded. They may not exist on disk. if (sourceMap.map.sourcesContent) { sourceMap.map.sources.forEach(function(source, i) { var contents = sourceMap.map.sourcesContent[i]; if (contents) { var url = supportRelativeURL(sourceMap.url, source); fileContentsCache[url] = contents; } }); } } else { sourceMap = sourceMapCache[position.source] = { url: null, map: null }; } } // Resolve the source URL relative to the URL of the source map if (sourceMap && sourceMap.map && typeof sourceMap.map.originalPositionFor === 'function') { var originalPosition = sourceMap.map.originalPositionFor(position); // Only return the original position if a matching line was found. If no // matching line is found then we return position instead, which will cause // the stack trace to print the path and line for the compiled file. It is // better to give a precise location in the compiled file than a vague // location in the original file. if (originalPosition.source !== null) { originalPosition.source = supportRelativeURL( sourceMap.url, originalPosition.source); return originalPosition; } } return position; } // Parses code generated by FormatEvalOrigin(), a function inside V8: // https://code.google.com/p/v8/source/browse/trunk/src/messages.js function mapEvalOrigin(origin) { // Most eval() calls are in this format var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin); if (match) { var position = mapSourcePosition({ source: match[2], line: +match[3], column: match[4] - 1 }); return 'eval at ' + match[1] + ' (' + position.source + ':' + position.line + ':' + (position.column + 1) + ')'; } // Parse nested eval() calls using recursion match = /^eval at ([^(]+) \((.+)\)$/.exec(origin); if (match) { return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')'; } // Make sure we still return useful information if we didn't find anything return origin; } // This is copied almost verbatim from the V8 source code at // https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The // implementation of wrapCallSite() used to just forward to the actual source // code of CallSite.prototype.toString but unfortunately a new release of V8 // did something to the prototype chain and broke the shim. The only fix I // could find was copy/paste. function CallSiteToString() { var fileName; var fileLocation = ""; if (this.isNative()) { fileLocation = "native"; } else { fileName = this.getScriptNameOrSourceURL(); if (!fileName && this.isEval()) { fileLocation = this.getEvalOrigin(); fileLocation += ", "; // Expecting source position to follow. } if (fileName) { fileLocation += fileName; } else { // Source code does not originate from a file and is not native, but we // can still get the source position inside the source string, e.g. in // an eval string. fileLocation += ""; } var lineNumber = this.getLineNumber(); if (lineNumber != null) { fileLocation += ":" + lineNumber; var columnNumber = this.getColumnNumber(); if (columnNumber) { fileLocation += ":" + columnNumber; } } } var line = ""; var functionName = this.getFunctionName(); var addSuffix = true; var isConstructor = this.isConstructor(); var isMethodCall = !(this.isToplevel() || isConstructor); if (isMethodCall) { var typeName = this.getTypeName(); // Fixes shim to be backward compatable with Node v0 to v4 if (typeName === "[object Object]") { typeName = "null"; } var methodName = this.getMethodName(); if (functionName) { if (typeName && functionName.indexOf(typeName) != 0) { line += typeName + "."; } line += functionName; if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) { line += " [as " + methodName + "]"; } } else { line += typeName + "." + (methodName || ""); } } else if (isConstructor) { line += "new " + (functionName || ""); } else if (functionName) { line += functionName; } else { line += fileLocation; addSuffix = false; } if (addSuffix) { line += " (" + fileLocation + ")"; } return line; } function cloneCallSite(frame) { var object = {}; Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) { object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name]; }); object.toString = CallSiteToString; return object; } function wrapCallSite(frame, state) { // provides interface backward compatibility if (state === undefined) { state = { nextPosition: null, curPosition: null } } if(frame.isNative()) { state.curPosition = null; return frame; } // Most call sites will return the source file from getFileName(), but code // passed to eval() ending in "//# sourceURL=..." will return the source file // from getScriptNameOrSourceURL() instead var source = frame.getFileName() || frame.getScriptNameOrSourceURL(); if (source) { var line = frame.getLineNumber(); var column = frame.getColumnNumber() - 1; // Fix position in Node where some (internal) code is prepended. // See https://github.com/evanw/node-source-map-support/issues/36 // Header removed in node at ^10.16 || >=11.11.0 // v11 is not an LTS candidate, we can just test the one version with it. // Test node versions for: 10.16-19, 10.20+, 12-19, 20-99, 100+, or 11.11 var noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/; var headerLength = noHeader.test(globalProcessVersion()) ? 0 : 62; if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) { column -= headerLength; } var position = mapSourcePosition({ source: source, line: line, column: column }); state.curPosition = position; frame = cloneCallSite(frame); var originalFunctionName = frame.getFunctionName; frame.getFunctionName = function() { if (state.nextPosition == null) { return originalFunctionName(); } return state.nextPosition.name || originalFunctionName(); }; frame.getFileName = function() { return position.source; }; frame.getLineNumber = function() { return position.line; }; frame.getColumnNumber = function() { return position.column + 1; }; frame.getScriptNameOrSourceURL = function() { return position.source; }; return frame; } // Code called using eval() needs special handling var origin = frame.isEval() && frame.getEvalOrigin(); if (origin) { origin = mapEvalOrigin(origin); frame = cloneCallSite(frame); frame.getEvalOrigin = function() { return origin; }; return frame; } // If we get here then we were unable to change the source position return frame; } // This function is part of the V8 stack trace API, for more info see: // https://v8.dev/docs/stack-trace-api function prepareStackTrace(error, stack) { if (emptyCacheBetweenOperations) { fileContentsCache = {}; sourceMapCache = {}; } var name = error.name || 'Error'; var message = error.message || ''; var errorString = name + ": " + message; var state = { nextPosition: null, curPosition: null }; var processedStack = []; for (var i = stack.length - 1; i >= 0; i--) { processedStack.push('\n at ' + wrapCallSite(stack[i], state)); state.nextPosition = state.curPosition; } state.curPosition = state.nextPosition = null; return errorString + processedStack.reverse().join(''); } // Generate position and snippet of original source with pointer function getErrorSource(error) { var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack); if (match) { var source = match[1]; var line = +match[2]; var column = +match[3]; // Support the inline sourceContents inside the source map var contents = fileContentsCache[source]; // Support files on disk if (!contents && fs && fs.existsSync(source)) { try { contents = fs.readFileSync(source, 'utf8'); } catch (er) { contents = ''; } } // Format the line from the original source code like node does if (contents) { var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1]; if (code) { return source + ':' + line + '\n' + code + '\n' + new Array(column).join(' ') + '^'; } } } return null; } function printErrorAndExit (error) { var source = getErrorSource(error); // Ensure error is printed synchronously and not truncated var stderr = globalProcessStderr(); if (stderr && stderr._handle && stderr._handle.setBlocking) { stderr._handle.setBlocking(true); } if (source) { console.error(); console.error(source); } console.error(error.stack); globalProcessExit(1); } function shimEmitUncaughtException () { var origEmit = process.emit; process.emit = function (type) { if (type === 'uncaughtException') { var hasStack = (arguments[1] && arguments[1].stack); var hasListeners = (this.listeners(type).length > 0); if (hasStack && !hasListeners) { return printErrorAndExit(arguments[1]); } } return origEmit.apply(this, arguments); }; } var originalRetrieveFileHandlers = retrieveFileHandlers.slice(0); var originalRetrieveMapHandlers = retrieveMapHandlers.slice(0); exports.wrapCallSite = wrapCallSite; exports.getErrorSource = getErrorSource; exports.mapSourcePosition = mapSourcePosition; exports.retrieveSourceMap = retrieveSourceMap; exports.install = function(options) { options = options || {}; if (options.environment) { environment = options.environment; if (["node", "browser", "auto"].indexOf(environment) === -1) { throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}") } } // Allow sources to be found by methods other than reading the files // directly from disk. if (options.retrieveFile) { if (options.overrideRetrieveFile) { retrieveFileHandlers.length = 0; } retrieveFileHandlers.unshift(options.retrieveFile); } // Allow source maps to be found by methods other than reading the files // directly from disk. if (options.retrieveSourceMap) { if (options.overrideRetrieveSourceMap) { retrieveMapHandlers.length = 0; } retrieveMapHandlers.unshift(options.retrieveSourceMap); } // Support runtime transpilers that include inline source maps if (options.hookRequire && !isInBrowser()) { // Use dynamicRequire to avoid including in browser bundles var Module = dynamicRequire(module, 'module'); var $compile = Module.prototype._compile; if (!$compile.__sourceMapSupport) { Module.prototype._compile = function(content, filename) { fileContentsCache[filename] = content; sourceMapCache[filename] = undefined; return $compile.call(this, content, filename); }; Module.prototype._compile.__sourceMapSupport = true; } } // Configure options if (!emptyCacheBetweenOperations) { emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ? options.emptyCacheBetweenOperations : false; } // Install the error reformatter if (!errorFormatterInstalled) { errorFormatterInstalled = true; Error.prepareStackTrace = prepareStackTrace; } if (!uncaughtShimInstalled) { var installHandler = 'handleUncaughtExceptions' in options ? options.handleUncaughtExceptions : true; // Do not override 'uncaughtException' with our own handler in Node.js // Worker threads. Workers pass the error to the main thread as an event, // rather than printing something to stderr and exiting. try { // We need to use `dynamicRequire` because `require` on it's own will be optimized by WebPack/Browserify. var worker_threads = dynamicRequire(module, 'worker_threads'); if (worker_threads.isMainThread === false) { installHandler = false; } } catch(e) {} // Provide the option to not install the uncaught exception handler. This is // to support other uncaught exception handlers (in test frameworks, for // example). If this handler is not installed and there are no other uncaught // exception handlers, uncaught exceptions will be caught by node's built-in // exception handler and the process will still be terminated. However, the // generated JavaScript code will be shown above the stack trace instead of // the original source code. if (installHandler && hasGlobalProcessEventEmitter()) { uncaughtShimInstalled = true; shimEmitUncaughtException(); } } }; exports.resetRetrieveHandlers = function() { retrieveFileHandlers.length = 0; retrieveMapHandlers.length = 0; retrieveFileHandlers = originalRetrieveFileHandlers.slice(0); retrieveMapHandlers = originalRetrieveMapHandlers.slice(0); retrieveSourceMap = handlerExec(retrieveMapHandlers); retrieveFile = handlerExec(retrieveFileHandlers); } /***/ }), /***/ 78213: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var util = __webpack_require__(32728); var has = Object.prototype.hasOwnProperty; var hasNativeMap = typeof Map !== "undefined"; /** * A data structure which is a combination of an array and a set. Adding a new * member is O(1), testing for membership is O(1), and finding the index of an * element is O(1). Removing elements from the set is not supported. Only * strings are supported for membership. */ function ArraySet() { this._array = []; this._set = hasNativeMap ? new Map() : Object.create(null); } /** * Static method for creating ArraySet instances from an existing array. */ ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { var set = new ArraySet(); for (var i = 0, len = aArray.length; i < len; i++) { set.add(aArray[i], aAllowDuplicates); } return set; }; /** * Return how many unique items are in this ArraySet. If duplicates have been * added, than those do not count towards the size. * * @returns Number */ ArraySet.prototype.size = function ArraySet_size() { return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; }; /** * Add the given string to this set. * * @param String aStr */ ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { var sStr = hasNativeMap ? aStr : util.toSetString(aStr); var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); var idx = this._array.length; if (!isDuplicate || aAllowDuplicates) { this._array.push(aStr); } if (!isDuplicate) { if (hasNativeMap) { this._set.set(aStr, idx); } else { this._set[sStr] = idx; } } }; /** * Is the given string a member of this set? * * @param String aStr */ ArraySet.prototype.has = function ArraySet_has(aStr) { if (hasNativeMap) { return this._set.has(aStr); } else { var sStr = util.toSetString(aStr); return has.call(this._set, sStr); } }; /** * What is the index of the given string in the array? * * @param String aStr */ ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { if (hasNativeMap) { var idx = this._set.get(aStr); if (idx >= 0) { return idx; } } else { var sStr = util.toSetString(aStr); if (has.call(this._set, sStr)) { return this._set[sStr]; } } throw new Error('"' + aStr + '" is not in the set.'); }; /** * What is the element at the given index? * * @param Number aIdx */ ArraySet.prototype.at = function ArraySet_at(aIdx) { if (aIdx >= 0 && aIdx < this._array.length) { return this._array[aIdx]; } throw new Error('No element indexed by ' + aIdx); }; /** * Returns the array representation of this set (which has the proper indices * indicated by indexOf). Note that this is a copy of the internal array used * for storing the members so that no one can mess with internal state. */ ArraySet.prototype.toArray = function ArraySet_toArray() { return this._array.slice(); }; exports.I = ArraySet; /***/ }), /***/ 16400: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause * * Based on the Base 64 VLQ implementation in Closure Compiler: * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java * * Copyright 2011 The Closure Compiler Authors. All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ var base64 = __webpack_require__(67923); // A single base 64 digit can contain 6 bits of data. For the base 64 variable // length quantities we use in the source map spec, the first bit is the sign, // the next four bits are the actual value, and the 6th bit is the // continuation bit. The continuation bit tells us whether there are more // digits in this value following this digit. // // Continuation // | Sign // | | // V V // 101011 var VLQ_BASE_SHIFT = 5; // binary: 100000 var VLQ_BASE = 1 << VLQ_BASE_SHIFT; // binary: 011111 var VLQ_BASE_MASK = VLQ_BASE - 1; // binary: 100000 var VLQ_CONTINUATION_BIT = VLQ_BASE; /** * Converts from a two-complement value to a value where the sign bit is * placed in the least significant bit. For example, as decimals: * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) */ function toVLQSigned(aValue) { return aValue < 0 ? ((-aValue) << 1) + 1 : (aValue << 1) + 0; } /** * Converts to a two-complement value from a value where the sign bit is * placed in the least significant bit. For example, as decimals: * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 */ function fromVLQSigned(aValue) { var isNegative = (aValue & 1) === 1; var shifted = aValue >> 1; return isNegative ? -shifted : shifted; } /** * Returns the base 64 VLQ encoded value. */ exports.encode = function base64VLQ_encode(aValue) { var encoded = ""; var digit; var vlq = toVLQSigned(aValue); do { digit = vlq & VLQ_BASE_MASK; vlq >>>= VLQ_BASE_SHIFT; if (vlq > 0) { // There are still more digits in this value, so we must make sure the // continuation bit is marked. digit |= VLQ_CONTINUATION_BIT; } encoded += base64.encode(digit); } while (vlq > 0); return encoded; }; /** * Decodes the next base 64 VLQ value from the given string and returns the * value and the rest of the string via the out parameter. */ exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { var strLen = aStr.length; var result = 0; var shift = 0; var continuation, digit; do { if (aIndex >= strLen) { throw new Error("Expected more digits in base 64 VLQ value."); } digit = base64.decode(aStr.charCodeAt(aIndex++)); if (digit === -1) { throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); } continuation = !!(digit & VLQ_CONTINUATION_BIT); digit &= VLQ_BASE_MASK; result = result + (digit << shift); shift += VLQ_BASE_SHIFT; } while (continuation); aOutParam.value = fromVLQSigned(result); aOutParam.rest = aIndex; }; /***/ }), /***/ 67923: /***/ ((__unused_webpack_module, exports) => { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); /** * Encode an integer in the range of 0 to 63 to a single base 64 digit. */ exports.encode = function (number) { if (0 <= number && number < intToCharMap.length) { return intToCharMap[number]; } throw new TypeError("Must be between 0 and 63: " + number); }; /** * Decode a single base 64 character code digit to an integer. Returns -1 on * failure. */ exports.decode = function (charCode) { var bigA = 65; // 'A' var bigZ = 90; // 'Z' var littleA = 97; // 'a' var littleZ = 122; // 'z' var zero = 48; // '0' var nine = 57; // '9' var plus = 43; // '+' var slash = 47; // '/' var littleOffset = 26; var numberOffset = 52; // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ if (bigA <= charCode && charCode <= bigZ) { return (charCode - bigA); } // 26 - 51: abcdefghijklmnopqrstuvwxyz if (littleA <= charCode && charCode <= littleZ) { return (charCode - littleA + littleOffset); } // 52 - 61: 0123456789 if (zero <= charCode && charCode <= nine) { return (charCode - zero + numberOffset); } // 62: + if (charCode == plus) { return 62; } // 63: / if (charCode == slash) { return 63; } // Invalid base64 digit. return -1; }; /***/ }), /***/ 9216: /***/ ((__unused_webpack_module, exports) => { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ exports.GREATEST_LOWER_BOUND = 1; exports.LEAST_UPPER_BOUND = 2; /** * Recursive implementation of binary search. * * @param aLow Indices here and lower do not contain the needle. * @param aHigh Indices here and higher do not contain the needle. * @param aNeedle The element being searched for. * @param aHaystack The non-empty array being searched. * @param aCompare Function which takes two elements and returns -1, 0, or 1. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. */ function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { // This function terminates when one of the following is true: // // 1. We find the exact element we are looking for. // // 2. We did not find the exact element, but we can return the index of // the next-closest element. // // 3. We did not find the exact element, and there is no next-closest // element than the one we are searching for, so we return -1. var mid = Math.floor((aHigh - aLow) / 2) + aLow; var cmp = aCompare(aNeedle, aHaystack[mid], true); if (cmp === 0) { // Found the element we are looking for. return mid; } else if (cmp > 0) { // Our needle is greater than aHaystack[mid]. if (aHigh - mid > 1) { // The element is in the upper half. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); } // The exact needle element was not found in this haystack. Determine if // we are in termination case (3) or (2) and return the appropriate thing. if (aBias == exports.LEAST_UPPER_BOUND) { return aHigh < aHaystack.length ? aHigh : -1; } else { return mid; } } else { // Our needle is less than aHaystack[mid]. if (mid - aLow > 1) { // The element is in the lower half. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); } // we are in termination case (3) or (2) and return the appropriate thing. if (aBias == exports.LEAST_UPPER_BOUND) { return mid; } else { return aLow < 0 ? -1 : aLow; } } } /** * This is an implementation of binary search which will always try and return * the index of the closest element if there is no exact hit. This is because * mappings between original and generated line/col pairs are single points, * and there is an implicit region between each of them, so a miss just means * that you aren't on the very start of a region. * * @param aNeedle The element you are looking for. * @param aHaystack The array that is being searched. * @param aCompare A function which takes the needle and an element in the * array and returns -1, 0, or 1 depending on whether the needle is less * than, equal to, or greater than the element, respectively. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. */ exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { if (aHaystack.length === 0) { return -1; } var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare, aBias || exports.GREATEST_LOWER_BOUND); if (index < 0) { return -1; } // We have found either the exact element, or the next-closest element than // the one we are searching for. However, there may be more than one such // element. Make sure we always return the smallest of these. while (index - 1 >= 0) { if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { break; } --index; } return index; }; /***/ }), /***/ 21188: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2014 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var util = __webpack_require__(32728); /** * Determine whether mappingB is after mappingA with respect to generated * position. */ function generatedPositionAfter(mappingA, mappingB) { // Optimized for most common case var lineA = mappingA.generatedLine; var lineB = mappingB.generatedLine; var columnA = mappingA.generatedColumn; var columnB = mappingB.generatedColumn; return lineB > lineA || lineB == lineA && columnB >= columnA || util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; } /** * A data structure to provide a sorted view of accumulated mappings in a * performance conscious manner. It trades a neglibable overhead in general * case for a large speedup in case of mappings being added in order. */ function MappingList() { this._array = []; this._sorted = true; // Serves as infimum this._last = {generatedLine: -1, generatedColumn: 0}; } /** * Iterate through internal items. This method takes the same arguments that * `Array.prototype.forEach` takes. * * NOTE: The order of the mappings is NOT guaranteed. */ MappingList.prototype.unsortedForEach = function MappingList_forEach(aCallback, aThisArg) { this._array.forEach(aCallback, aThisArg); }; /** * Add the given source mapping. * * @param Object aMapping */ MappingList.prototype.add = function MappingList_add(aMapping) { if (generatedPositionAfter(this._last, aMapping)) { this._last = aMapping; this._array.push(aMapping); } else { this._sorted = false; this._array.push(aMapping); } }; /** * Returns the flat, sorted array of mappings. The mappings are sorted by * generated position. * * WARNING: This method returns internal data without copying, for * performance. The return value must NOT be mutated, and should be treated as * an immutable borrow. If you want to take ownership, you must make your own * copy. */ MappingList.prototype.toArray = function MappingList_toArray() { if (!this._sorted) { this._array.sort(util.compareByGeneratedPositionsInflated); this._sorted = true; } return this._array; }; exports.H = MappingList; /***/ }), /***/ 22826: /***/ ((__unused_webpack_module, exports) => { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ // It turns out that some (most?) JavaScript engines don't self-host // `Array.prototype.sort`. This makes sense because C++ will likely remain // faster than JS when doing raw CPU-intensive sorting. However, when using a // custom comparator function, calling back and forth between the VM's C++ and // JIT'd JS is rather slow *and* loses JIT type information, resulting in // worse generated code for the comparator function than would be optimal. In // fact, when sorting with a comparator, these costs outweigh the benefits of // sorting in C++. By using our own JS-implemented Quick Sort (below), we get // a ~3500ms mean speed-up in `bench/bench.html`. /** * Swap the elements indexed by `x` and `y` in the array `ary`. * * @param {Array} ary * The array. * @param {Number} x * The index of the first item. * @param {Number} y * The index of the second item. */ function swap(ary, x, y) { var temp = ary[x]; ary[x] = ary[y]; ary[y] = temp; } /** * Returns a random integer within the range `low .. high` inclusive. * * @param {Number} low * The lower bound on the range. * @param {Number} high * The upper bound on the range. */ function randomIntInRange(low, high) { return Math.round(low + (Math.random() * (high - low))); } /** * The Quick Sort algorithm. * * @param {Array} ary * An array to sort. * @param {function} comparator * Function to use to compare two items. * @param {Number} p * Start index of the array * @param {Number} r * End index of the array */ function doQuickSort(ary, comparator, p, r) { // If our lower bound is less than our upper bound, we (1) partition the // array into two pieces and (2) recurse on each half. If it is not, this is // the empty array and our base case. if (p < r) { // (1) Partitioning. // // The partitioning chooses a pivot between `p` and `r` and moves all // elements that are less than or equal to the pivot to the before it, and // all the elements that are greater than it after it. The effect is that // once partition is done, the pivot is in the exact place it will be when // the array is put in sorted order, and it will not need to be moved // again. This runs in O(n) time. // Always choose a random pivot so that an input array which is reverse // sorted does not cause O(n^2) running time. var pivotIndex = randomIntInRange(p, r); var i = p - 1; swap(ary, pivotIndex, r); var pivot = ary[r]; // Immediately after `j` is incremented in this loop, the following hold // true: // // * Every element in `ary[p .. i]` is less than or equal to the pivot. // // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. for (var j = p; j < r; j++) { if (comparator(ary[j], pivot) <= 0) { i += 1; swap(ary, i, j); } } swap(ary, i + 1, j); var q = i + 1; // (2) Recurse on each half. doQuickSort(ary, comparator, p, q - 1); doQuickSort(ary, comparator, q + 1, r); } } /** * Sort the given array in-place with the given comparator function. * * @param {Array} ary * An array to sort. * @param {function} comparator * Function to use to compare two items. */ exports.U = function (ary, comparator) { doQuickSort(ary, comparator, 0, ary.length - 1); }; /***/ }), /***/ 76771: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { var __webpack_unused_export__; /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var util = __webpack_require__(32728); var binarySearch = __webpack_require__(9216); var ArraySet = __webpack_require__(78213)/* .ArraySet */ .I; var base64VLQ = __webpack_require__(16400); var quickSort = __webpack_require__(22826)/* .quickSort */ .U; function SourceMapConsumer(aSourceMap, aSourceMapURL) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = util.parseSourceMapInput(aSourceMap); } return sourceMap.sections != null ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); } SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); } /** * The version of the source mapping spec that we are consuming. */ SourceMapConsumer.prototype._version = 3; // `__generatedMappings` and `__originalMappings` are arrays that hold the // parsed mapping coordinates from the source map's "mappings" attribute. They // are lazily instantiated, accessed via the `_generatedMappings` and // `_originalMappings` getters respectively, and we only parse the mappings // and create these arrays once queried for a source location. We jump through // these hoops because there can be many thousands of mappings, and parsing // them is expensive, so we only want to do it if we must. // // Each object in the arrays is of the form: // // { // generatedLine: The line number in the generated code, // generatedColumn: The column number in the generated code, // source: The path to the original source file that generated this // chunk of code, // originalLine: The line number in the original source that // corresponds to this chunk of generated code, // originalColumn: The column number in the original source that // corresponds to this chunk of generated code, // name: The name of the original symbol which generated this chunk of // code. // } // // All properties except for `generatedLine` and `generatedColumn` can be // `null`. // // `_generatedMappings` is ordered by the generated positions. // // `_originalMappings` is ordered by the original positions. SourceMapConsumer.prototype.__generatedMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { configurable: true, enumerable: true, get: function () { if (!this.__generatedMappings) { this._parseMappings(this._mappings, this.sourceRoot); } return this.__generatedMappings; } }); SourceMapConsumer.prototype.__originalMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { configurable: true, enumerable: true, get: function () { if (!this.__originalMappings) { this._parseMappings(this._mappings, this.sourceRoot); } return this.__originalMappings; } }); SourceMapConsumer.prototype._charIsMappingSeparator = function SourceMapConsumer_charIsMappingSeparator(aStr, index) { var c = aStr.charAt(index); return c === ";" || c === ","; }; /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { throw new Error("Subclasses must implement _parseMappings"); }; SourceMapConsumer.GENERATED_ORDER = 1; SourceMapConsumer.ORIGINAL_ORDER = 2; SourceMapConsumer.GREATEST_LOWER_BOUND = 1; SourceMapConsumer.LEAST_UPPER_BOUND = 2; /** * Iterate over each mapping between an original source/line/column and a * generated line/column in this source map. * * @param Function aCallback * The function that is called with each mapping. * @param Object aContext * Optional. If specified, this object will be the value of `this` every * time that `aCallback` is called. * @param aOrder * Either `SourceMapConsumer.GENERATED_ORDER` or * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to * iterate over the mappings sorted by the generated file's line/column * order or the original's source/line/column order, respectively. Defaults to * `SourceMapConsumer.GENERATED_ORDER`. */ SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { var context = aContext || null; var order = aOrder || SourceMapConsumer.GENERATED_ORDER; var mappings; switch (order) { case SourceMapConsumer.GENERATED_ORDER: mappings = this._generatedMappings; break; case SourceMapConsumer.ORIGINAL_ORDER: mappings = this._originalMappings; break; default: throw new Error("Unknown order of iteration."); } var sourceRoot = this.sourceRoot; mappings.map(function (mapping) { var source = mapping.source === null ? null : this._sources.at(mapping.source); source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); return { source: source, generatedLine: mapping.generatedLine, generatedColumn: mapping.generatedColumn, originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: mapping.name === null ? null : this._names.at(mapping.name) }; }, this).forEach(aCallback, context); }; /** * Returns all generated line and column information for the original source, * line, and column provided. If no column is provided, returns all mappings * corresponding to a either the line we are searching for or the next * closest line that has any mappings. Otherwise, returns all mappings * corresponding to the given line and either the column we are searching for * or the next closest column that has any offsets. * * The only argument is an object with the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. The line number is 1-based. * - column: Optional. the column number in the original source. * The column number is 0-based. * * and an array of objects is returned, each with the following properties: * * - line: The line number in the generated source, or null. The * line number is 1-based. * - column: The column number in the generated source, or null. * The column number is 0-based. */ SourceMapConsumer.prototype.allGeneratedPositionsFor = function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { var line = util.getArg(aArgs, 'line'); // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping // returns the index of the closest mapping less than the needle. By // setting needle.originalColumn to 0, we thus find the last mapping for // the given line, provided such a mapping exists. var needle = { source: util.getArg(aArgs, 'source'), originalLine: line, originalColumn: util.getArg(aArgs, 'column', 0) }; needle.source = this._findSourceIndex(needle.source); if (needle.source < 0) { return []; } var mappings = []; var index = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, binarySearch.LEAST_UPPER_BOUND); if (index >= 0) { var mapping = this._originalMappings[index]; if (aArgs.column === undefined) { var originalLine = mapping.originalLine; // Iterate until either we run out of mappings, or we run into // a mapping for a different line than the one we found. Since // mappings are sorted, this is guaranteed to find all mappings for // the line we found. while (mapping && mapping.originalLine === originalLine) { mappings.push({ line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null), lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) }); mapping = this._originalMappings[++index]; } } else { var originalColumn = mapping.originalColumn; // Iterate until either we run out of mappings, or we run into // a mapping for a different line than the one we were searching for. // Since mappings are sorted, this is guaranteed to find all mappings for // the line we are searching for. while (mapping && mapping.originalLine === line && mapping.originalColumn == originalColumn) { mappings.push({ line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null), lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) }); mapping = this._originalMappings[++index]; } } } return mappings; }; exports.SourceMapConsumer = SourceMapConsumer; /** * A BasicSourceMapConsumer instance represents a parsed source map which we can * query for information about the original file positions by giving it a file * position in the generated source. * * The first parameter is the raw source map (either as a JSON string, or * already parsed to an object). According to the spec, source maps have the * following attributes: * * - version: Which version of the source map spec this map is following. * - sources: An array of URLs to the original source files. * - names: An array of identifiers which can be referrenced by individual mappings. * - sourceRoot: Optional. The URL root from which all sources are relative. * - sourcesContent: Optional. An array of contents of the original source files. * - mappings: A string of base64 VLQs which contain the actual mappings. * - file: Optional. The generated file this source map is associated with. * * Here is an example source map, taken from the source map spec[0]: * * { * version : 3, * file: "out.js", * sourceRoot : "", * sources: ["foo.js", "bar.js"], * names: ["src", "maps", "are", "fun"], * mappings: "AA,AB;;ABCDE;" * } * * The second parameter, if given, is a string whose value is the URL * at which the source map was found. This URL is used to compute the * sources array. * * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# */ function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = util.parseSourceMapInput(aSourceMap); } var version = util.getArg(sourceMap, 'version'); var sources = util.getArg(sourceMap, 'sources'); // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which // requires the array) to play nice here. var names = util.getArg(sourceMap, 'names', []); var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); var mappings = util.getArg(sourceMap, 'mappings'); var file = util.getArg(sourceMap, 'file', null); // Once again, Sass deviates from the spec and supplies the version as a // string rather than a number, so we use loose equality checking here. if (version != this._version) { throw new Error('Unsupported version: ' + version); } if (sourceRoot) { sourceRoot = util.normalize(sourceRoot); } sources = sources .map(String) // Some source maps produce relative source paths like "./foo.js" instead of // "foo.js". Normalize these first so that future comparisons will succeed. // See bugzil.la/1090768. .map(util.normalize) // Always ensure that absolute sources are internally stored relative to // the source root, if the source root is absolute. Not doing this would // be particularly problematic when the source root is a prefix of the // source (valid, but why??). See github issue #199 and bugzil.la/1188982. .map(function (source) { return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) ? util.relative(sourceRoot, source) : source; }); // Pass `true` below to allow duplicate names and sources. While source maps // are intended to be compressed and deduplicated, the TypeScript compiler // sometimes generates source maps with duplicates in them. See Github issue // #72 and bugzil.la/889492. this._names = ArraySet.fromArray(names.map(String), true); this._sources = ArraySet.fromArray(sources, true); this._absoluteSources = this._sources.toArray().map(function (s) { return util.computeSourceURL(sourceRoot, s, aSourceMapURL); }); this.sourceRoot = sourceRoot; this.sourcesContent = sourcesContent; this._mappings = mappings; this._sourceMapURL = aSourceMapURL; this.file = file; } BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; /** * Utility function to find the index of a source. Returns -1 if not * found. */ BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { var relativeSource = aSource; if (this.sourceRoot != null) { relativeSource = util.relative(this.sourceRoot, relativeSource); } if (this._sources.has(relativeSource)) { return this._sources.indexOf(relativeSource); } // Maybe aSource is an absolute URL as returned by |sources|. In // this case we can't simply undo the transform. var i; for (i = 0; i < this._absoluteSources.length; ++i) { if (this._absoluteSources[i] == aSource) { return i; } } return -1; }; /** * Create a BasicSourceMapConsumer from a SourceMapGenerator. * * @param SourceMapGenerator aSourceMap * The source map that will be consumed. * @param String aSourceMapURL * The URL at which the source map can be found (optional) * @returns BasicSourceMapConsumer */ BasicSourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { var smc = Object.create(BasicSourceMapConsumer.prototype); var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); smc.sourceRoot = aSourceMap._sourceRoot; smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot); smc.file = aSourceMap._file; smc._sourceMapURL = aSourceMapURL; smc._absoluteSources = smc._sources.toArray().map(function (s) { return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); }); // Because we are modifying the entries (by converting string sources and // names to indices into the sources and names ArraySets), we have to make // a copy of the entry or else bad things happen. Shared mutable state // strikes again! See github issue #191. var generatedMappings = aSourceMap._mappings.toArray().slice(); var destGeneratedMappings = smc.__generatedMappings = []; var destOriginalMappings = smc.__originalMappings = []; for (var i = 0, length = generatedMappings.length; i < length; i++) { var srcMapping = generatedMappings[i]; var destMapping = new Mapping; destMapping.generatedLine = srcMapping.generatedLine; destMapping.generatedColumn = srcMapping.generatedColumn; if (srcMapping.source) { destMapping.source = sources.indexOf(srcMapping.source); destMapping.originalLine = srcMapping.originalLine; destMapping.originalColumn = srcMapping.originalColumn; if (srcMapping.name) { destMapping.name = names.indexOf(srcMapping.name); } destOriginalMappings.push(destMapping); } destGeneratedMappings.push(destMapping); } quickSort(smc.__originalMappings, util.compareByOriginalPositions); return smc; }; /** * The version of the source mapping spec that we are consuming. */ BasicSourceMapConsumer.prototype._version = 3; /** * The list of original sources. */ Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { get: function () { return this._absoluteSources.slice(); } }); /** * Provide the JIT with a nice shape / hidden class. */ function Mapping() { this.generatedLine = 0; this.generatedColumn = 0; this.source = null; this.originalLine = null; this.originalColumn = null; this.name = null; } /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ BasicSourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { var generatedLine = 1; var previousGeneratedColumn = 0; var previousOriginalLine = 0; var previousOriginalColumn = 0; var previousSource = 0; var previousName = 0; var length = aStr.length; var index = 0; var cachedSegments = {}; var temp = {}; var originalMappings = []; var generatedMappings = []; var mapping, str, segment, end, value; while (index < length) { if (aStr.charAt(index) === ';') { generatedLine++; index++; previousGeneratedColumn = 0; } else if (aStr.charAt(index) === ',') { index++; } else { mapping = new Mapping(); mapping.generatedLine = generatedLine; // Because each offset is encoded relative to the previous one, // many segments often have the same encoding. We can exploit this // fact by caching the parsed variable length fields of each segment, // allowing us to avoid a second parse if we encounter the same // segment again. for (end = index; end < length; end++) { if (this._charIsMappingSeparator(aStr, end)) { break; } } str = aStr.slice(index, end); segment = cachedSegments[str]; if (segment) { index += str.length; } else { segment = []; while (index < end) { base64VLQ.decode(aStr, index, temp); value = temp.value; index = temp.rest; segment.push(value); } if (segment.length === 2) { throw new Error('Found a source, but no line and column'); } if (segment.length === 3) { throw new Error('Found a source and line, but no column'); } cachedSegments[str] = segment; } // Generated column. mapping.generatedColumn = previousGeneratedColumn + segment[0]; previousGeneratedColumn = mapping.generatedColumn; if (segment.length > 1) { // Original source. mapping.source = previousSource + segment[1]; previousSource += segment[1]; // Original line. mapping.originalLine = previousOriginalLine + segment[2]; previousOriginalLine = mapping.originalLine; // Lines are stored 0-based mapping.originalLine += 1; // Original column. mapping.originalColumn = previousOriginalColumn + segment[3]; previousOriginalColumn = mapping.originalColumn; if (segment.length > 4) { // Original name. mapping.name = previousName + segment[4]; previousName += segment[4]; } } generatedMappings.push(mapping); if (typeof mapping.originalLine === 'number') { originalMappings.push(mapping); } } } quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); this.__generatedMappings = generatedMappings; quickSort(originalMappings, util.compareByOriginalPositions); this.__originalMappings = originalMappings; }; /** * Find the mapping that best matches the hypothetical "needle" mapping that * we are searching for in the given "haystack" of mappings. */ BasicSourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) { // To return the position we are searching for, we must first find the // mapping for the given position and then return the opposite position it // points to. Because the mappings are sorted, we can use binary search to // find the best mapping. if (aNeedle[aLineName] <= 0) { throw new TypeError('Line must be greater than or equal to 1, got ' + aNeedle[aLineName]); } if (aNeedle[aColumnName] < 0) { throw new TypeError('Column must be greater than or equal to 0, got ' + aNeedle[aColumnName]); } return binarySearch.search(aNeedle, aMappings, aComparator, aBias); }; /** * Compute the last column for each generated mapping. The last column is * inclusive. */ BasicSourceMapConsumer.prototype.computeColumnSpans = function SourceMapConsumer_computeColumnSpans() { for (var index = 0; index < this._generatedMappings.length; ++index) { var mapping = this._generatedMappings[index]; // Mappings do not contain a field for the last generated columnt. We // can come up with an optimistic estimate, however, by assuming that // mappings are contiguous (i.e. given two consecutive mappings, the // first mapping ends where the second one starts). if (index + 1 < this._generatedMappings.length) { var nextMapping = this._generatedMappings[index + 1]; if (mapping.generatedLine === nextMapping.generatedLine) { mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; continue; } } // The last mapping for each line spans the entire line. mapping.lastGeneratedColumn = Infinity; } }; /** * Returns the original source, line, and column information for the generated * source's line and column positions provided. The only argument is an object * with the following properties: * * - line: The line number in the generated source. The line number * is 1-based. * - column: The column number in the generated source. The column * number is 0-based. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. * * and an object is returned with the following properties: * * - source: The original source file, or null. * - line: The line number in the original source, or null. The * line number is 1-based. * - column: The column number in the original source, or null. The * column number is 0-based. * - name: The original identifier, or null. */ BasicSourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util.getArg(aArgs, 'line'), generatedColumn: util.getArg(aArgs, 'column') }; var index = this._findMapping( needle, this._generatedMappings, "generatedLine", "generatedColumn", util.compareByGeneratedPositionsDeflated, util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) ); if (index >= 0) { var mapping = this._generatedMappings[index]; if (mapping.generatedLine === needle.generatedLine) { var source = util.getArg(mapping, 'source', null); if (source !== null) { source = this._sources.at(source); source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); } var name = util.getArg(mapping, 'name', null); if (name !== null) { name = this._names.at(name); } return { source: source, line: util.getArg(mapping, 'originalLine', null), column: util.getArg(mapping, 'originalColumn', null), name: name }; } } return { source: null, line: null, column: null, name: null }; }; /** * Return true if we have the source content for every source in the source * map, false otherwise. */ BasicSourceMapConsumer.prototype.hasContentsOfAllSources = function BasicSourceMapConsumer_hasContentsOfAllSources() { if (!this.sourcesContent) { return false; } return this.sourcesContent.length >= this._sources.size() && !this.sourcesContent.some(function (sc) { return sc == null; }); }; /** * Returns the original source content. The only argument is the url of the * original source file. Returns null if no original source content is * available. */ BasicSourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { if (!this.sourcesContent) { return null; } var index = this._findSourceIndex(aSource); if (index >= 0) { return this.sourcesContent[index]; } var relativeSource = aSource; if (this.sourceRoot != null) { relativeSource = util.relative(this.sourceRoot, relativeSource); } var url; if (this.sourceRoot != null && (url = util.urlParse(this.sourceRoot))) { // XXX: file:// URIs and absolute paths lead to unexpected behavior for // many users. We can help them out when they expect file:// URIs to // behave like it would if they were running a local HTTP server. See // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) { return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] } if ((!url.path || url.path == "/") && this._sources.has("/" + relativeSource)) { return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; } } // This function is used recursively from // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we // don't want to throw if we can't find the source - we just want to // return null, so we provide a flag to exit gracefully. if (nullOnMissing) { return null; } else { throw new Error('"' + relativeSource + '" is not in the SourceMap.'); } }; /** * Returns the generated line and column information for the original source, * line, and column positions provided. The only argument is an object with * the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. The line number * is 1-based. * - column: The column number in the original source. The column * number is 0-based. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. * * and an object is returned with the following properties: * * - line: The line number in the generated source, or null. The * line number is 1-based. * - column: The column number in the generated source, or null. * The column number is 0-based. */ BasicSourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) { var source = util.getArg(aArgs, 'source'); source = this._findSourceIndex(source); if (source < 0) { return { line: null, column: null, lastColumn: null }; } var needle = { source: source, originalLine: util.getArg(aArgs, 'line'), originalColumn: util.getArg(aArgs, 'column') }; var index = this._findMapping( needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) ); if (index >= 0) { var mapping = this._originalMappings[index]; if (mapping.source === needle.source) { return { line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null), lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) }; } } return { line: null, column: null, lastColumn: null }; }; __webpack_unused_export__ = BasicSourceMapConsumer; /** * An IndexedSourceMapConsumer instance represents a parsed source map which * we can query for information. It differs from BasicSourceMapConsumer in * that it takes "indexed" source maps (i.e. ones with a "sections" field) as * input. * * The first parameter is a raw source map (either as a JSON string, or already * parsed to an object). According to the spec for indexed source maps, they * have the following attributes: * * - version: Which version of the source map spec this map is following. * - file: Optional. The generated file this source map is associated with. * - sections: A list of section definitions. * * Each value under the "sections" field has two fields: * - offset: The offset into the original specified at which this section * begins to apply, defined as an object with a "line" and "column" * field. * - map: A source map definition. This source map could also be indexed, * but doesn't have to be. * * Instead of the "map" field, it's also possible to have a "url" field * specifying a URL to retrieve a source map from, but that's currently * unsupported. * * Here's an example source map, taken from the source map spec[0], but * modified to omit a section which uses the "url" field. * * { * version : 3, * file: "app.js", * sections: [{ * offset: {line:100, column:10}, * map: { * version : 3, * file: "section.js", * sources: ["foo.js", "bar.js"], * names: ["src", "maps", "are", "fun"], * mappings: "AAAA,E;;ABCDE;" * } * }], * } * * The second parameter, if given, is a string whose value is the URL * at which the source map was found. This URL is used to compute the * sources array. * * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt */ function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = util.parseSourceMapInput(aSourceMap); } var version = util.getArg(sourceMap, 'version'); var sections = util.getArg(sourceMap, 'sections'); if (version != this._version) { throw new Error('Unsupported version: ' + version); } this._sources = new ArraySet(); this._names = new ArraySet(); var lastOffset = { line: -1, column: 0 }; this._sections = sections.map(function (s) { if (s.url) { // The url field will require support for asynchronicity. // See https://github.com/mozilla/source-map/issues/16 throw new Error('Support for url field in sections not implemented.'); } var offset = util.getArg(s, 'offset'); var offsetLine = util.getArg(offset, 'line'); var offsetColumn = util.getArg(offset, 'column'); if (offsetLine < lastOffset.line || (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { throw new Error('Section offsets must be ordered and non-overlapping.'); } lastOffset = offset; return { generatedOffset: { // The offset fields are 0-based, but we use 1-based indices when // encoding/decoding from VLQ. generatedLine: offsetLine + 1, generatedColumn: offsetColumn + 1 }, consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) } }); } IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; /** * The version of the source mapping spec that we are consuming. */ IndexedSourceMapConsumer.prototype._version = 3; /** * The list of original sources. */ Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { get: function () { var sources = []; for (var i = 0; i < this._sections.length; i++) { for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { sources.push(this._sections[i].consumer.sources[j]); } } return sources; } }); /** * Returns the original source, line, and column information for the generated * source's line and column positions provided. The only argument is an object * with the following properties: * * - line: The line number in the generated source. The line number * is 1-based. * - column: The column number in the generated source. The column * number is 0-based. * * and an object is returned with the following properties: * * - source: The original source file, or null. * - line: The line number in the original source, or null. The * line number is 1-based. * - column: The column number in the original source, or null. The * column number is 0-based. * - name: The original identifier, or null. */ IndexedSourceMapConsumer.prototype.originalPositionFor = function IndexedSourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util.getArg(aArgs, 'line'), generatedColumn: util.getArg(aArgs, 'column') }; // Find the section containing the generated position we're trying to map // to an original position. var sectionIndex = binarySearch.search(needle, this._sections, function(needle, section) { var cmp = needle.generatedLine - section.generatedOffset.generatedLine; if (cmp) { return cmp; } return (needle.generatedColumn - section.generatedOffset.generatedColumn); }); var section = this._sections[sectionIndex]; if (!section) { return { source: null, line: null, column: null, name: null }; } return section.consumer.originalPositionFor({ line: needle.generatedLine - (section.generatedOffset.generatedLine - 1), column: needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0), bias: aArgs.bias }); }; /** * Return true if we have the source content for every source in the source * map, false otherwise. */ IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = function IndexedSourceMapConsumer_hasContentsOfAllSources() { return this._sections.every(function (s) { return s.consumer.hasContentsOfAllSources(); }); }; /** * Returns the original source content. The only argument is the url of the * original source file. Returns null if no original source content is * available. */ IndexedSourceMapConsumer.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; var content = section.consumer.sourceContentFor(aSource, true); if (content) { return content; } } if (nullOnMissing) { return null; } else { throw new Error('"' + aSource + '" is not in the SourceMap.'); } }; /** * Returns the generated line and column information for the original source, * line, and column positions provided. The only argument is an object with * the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. The line number * is 1-based. * - column: The column number in the original source. The column * number is 0-based. * * and an object is returned with the following properties: * * - line: The line number in the generated source, or null. The * line number is 1-based. * - column: The column number in the generated source, or null. * The column number is 0-based. */ IndexedSourceMapConsumer.prototype.generatedPositionFor = function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; // Only consider this section if the requested source is in the list of // sources of the consumer. if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { continue; } var generatedPosition = section.consumer.generatedPositionFor(aArgs); if (generatedPosition) { var ret = { line: generatedPosition.line + (section.generatedOffset.generatedLine - 1), column: generatedPosition.column + (section.generatedOffset.generatedLine === generatedPosition.line ? section.generatedOffset.generatedColumn - 1 : 0) }; return ret; } } return { line: null, column: null }; }; /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ IndexedSourceMapConsumer.prototype._parseMappings = function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { this.__generatedMappings = []; this.__originalMappings = []; for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; var sectionMappings = section.consumer._generatedMappings; for (var j = 0; j < sectionMappings.length; j++) { var mapping = sectionMappings[j]; var source = section.consumer._sources.at(mapping.source); source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); this._sources.add(source); source = this._sources.indexOf(source); var name = null; if (mapping.name) { name = section.consumer._names.at(mapping.name); this._names.add(name); name = this._names.indexOf(name); } // The mappings coming from the consumer for the section have // generated positions relative to the start of the section, so we // need to offset them to be relative to the start of the concatenated // generated file. var adjustedMapping = { source: source, generatedLine: mapping.generatedLine + (section.generatedOffset.generatedLine - 1), generatedColumn: mapping.generatedColumn + (section.generatedOffset.generatedLine === mapping.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0), originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: name }; this.__generatedMappings.push(adjustedMapping); if (typeof adjustedMapping.originalLine === 'number') { this.__originalMappings.push(adjustedMapping); } } } quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); quickSort(this.__originalMappings, util.compareByOriginalPositions); }; __webpack_unused_export__ = IndexedSourceMapConsumer; /***/ }), /***/ 34433: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var base64VLQ = __webpack_require__(16400); var util = __webpack_require__(32728); var ArraySet = __webpack_require__(78213)/* .ArraySet */ .I; var MappingList = __webpack_require__(21188)/* .MappingList */ .H; /** * An instance of the SourceMapGenerator represents a source map which is * being built incrementally. You may pass an object with the following * properties: * * - file: The filename of the generated source. * - sourceRoot: A root for all relative URLs in this source map. */ function SourceMapGenerator(aArgs) { if (!aArgs) { aArgs = {}; } this._file = util.getArg(aArgs, 'file', null); this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); this._skipValidation = util.getArg(aArgs, 'skipValidation', false); this._sources = new ArraySet(); this._names = new ArraySet(); this._mappings = new MappingList(); this._sourcesContents = null; } SourceMapGenerator.prototype._version = 3; /** * Creates a new SourceMapGenerator based on a SourceMapConsumer * * @param aSourceMapConsumer The SourceMap. */ SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { var sourceRoot = aSourceMapConsumer.sourceRoot; var generator = new SourceMapGenerator({ file: aSourceMapConsumer.file, sourceRoot: sourceRoot }); aSourceMapConsumer.eachMapping(function (mapping) { var newMapping = { generated: { line: mapping.generatedLine, column: mapping.generatedColumn } }; if (mapping.source != null) { newMapping.source = mapping.source; if (sourceRoot != null) { newMapping.source = util.relative(sourceRoot, newMapping.source); } newMapping.original = { line: mapping.originalLine, column: mapping.originalColumn }; if (mapping.name != null) { newMapping.name = mapping.name; } } generator.addMapping(newMapping); }); aSourceMapConsumer.sources.forEach(function (sourceFile) { var sourceRelative = sourceFile; if (sourceRoot !== null) { sourceRelative = util.relative(sourceRoot, sourceFile); } if (!generator._sources.has(sourceRelative)) { generator._sources.add(sourceRelative); } var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { generator.setSourceContent(sourceFile, content); } }); return generator; }; /** * Add a single mapping from original source line and column to the generated * source's line and column for this source map being created. The mapping * object should have the following properties: * * - generated: An object with the generated line and column positions. * - original: An object with the original line and column positions. * - source: The original source file (relative to the sourceRoot). * - name: An optional original token name for this mapping. */ SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) { var generated = util.getArg(aArgs, 'generated'); var original = util.getArg(aArgs, 'original', null); var source = util.getArg(aArgs, 'source', null); var name = util.getArg(aArgs, 'name', null); if (!this._skipValidation) { this._validateMapping(generated, original, source, name); } if (source != null) { source = String(source); if (!this._sources.has(source)) { this._sources.add(source); } } if (name != null) { name = String(name); if (!this._names.has(name)) { this._names.add(name); } } this._mappings.add({ generatedLine: generated.line, generatedColumn: generated.column, originalLine: original != null && original.line, originalColumn: original != null && original.column, source: source, name: name }); }; /** * Set the source content for a source file. */ SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { var source = aSourceFile; if (this._sourceRoot != null) { source = util.relative(this._sourceRoot, source); } if (aSourceContent != null) { // Add the source content to the _sourcesContents map. // Create a new _sourcesContents map if the property is null. if (!this._sourcesContents) { this._sourcesContents = Object.create(null); } this._sourcesContents[util.toSetString(source)] = aSourceContent; } else if (this._sourcesContents) { // Remove the source file from the _sourcesContents map. // If the _sourcesContents map is empty, set the property to null. delete this._sourcesContents[util.toSetString(source)]; if (Object.keys(this._sourcesContents).length === 0) { this._sourcesContents = null; } } }; /** * Applies the mappings of a sub-source-map for a specific source file to the * source map being generated. Each mapping to the supplied source file is * rewritten using the supplied source map. Note: The resolution for the * resulting mappings is the minimium of this map and the supplied map. * * @param aSourceMapConsumer The source map to be applied. * @param aSourceFile Optional. The filename of the source file. * If omitted, SourceMapConsumer's file property will be used. * @param aSourceMapPath Optional. The dirname of the path to the source map * to be applied. If relative, it is relative to the SourceMapConsumer. * This parameter is needed when the two source maps aren't in the same * directory, and the source map to be applied contains relative source * paths. If so, those relative source paths need to be rewritten * relative to the SourceMapGenerator. */ SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { var sourceFile = aSourceFile; // If aSourceFile is omitted, we will use the file property of the SourceMap if (aSourceFile == null) { if (aSourceMapConsumer.file == null) { throw new Error( 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + 'or the source map\'s "file" property. Both were omitted.' ); } sourceFile = aSourceMapConsumer.file; } var sourceRoot = this._sourceRoot; // Make "sourceFile" relative if an absolute Url is passed. if (sourceRoot != null) { sourceFile = util.relative(sourceRoot, sourceFile); } // Applying the SourceMap can add and remove items from the sources and // the names array. var newSources = new ArraySet(); var newNames = new ArraySet(); // Find mappings for the "sourceFile" this._mappings.unsortedForEach(function (mapping) { if (mapping.source === sourceFile && mapping.originalLine != null) { // Check if it can be mapped by the source map, then update the mapping. var original = aSourceMapConsumer.originalPositionFor({ line: mapping.originalLine, column: mapping.originalColumn }); if (original.source != null) { // Copy mapping mapping.source = original.source; if (aSourceMapPath != null) { mapping.source = util.join(aSourceMapPath, mapping.source) } if (sourceRoot != null) { mapping.source = util.relative(sourceRoot, mapping.source); } mapping.originalLine = original.line; mapping.originalColumn = original.column; if (original.name != null) { mapping.name = original.name; } } } var source = mapping.source; if (source != null && !newSources.has(source)) { newSources.add(source); } var name = mapping.name; if (name != null && !newNames.has(name)) { newNames.add(name); } }, this); this._sources = newSources; this._names = newNames; // Copy sourcesContents of applied map. aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { if (aSourceMapPath != null) { sourceFile = util.join(aSourceMapPath, sourceFile); } if (sourceRoot != null) { sourceFile = util.relative(sourceRoot, sourceFile); } this.setSourceContent(sourceFile, content); } }, this); }; /** * A mapping can have one of the three levels of data: * * 1. Just the generated position. * 2. The Generated position, original position, and original source. * 3. Generated and original position, original source, as well as a name * token. * * To maintain consistency, we validate that any new mapping being added falls * in to one of these categories. */ SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) { // When aOriginal is truthy but has empty values for .line and .column, // it is most likely a programmer error. In this case we throw a very // specific error message to try to guide them the right way. // For example: https://github.com/Polymer/polymer-bundler/pull/519 if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { throw new Error( 'original.line and original.column are not numbers -- you probably meant to omit ' + 'the original mapping entirely and only map the generated position. If so, pass ' + 'null for the original mapping instead of an object with empty or null values.' ); } if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) { // Case 1. return; } else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aOriginal && 'line' in aOriginal && 'column' in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) { // Cases 2 and 3. return; } else { throw new Error('Invalid mapping: ' + JSON.stringify({ generated: aGenerated, source: aSource, original: aOriginal, name: aName })); } }; /** * Serialize the accumulated mappings in to the stream of base 64 VLQs * specified by the source map format. */ SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() { var previousGeneratedColumn = 0; var previousGeneratedLine = 1; var previousOriginalColumn = 0; var previousOriginalLine = 0; var previousName = 0; var previousSource = 0; var result = ''; var next; var mapping; var nameIdx; var sourceIdx; var mappings = this._mappings.toArray(); for (var i = 0, len = mappings.length; i < len; i++) { mapping = mappings[i]; next = '' if (mapping.generatedLine !== previousGeneratedLine) { previousGeneratedColumn = 0; while (mapping.generatedLine !== previousGeneratedLine) { next += ';'; previousGeneratedLine++; } } else { if (i > 0) { if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { continue; } next += ','; } } next += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn); previousGeneratedColumn = mapping.generatedColumn; if (mapping.source != null) { sourceIdx = this._sources.indexOf(mapping.source); next += base64VLQ.encode(sourceIdx - previousSource); previousSource = sourceIdx; // lines are stored 0-based in SourceMap spec version 3 next += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine); previousOriginalLine = mapping.originalLine - 1; next += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn); previousOriginalColumn = mapping.originalColumn; if (mapping.name != null) { nameIdx = this._names.indexOf(mapping.name); next += base64VLQ.encode(nameIdx - previousName); previousName = nameIdx; } } result += next; } return result; }; SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { return aSources.map(function (source) { if (!this._sourcesContents) { return null; } if (aSourceRoot != null) { source = util.relative(aSourceRoot, source); } var key = util.toSetString(source); return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null; }, this); }; /** * Externalize the source map. */ SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() { var map = { version: this._version, sources: this._sources.toArray(), names: this._names.toArray(), mappings: this._serializeMappings() }; if (this._file != null) { map.file = this._file; } if (this._sourceRoot != null) { map.sourceRoot = this._sourceRoot; } if (this._sourcesContents) { map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); } return map; }; /** * Render the source map being generated to a string. */ SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() { return JSON.stringify(this.toJSON()); }; exports.h = SourceMapGenerator; /***/ }), /***/ 17085: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { var __webpack_unused_export__; /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var SourceMapGenerator = __webpack_require__(34433)/* .SourceMapGenerator */ .h; var util = __webpack_require__(32728); // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other // operating systems these days (capturing the result). var REGEX_NEWLINE = /(\r?\n)/; // Newline character code for charCodeAt() comparisons var NEWLINE_CODE = 10; // Private symbol for identifying `SourceNode`s when multiple versions of // the source-map library are loaded. This MUST NOT CHANGE across // versions! var isSourceNode = "$$$isSourceNode$$$"; /** * SourceNodes provide a way to abstract over interpolating/concatenating * snippets of generated JavaScript source code while maintaining the line and * column information associated with the original source code. * * @param aLine The original line number. * @param aColumn The original column number. * @param aSource The original source's filename. * @param aChunks Optional. An array of strings which are snippets of * generated JS, or other SourceNodes. * @param aName The original identifier. */ function SourceNode(aLine, aColumn, aSource, aChunks, aName) { this.children = []; this.sourceContents = {}; this.line = aLine == null ? null : aLine; this.column = aColumn == null ? null : aColumn; this.source = aSource == null ? null : aSource; this.name = aName == null ? null : aName; this[isSourceNode] = true; if (aChunks != null) this.add(aChunks); } /** * Creates a SourceNode from generated code and a SourceMapConsumer. * * @param aGeneratedCode The generated code * @param aSourceMapConsumer The SourceMap for the generated code * @param aRelativePath Optional. The path that relative sources in the * SourceMapConsumer should be relative to. */ SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { // The SourceNode we want to fill with the generated code // and the SourceMap var node = new SourceNode(); // All even indices of this array are one line of the generated code, // while all odd indices are the newlines between two adjacent lines // (since `REGEX_NEWLINE` captures its match). // Processed fragments are accessed by calling `shiftNextLine`. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); var remainingLinesIndex = 0; var shiftNextLine = function() { var lineContents = getNextLine(); // The last line of a file might not have a newline. var newLine = getNextLine() || ""; return lineContents + newLine; function getNextLine() { return remainingLinesIndex < remainingLines.length ? remainingLines[remainingLinesIndex++] : undefined; } }; // We need to remember the position of "remainingLines" var lastGeneratedLine = 1, lastGeneratedColumn = 0; // The generate SourceNodes we need a code range. // To extract it current and last mapping is used. // Here we store the last mapping. var lastMapping = null; aSourceMapConsumer.eachMapping(function (mapping) { if (lastMapping !== null) { // We add the code from "lastMapping" to "mapping": // First check if there is a new line in between. if (lastGeneratedLine < mapping.generatedLine) { // Associate first line with "lastMapping" addMappingWithCode(lastMapping, shiftNextLine()); lastGeneratedLine++; lastGeneratedColumn = 0; // The remaining code is added without mapping } else { // There is no new line in between. // Associate the code between "lastGeneratedColumn" and // "mapping.generatedColumn" with "lastMapping" var nextLine = remainingLines[remainingLinesIndex] || ''; var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn); remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn); lastGeneratedColumn = mapping.generatedColumn; addMappingWithCode(lastMapping, code); // No more remaining code, continue lastMapping = mapping; return; } } // We add the generated code until the first mapping // to the SourceNode without any mapping. // Each line is added as separate string. while (lastGeneratedLine < mapping.generatedLine) { node.add(shiftNextLine()); lastGeneratedLine++; } if (lastGeneratedColumn < mapping.generatedColumn) { var nextLine = remainingLines[remainingLinesIndex] || ''; node.add(nextLine.substr(0, mapping.generatedColumn)); remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); lastGeneratedColumn = mapping.generatedColumn; } lastMapping = mapping; }, this); // We have processed all mappings. if (remainingLinesIndex < remainingLines.length) { if (lastMapping) { // Associate the remaining code in the current line with "lastMapping" addMappingWithCode(lastMapping, shiftNextLine()); } // and add the remaining lines without any mapping node.add(remainingLines.splice(remainingLinesIndex).join("")); } // Copy sourcesContent into SourceNode aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { if (aRelativePath != null) { sourceFile = util.join(aRelativePath, sourceFile); } node.setSourceContent(sourceFile, content); } }); return node; function addMappingWithCode(mapping, code) { if (mapping === null || mapping.source === undefined) { node.add(code); } else { var source = aRelativePath ? util.join(aRelativePath, mapping.source) : mapping.source; node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, source, code, mapping.name)); } } }; /** * Add a chunk of generated JS to this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.add = function SourceNode_add(aChunk) { if (Array.isArray(aChunk)) { aChunk.forEach(function (chunk) { this.add(chunk); }, this); } else if (aChunk[isSourceNode] || typeof aChunk === "string") { if (aChunk) { this.children.push(aChunk); } } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Add a chunk of generated JS to the beginning of this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { if (Array.isArray(aChunk)) { for (var i = aChunk.length-1; i >= 0; i--) { this.prepend(aChunk[i]); } } else if (aChunk[isSourceNode] || typeof aChunk === "string") { this.children.unshift(aChunk); } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Walk over the tree of JS snippets in this node and its children. The * walking function is called once for each snippet of JS and is passed that * snippet and the its original associated source's line/column location. * * @param aFn The traversal function. */ SourceNode.prototype.walk = function SourceNode_walk(aFn) { var chunk; for (var i = 0, len = this.children.length; i < len; i++) { chunk = this.children[i]; if (chunk[isSourceNode]) { chunk.walk(aFn); } else { if (chunk !== '') { aFn(chunk, { source: this.source, line: this.line, column: this.column, name: this.name }); } } } }; /** * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between * each of `this.children`. * * @param aSep The separator. */ SourceNode.prototype.join = function SourceNode_join(aSep) { var newChildren; var i; var len = this.children.length; if (len > 0) { newChildren = []; for (i = 0; i < len-1; i++) { newChildren.push(this.children[i]); newChildren.push(aSep); } newChildren.push(this.children[i]); this.children = newChildren; } return this; }; /** * Call String.prototype.replace on the very right-most source snippet. Useful * for trimming whitespace from the end of a source node, etc. * * @param aPattern The pattern to replace. * @param aReplacement The thing to replace the pattern with. */ SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { var lastChild = this.children[this.children.length - 1]; if (lastChild[isSourceNode]) { lastChild.replaceRight(aPattern, aReplacement); } else if (typeof lastChild === 'string') { this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); } else { this.children.push(''.replace(aPattern, aReplacement)); } return this; }; /** * Set the source content for a source file. This will be added to the SourceMapGenerator * in the sourcesContent field. * * @param aSourceFile The filename of the source file * @param aSourceContent The content of the source file */ SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) { this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; }; /** * Walk over the tree of SourceNodes. The walking function is called for each * source file content and is passed the filename and source content. * * @param aFn The traversal function. */ SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) { for (var i = 0, len = this.children.length; i < len; i++) { if (this.children[i][isSourceNode]) { this.children[i].walkSourceContents(aFn); } } var sources = Object.keys(this.sourceContents); for (var i = 0, len = sources.length; i < len; i++) { aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); } }; /** * Return the string representation of this source node. Walks over the tree * and concatenates all the various snippets together to one string. */ SourceNode.prototype.toString = function SourceNode_toString() { var str = ""; this.walk(function (chunk) { str += chunk; }); return str; }; /** * Returns the string representation of this source node along with a source * map. */ SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { var generated = { code: "", line: 1, column: 0 }; var map = new SourceMapGenerator(aArgs); var sourceMappingActive = false; var lastOriginalSource = null; var lastOriginalLine = null; var lastOriginalColumn = null; var lastOriginalName = null; this.walk(function (chunk, original) { generated.code += chunk; if (original.source !== null && original.line !== null && original.column !== null) { if(lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) { map.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } lastOriginalSource = original.source; lastOriginalLine = original.line; lastOriginalColumn = original.column; lastOriginalName = original.name; sourceMappingActive = true; } else if (sourceMappingActive) { map.addMapping({ generated: { line: generated.line, column: generated.column } }); lastOriginalSource = null; sourceMappingActive = false; } for (var idx = 0, length = chunk.length; idx < length; idx++) { if (chunk.charCodeAt(idx) === NEWLINE_CODE) { generated.line++; generated.column = 0; // Mappings end at eol if (idx + 1 === length) { lastOriginalSource = null; sourceMappingActive = false; } else if (sourceMappingActive) { map.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } } else { generated.column++; } } }); this.walkSourceContents(function (sourceFile, sourceContent) { map.setSourceContent(sourceFile, sourceContent); }); return { code: generated.code, map: map }; }; __webpack_unused_export__ = SourceNode; /***/ }), /***/ 32728: /***/ ((__unused_webpack_module, exports) => { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ /** * This is a helper function for getting values from parameter/options * objects. * * @param args The object we are extracting values from * @param name The name of the property we are getting. * @param defaultValue An optional value to return if the property is missing * from the object. If this is not specified and the property is missing, an * error will be thrown. */ function getArg(aArgs, aName, aDefaultValue) { if (aName in aArgs) { return aArgs[aName]; } else if (arguments.length === 3) { return aDefaultValue; } else { throw new Error('"' + aName + '" is a required argument.'); } } exports.getArg = getArg; var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; var dataUrlRegexp = /^data:.+\,.+$/; function urlParse(aUrl) { var match = aUrl.match(urlRegexp); if (!match) { return null; } return { scheme: match[1], auth: match[2], host: match[3], port: match[4], path: match[5] }; } exports.urlParse = urlParse; function urlGenerate(aParsedUrl) { var url = ''; if (aParsedUrl.scheme) { url += aParsedUrl.scheme + ':'; } url += '//'; if (aParsedUrl.auth) { url += aParsedUrl.auth + '@'; } if (aParsedUrl.host) { url += aParsedUrl.host; } if (aParsedUrl.port) { url += ":" + aParsedUrl.port } if (aParsedUrl.path) { url += aParsedUrl.path; } return url; } exports.urlGenerate = urlGenerate; /** * Normalizes a path, or the path portion of a URL: * * - Replaces consecutive slashes with one slash. * - Removes unnecessary '.' parts. * - Removes unnecessary '/..' parts. * * Based on code in the Node.js 'path' core module. * * @param aPath The path or url to normalize. */ function normalize(aPath) { var path = aPath; var url = urlParse(aPath); if (url) { if (!url.path) { return aPath; } path = url.path; } var isAbsolute = exports.isAbsolute(path); var parts = path.split(/\/+/); for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { part = parts[i]; if (part === '.') { parts.splice(i, 1); } else if (part === '..') { up++; } else if (up > 0) { if (part === '') { // The first part is blank if the path is absolute. Trying to go // above the root is a no-op. Therefore we can remove all '..' parts // directly after the root. parts.splice(i + 1, up); up = 0; } else { parts.splice(i, 2); up--; } } } path = parts.join('/'); if (path === '') { path = isAbsolute ? '/' : '.'; } if (url) { url.path = path; return urlGenerate(url); } return path; } exports.normalize = normalize; /** * Joins two paths/URLs. * * @param aRoot The root path or URL. * @param aPath The path or URL to be joined with the root. * * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a * scheme-relative URL: Then the scheme of aRoot, if any, is prepended * first. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion * is updated with the result and aRoot is returned. Otherwise the result * is returned. * - If aPath is absolute, the result is aPath. * - Otherwise the two paths are joined with a slash. * - Joining for example 'http://' and 'www.example.com' is also supported. */ function join(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } if (aPath === "") { aPath = "."; } var aPathUrl = urlParse(aPath); var aRootUrl = urlParse(aRoot); if (aRootUrl) { aRoot = aRootUrl.path || '/'; } // `join(foo, '//www.example.org')` if (aPathUrl && !aPathUrl.scheme) { if (aRootUrl) { aPathUrl.scheme = aRootUrl.scheme; } return urlGenerate(aPathUrl); } if (aPathUrl || aPath.match(dataUrlRegexp)) { return aPath; } // `join('http://', 'www.example.com')` if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { aRootUrl.host = aPath; return urlGenerate(aRootUrl); } var joined = aPath.charAt(0) === '/' ? aPath : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); if (aRootUrl) { aRootUrl.path = joined; return urlGenerate(aRootUrl); } return joined; } exports.join = join; exports.isAbsolute = function (aPath) { return aPath.charAt(0) === '/' || urlRegexp.test(aPath); }; /** * Make a path relative to a URL or another path. * * @param aRoot The root path or URL. * @param aPath The path or URL to be made relative to aRoot. */ function relative(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } aRoot = aRoot.replace(/\/$/, ''); // It is possible for the path to be above the root. In this case, simply // checking whether the root is a prefix of the path won't work. Instead, we // need to remove components from the root one by one, until either we find // a prefix that fits, or we run out of components to remove. var level = 0; while (aPath.indexOf(aRoot + '/') !== 0) { var index = aRoot.lastIndexOf("/"); if (index < 0) { return aPath; } // If the only part of the root that is left is the scheme (i.e. http://, // file:///, etc.), one or more slashes (/), or simply nothing at all, we // have exhausted all components, so the path is not relative to the root. aRoot = aRoot.slice(0, index); if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { return aPath; } ++level; } // Make sure we add a "../" for each component we removed from the root. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); } exports.relative = relative; var supportsNullProto = (function () { var obj = Object.create(null); return !('__proto__' in obj); }()); function identity (s) { return s; } /** * Because behavior goes wacky when you set `__proto__` on objects, we * have to prefix all the strings in our set with an arbitrary character. * * See https://github.com/mozilla/source-map/pull/31 and * https://github.com/mozilla/source-map/issues/30 * * @param String aStr */ function toSetString(aStr) { if (isProtoString(aStr)) { return '$' + aStr; } return aStr; } exports.toSetString = supportsNullProto ? identity : toSetString; function fromSetString(aStr) { if (isProtoString(aStr)) { return aStr.slice(1); } return aStr; } exports.fromSetString = supportsNullProto ? identity : fromSetString; function isProtoString(s) { if (!s) { return false; } var length = s.length; if (length < 9 /* "__proto__".length */) { return false; } if (s.charCodeAt(length - 1) !== 95 /* '_' */ || s.charCodeAt(length - 2) !== 95 /* '_' */ || s.charCodeAt(length - 3) !== 111 /* 'o' */ || s.charCodeAt(length - 4) !== 116 /* 't' */ || s.charCodeAt(length - 5) !== 111 /* 'o' */ || s.charCodeAt(length - 6) !== 114 /* 'r' */ || s.charCodeAt(length - 7) !== 112 /* 'p' */ || s.charCodeAt(length - 8) !== 95 /* '_' */ || s.charCodeAt(length - 9) !== 95 /* '_' */) { return false; } for (var i = length - 10; i >= 0; i--) { if (s.charCodeAt(i) !== 36 /* '$' */) { return false; } } return true; } /** * Comparator between two mappings where the original positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same original source/line/column, but different generated * line and column the same. Useful when searching for a mapping with a * stubbed out mapping. */ function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { var cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0 || onlyCompareOriginal) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByOriginalPositions = compareByOriginalPositions; /** * Comparator between two mappings with deflated source and name indices where * the generated positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same generated line and column, but different * source/name/original line and column the same. Useful when searching for a * mapping with a stubbed out mapping. */ function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0 || onlyCompareGenerated) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; function strcmp(aStr1, aStr2) { if (aStr1 === aStr2) { return 0; } if (aStr1 === null) { return 1; // aStr2 !== null } if (aStr2 === null) { return -1; // aStr1 !== null } if (aStr1 > aStr2) { return 1; } return -1; } /** * Comparator between two mappings with inflated source and name strings where * the generated positions are compared. */ function compareByGeneratedPositionsInflated(mappingA, mappingB) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; /** * Strip any JSON XSSI avoidance prefix from the string (as documented * in the source maps specification), and then parse the string as * JSON. */ function parseSourceMapInput(str) { return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); } exports.parseSourceMapInput = parseSourceMapInput; /** * Compute the URL of a source given the the source root, the source's * URL, and the source map's URL. */ function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { sourceURL = sourceURL || ''; if (sourceRoot) { // This follows what Chrome does. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { sourceRoot += '/'; } // The spec says: // Line 4: An optional source root, useful for relocating source // files on a server or removing repeated values in the // “sources” entry. This value is prepended to the individual // entries in the “source” field. sourceURL = sourceRoot + sourceURL; } // Historically, SourceMapConsumer did not take the sourceMapURL as // a parameter. This mode is still somewhat supported, which is why // this code block is conditional. However, it's preferable to pass // the source map URL to SourceMapConsumer, so that this function // can implement the source URL resolution algorithm as outlined in // the spec. This block is basically the equivalent of: // new URL(sourceURL, sourceMapURL).toString() // ... except it avoids using URL, which wasn't available in the // older releases of node still supported by this library. // // The spec says: // If the sources are not absolute URLs after prepending of the // “sourceRoot”, the sources are resolved relative to the // SourceMap (like resolving script src in a html document). if (sourceMapURL) { var parsed = urlParse(sourceMapURL); if (!parsed) { throw new Error("sourceMapURL could not be parsed"); } if (parsed.path) { // Strip the last path component, but keep the "/". var index = parsed.path.lastIndexOf('/'); if (index >= 0) { parsed.path = parsed.path.substring(0, index + 1); } } sourceURL = join(urlGenerate(parsed), sourceURL); } return normalize(sourceURL); } exports.computeSourceURL = computeSourceURL; /***/ }), /***/ 49125: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { /* * Copyright 2009-2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE.txt or: * http://opensource.org/licenses/BSD-3-Clause */ /* unused reexport */ __webpack_require__(34433)/* .SourceMapGenerator */ .h; exports.SourceMapConsumer = __webpack_require__(76771).SourceMapConsumer; /* unused reexport */ __webpack_require__(17085); /***/ }), /***/ 22714: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var fs = __webpack_require__(57147); module.exports = function (filepath, split, encoding) { split = typeof split !== 'undefined' ? split : "\n"; encoding = typeof encoding !== 'undefined' ? encoding : "utf8"; var ca = []; var chain = fs.readFileSync(filepath, encoding); if(chain.indexOf("-END CERTIFICATE-") < 0 || chain.indexOf("-BEGIN CERTIFICATE-") < 0){ throw Error("File does not contain 'BEGIN CERTIFICATE' or 'END CERTIFICATE'"); } chain = chain.split(split); var cert = []; var _i, _len; for (_i = 0, _len = chain.length; _i < _len; _i++) { var line = chain[_i]; if (!(line.length !== 0)) { continue; } cert.push(line); if (line.match(/-END CERTIFICATE-/)) { ca.push(cert.join(split)); cert = []; } } return ca; } /***/ }), /***/ 26657: /***/ (function(module, exports) { // We are modularizing this manually because the current modularize setting in Emscripten has some issues: // https://github.com/kripken/emscripten/issues/5820 // In addition, When you use emcc's modularization, it still expects to export a global object called `Module`, // which is able to be used/called before the WASM is loaded. // The modularization below exports a promise that loads and resolves to the actual sql.js module. // That way, this module can't be used before the WASM is finished loading. // We are going to define a function that a user will call to start loading initializing our Sql.js library // However, that function might be called multiple times, and on subsequent calls, we don't actually want it to instantiate a new instance of the Module // Instead, we want to return the previously loaded module // TODO: Make this not declare a global if used in the browser var initSqlJsPromise = undefined; var initSqlJs = function (moduleConfig) { if (initSqlJsPromise){ return initSqlJsPromise; } // If we're here, we've never called this function before initSqlJsPromise = new Promise(function (resolveModule, reject) { // We are modularizing this manually because the current modularize setting in Emscripten has some issues: // https://github.com/kripken/emscripten/issues/5820 // The way to affect the loading of emcc compiled modules is to create a variable called `Module` and add // properties to it, like `preRun`, `postRun`, etc // We are using that to get notified when the WASM has finished loading. // Only then will we return our promise // If they passed in a moduleConfig object, use that // Otherwise, initialize Module to the empty object var Module = typeof moduleConfig !== 'undefined' ? moduleConfig : {}; // EMCC only allows for a single onAbort function (not an array of functions) // So if the user defined their own onAbort function, we remember it and call it var originalOnAbortFunction = Module['onAbort']; Module['onAbort'] = function (errorThatCausedAbort) { reject(new Error(errorThatCausedAbort)); if (originalOnAbortFunction){ originalOnAbortFunction(errorThatCausedAbort); } }; Module['postRun'] = Module['postRun'] || []; Module['postRun'].push(function () { // When Emscripted calls postRun, this promise resolves with the built Module resolveModule(Module); }); // There is a section of code in the emcc-generated code below that looks like this: // (Note that this is lowercase `module`) // if (typeof module !== 'undefined') { // module['exports'] = Module; // } // When that runs, it's going to overwrite our own modularization export efforts in shell-post.js! // The only way to tell emcc not to emit it is to pass the MODULARIZE=1 or MODULARIZE_INSTANCE=1 flags, // but that carries with it additional unnecessary baggage/bugs we don't want either. // So, we have three options: // 1) We undefine `module` // 2) We remember what `module['exports']` was at the beginning of this function and we restore it later // 3) We write a script to remove those lines of code as part of the Make process. // // Since those are the only lines of code that care about module, we will undefine it. It's the most straightforward // of the options, and has the side effect of reducing emcc's efforts to modify the module if its output were to change in the future. // That's a nice side effect since we're handling the modularization efforts ourselves module = undefined; // The emcc-generated code and shell-post.js code goes below, // meaning that all of it runs inside of this promise. If anything throws an exception, our promise will abort var e;e||(e=typeof Module !== 'undefined' ? Module : {});null; e.onRuntimeInitialized=function(){function a(g,m){switch(typeof m){case "boolean":gc(g,m?1:0);break;case "number":hc(g,m);break;case "string":ic(g,m,-1,-1);break;case "object":if(null===m)kb(g);else if(null!=m.length){var n=aa(m);jc(g,n,m.length,-1);ba(n)}else xa(g,"Wrong API use : tried to return a value of an unknown type ("+m+").",-1);break;default:kb(g)}}function b(g,m){for(var n=[],p=0;p>>0);if(null!=g){var m=this.filename,n="/",p=m;n&&(n="string"==typeof n?n:ea(n),p=m?z(n+"/"+m):n);m=fa(!0, !0);p=ha(p,(void 0!==m?m:438)&4095|32768,0);if(g){if("string"==typeof g){n=Array(g.length);for(var v=0,y=g.length;v{Ea||(fs=require("fs"),Ea=require("path"))},Ba=function(a,b){Fa();a=Ea.normalize(a);return fs.readFileSync(a,b?void 0:"utf8")},Da=a=>{a=Ba(a,!0);a.buffer||(a=new Uint8Array(a));return a},Ca=(a,b,c)=>{Fa();a=Ea.normalize(a);fs.readFile(a,function(d,f){d?c(d):b(f.buffer)})},1{var b=new XMLHttpRequest;b.open("GET",a,!1);b.send(null);return b.responseText},za&&(Da=a=>{var b=new XMLHttpRequest;b.open("GET",a,!1);b.responseType="arraybuffer";b.send(null);return new Uint8Array(b.response)}),Ca=(a,b,c)=>{var d=new XMLHttpRequest;d.open("GET",a,!0);d.responseType="arraybuffer"; d.onload=()=>{200==d.status||0==d.status&&d.response?b(d.response):c()};d.onerror=c;d.send(null)};var Ga=e.print||console.log.bind(console),Ha=e.printErr||console.warn.bind(console);Object.assign(e,va);va=null;e.thisProgram&&(wa=e.thisProgram);var Ia;e.wasmBinary&&(Ia=e.wasmBinary);var noExitRuntime=e.noExitRuntime||!0;"object"!=typeof WebAssembly&&E("no native wasm support detected");var Ja,Ka=!1,La="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0; function Ma(a,b,c){var d=b+c;for(c=b;a[c]&&!(c>=d);)++c;if(16f?d+=String.fromCharCode(f):(f-=65536,d+=String.fromCharCode(55296|f>>10,56320|f&1023))}}else d+=String.fromCharCode(f)}return d}function C(a,b){return a?Ma(u,a,b):""} function t(a,b,c,d){if(!(0=k){var q=a.charCodeAt(++h);k=65536+((k&1023)<<10)|q&1023}if(127>=k){if(c>=d)break;b[c++]=k}else{if(2047>=k){if(c+1>=d)break;b[c++]=192|k>>6}else{if(65535>=k){if(c+2>=d)break;b[c++]=224|k>>12}else{if(c+3>=d)break;b[c++]=240|k>>18;b[c++]=128|k>>12&63}b[c++]=128|k>>6&63}b[c++]=128|k&63}}b[c]=0;return c-f} function ca(a){for(var b=0,c=0;c=d?b++:2047>=d?b+=2:55296<=d&&57343>=d?(b+=4,++c):b+=3}return b}var Na,r,u,Oa,F,J,Pa,Qa;function Ra(){var a=Ja.buffer;Na=a;e.HEAP8=r=new Int8Array(a);e.HEAP16=Oa=new Int16Array(a);e.HEAP32=F=new Int32Array(a);e.HEAPU8=u=new Uint8Array(a);e.HEAPU16=new Uint16Array(a);e.HEAPU32=J=new Uint32Array(a);e.HEAPF32=Pa=new Float32Array(a);e.HEAPF64=Qa=new Float64Array(a)}var K,Sa=[],Ta=[],Ua=[]; function Va(){var a=e.preRun.shift();Sa.unshift(a)}var Wa=0,Xa=null,Ya=null;function E(a){if(e.onAbort)e.onAbort(a);a="Aborted("+a+")";Ha(a);Ka=!0;throw new WebAssembly.RuntimeError(a+". Build with -sASSERTIONS for more info.");}function Za(){return M.startsWith("data:application/octet-stream;base64,")}var M;M="sql-wasm.wasm";if(!Za()){var $a=M;M=e.locateFile?e.locateFile($a,D):D+$a} function ab(){var a=M;try{if(a==M&&Ia)return new Uint8Array(Ia);if(Da)return Da(a);throw"both async and sync fetching of the wasm failed";}catch(b){E(b)}} function bb(){if(!Ia&&(ya||za)){if("function"==typeof fetch&&!M.startsWith("file://"))return fetch(M,{credentials:"same-origin"}).then(function(a){if(!a.ok)throw"failed to load wasm binary file at '"+M+"'";return a.arrayBuffer()}).catch(function(){return ab()});if(Ca)return new Promise(function(a,b){Ca(M,function(c){a(new Uint8Array(c))},b)})}return Promise.resolve().then(function(){return ab()})}var N,O;function cb(a){for(;0>0];case "i8":return r[a>>0];case "i16":return Oa[a>>1];case "i32":return F[a>>2];case "i64":return F[a>>2];case "float":return Pa[a>>2];case "double":return Qa[a>>3];case "*":return J[a>>2];default:E("invalid type for getValue: "+b)}return null} function pa(a){var b="i32";b.endsWith("*")&&(b="*");switch(b){case "i1":r[a>>0]=0;break;case "i8":r[a>>0]=0;break;case "i16":Oa[a>>1]=0;break;case "i32":F[a>>2]=0;break;case "i64":O=[0,(N=0,1<=+Math.abs(N)?0>>0:~~+Math.ceil((N-+(~~N>>>0))/4294967296)>>>0:0)];F[a>>2]=O[0];F[a+4>>2]=O[1];break;case "float":Pa[a>>2]=0;break;case "double":Qa[a>>3]=0;break;case "*":J[a>>2]=0;break;default:E("invalid type for setValue: "+b)}} var db=(a,b)=>{for(var c=0,d=a.length-1;0<=d;d--){var f=a[d];"."===f?a.splice(d,1):".."===f?(a.splice(d,1),c++):c&&(a.splice(d,1),c--)}if(b)for(;c;c--)a.unshift("..");return a},z=a=>{var b="/"===a.charAt(0),c="/"===a.substr(-1);(a=db(a.split("/").filter(d=>!!d),!b).join("/"))||b||(a=".");a&&c&&(a+="/");return(b?"/":"")+a},eb=a=>{var b=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(a).slice(1);a=b[0];b=b[1];if(!a&&!b)return".";b&&(b=b.substr(0,b.length-1));return a+b},fb=a=>{if("/"=== a)return"/";a=z(a);a=a.replace(/\/$/,"");var b=a.lastIndexOf("/");return-1===b?a:a.substr(b+1)};function gb(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var a=new Uint8Array(1);return()=>{crypto.getRandomValues(a);return a[0]}}if(Aa)try{var b=require("crypto");return()=>b.randomBytes(1)[0]}catch(c){}return()=>E("randomDevice")} function hb(){for(var a="",b=!1,c=arguments.length-1;-1<=c&&!b;c--){b=0<=c?arguments[c]:"/";if("string"!=typeof b)throw new TypeError("Arguments to path.resolve must be strings");if(!b)return"";a=b+"/"+a;b="/"===b.charAt(0)}a=db(a.split("/").filter(d=>!!d),!b).join("/");return(b?"/":"")+a||"."}function ma(a,b){var c=Array(ca(a)+1);a=t(a,c,0,c.length);b&&(c.length=a);return c}var ib=[];function jb(a,b){ib[a]={input:[],output:[],Xa:b};lb(a,mb)} var mb={open:function(a){var b=ib[a.node.rdev];if(!b)throw new P(43);a.tty=b;a.seekable=!1},close:function(a){a.tty.Xa.fsync(a.tty)},fsync:function(a){a.tty.Xa.fsync(a.tty)},read:function(a,b,c,d){if(!a.tty||!a.tty.Xa.tb)throw new P(60);for(var f=0,h=0;h=b||(b=Math.max(b,c*(1048576>c?2:1.125)>>>0),0!=c&&(b=Math.max(b,256)),c=a.Ia,a.Ia=new Uint8Array(b),0=a.node.Ma)return 0;a=Math.min(a.node.Ma-f,d);if(8b)throw new P(28);return b},lb:function(a,b,c){Q.qb(a.node,b+c);a.node.Ma=Math.max(a.node.Ma,b+c)},bb:function(a,b,c,d,f){if(32768!==(a.node.mode&61440))throw new P(43);a=a.node.Ia;if(f&2||a.buffer!==Na){if(0{a=hb("/",a);if(!a)return{path:"",node:null};b=Object.assign({rb:!0,kb:0},b);if(8!!k),!1);for(var c=Ab,d="/", f=0;f{for(var b;;){if(a===a.parent)return a=a.Ra.ub,b?"/"!==a[a.length-1]?a+"/"+b:a+b:a;b=b?a.name+"/"+b:a.name;a=a.parent}},Fb=(a,b)=>{for(var c=0,d=0;d>>0)%T.length},Gb=a=>{var b= Fb(a.parent.id,a.name);if(T[b]===a)T[b]=a.Wa;else for(b=T[b];b;){if(b.Wa===a){b.Wa=a.Wa;break}b=b.Wa}},yb=(a,b)=>{var c;if(c=(c=Hb(a,"x"))?c:a.Ga.lookup?0:2)throw new P(c,a);for(c=T[Fb(a.id,b)];c;c=c.Wa){var d=c.name;if(c.parent.id===a.id&&d===b)return c}return a.Ga.lookup(a,b)},wb=(a,b,c,d)=>{a=new Ib(a,b,c,d);b=Fb(a.parent.id,a.name);a.Wa=T[b];return T[b]=a},Jb={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090},Kb=a=>{var b=["r","w","rw"][a&3];a&512&&(b+="w");return b},Hb=(a,b)=>{if(Db)return 0;if(!b.includes("r")|| a.mode&292){if(b.includes("w")&&!(a.mode&146)||b.includes("x")&&!(a.mode&73))return 2}else return 2;return 0},Lb=(a,b)=>{try{return yb(a,b),20}catch(c){}return Hb(a,"wx")},Mb=(a,b,c)=>{try{var d=yb(a,b)}catch(f){return f.Ka}if(a=Hb(a,"wx"))return a;if(c){if(16384!==(d.mode&61440))return 54;if(d===d.parent||"/"===ea(d))return 10}else if(16384===(d.mode&61440))return 31;return 0},Nb=(a=0)=>{for(;4096>=a;a++)if(!R[a])return a;throw new P(33);},Pb=(a,b)=>{Ob||(Ob=function(){this.$a={}},Ob.prototype={}, Object.defineProperties(Ob.prototype,{object:{get:function(){return this.node},set:function(c){this.node=c}},flags:{get:function(){return this.$a.flags},set:function(c){this.$a.flags=c}},position:{get:function(){return this.$a.position},set:function(c){this.$a.position=c}}}));a=Object.assign(new Ob,a);b=Nb(b);a.fd=b;return R[b]=a},vb={open:a=>{a.Ha=Bb[a.node.rdev].Ha;a.Ha.open&&a.Ha.open(a)},Ta:()=>{throw new P(70);}},lb=(a,b)=>{Bb[a]={Ha:b}},Qb=(a,b)=>{var c="/"===b,d=!b;if(c&&Ab)throw new P(10); if(!c&&!d){var f=U(b,{rb:!1});b=f.path;f=f.node;if(f.Va)throw new P(10);if(16384!==(f.mode&61440))throw new P(54);}b={type:a,Kb:{},ub:b,Eb:[]};a=a.Ra(b);a.Ra=b;b.root=a;c?Ab=a:f&&(f.Va=b,f.Ra&&f.Ra.Eb.push(b))},ha=(a,b,c)=>{var d=U(a,{parent:!0}).node;a=fb(a);if(!a||"."===a||".."===a)throw new P(28);var f=Lb(d,a);if(f)throw new P(f);if(!d.Ga.ab)throw new P(63);return d.Ga.ab(d,a,b,c)},V=(a,b)=>ha(a,(void 0!==b?b:511)&1023|16384,0),Rb=(a,b,c)=>{"undefined"==typeof c&&(c=b,b=438);ha(a,b|8192,c)},Sb= (a,b)=>{if(!hb(a))throw new P(44);var c=U(b,{parent:!0}).node;if(!c)throw new P(44);b=fb(b);var d=Lb(c,b);if(d)throw new P(d);if(!c.Ga.symlink)throw new P(63);c.Ga.symlink(c,b,a)},Tb=a=>{var b=U(a,{parent:!0}).node;a=fb(a);var c=yb(b,a),d=Mb(b,a,!0);if(d)throw new P(d);if(!b.Ga.rmdir)throw new P(63);if(c.Va)throw new P(10);b.Ga.rmdir(b,a);Gb(c)},ta=a=>{var b=U(a,{parent:!0}).node;if(!b)throw new P(44);a=fb(a);var c=yb(b,a),d=Mb(b,a,!1);if(d)throw new P(d);if(!b.Ga.unlink)throw new P(63);if(c.Va)throw new P(10); b.Ga.unlink(b,a);Gb(c)},Eb=a=>{a=U(a).node;if(!a)throw new P(44);if(!a.Ga.readlink)throw new P(28);return hb(ea(a.parent),a.Ga.readlink(a))},Ub=(a,b)=>{a=U(a,{Sa:!b}).node;if(!a)throw new P(44);if(!a.Ga.Pa)throw new P(63);return a.Ga.Pa(a)},Vb=a=>Ub(a,!0),ia=(a,b)=>{a="string"==typeof a?U(a,{Sa:!0}).node:a;if(!a.Ga.Oa)throw new P(63);a.Ga.Oa(a,{mode:b&4095|a.mode&-4096,timestamp:Date.now()})},Wb=(a,b)=>{if(0>b)throw new P(28);a="string"==typeof a?U(a,{Sa:!0}).node:a;if(!a.Ga.Oa)throw new P(63);if(16384=== (a.mode&61440))throw new P(31);if(32768!==(a.mode&61440))throw new P(28);var c=Hb(a,"w");if(c)throw new P(c);a.Ga.Oa(a,{size:b,timestamp:Date.now()})},ja=(a,b,c)=>{if(""===a)throw new P(44);if("string"==typeof b){var d=Jb[b];if("undefined"==typeof d)throw Error("Unknown file open mode: "+b);b=d}c=b&64?("undefined"==typeof c?438:c)&4095|32768:0;if("object"==typeof a)var f=a;else{a=z(a);try{f=U(a,{Sa:!(b&131072)}).node}catch(h){}}d=!1;if(b&64)if(f){if(b&128)throw new P(20);}else f=ha(a,c,0),d=!0;if(!f)throw new P(44); 8192===(f.mode&61440)&&(b&=-513);if(b&65536&&16384!==(f.mode&61440))throw new P(54);if(!d&&(c=f?40960===(f.mode&61440)?32:16384===(f.mode&61440)&&("r"!==Kb(b)||b&512)?31:Hb(f,Kb(b)):44))throw new P(c);b&512&&!d&&Wb(f,0);b&=-131713;f=Pb({node:f,path:ea(f),flags:b,seekable:!0,position:0,Ha:f.Ha,Ib:[],error:!1});f.Ha.open&&f.Ha.open(f);!e.logReadFiles||b&1||(Xb||(Xb={}),a in Xb||(Xb[a]=1));return f},la=a=>{if(null===a.fd)throw new P(8);a.hb&&(a.hb=null);try{a.Ha.close&&a.Ha.close(a)}catch(b){throw b; }finally{R[a.fd]=null}a.fd=null},Yb=(a,b,c)=>{if(null===a.fd)throw new P(8);if(!a.seekable||!a.Ha.Ta)throw new P(70);if(0!=c&&1!=c&&2!=c)throw new P(28);a.position=a.Ha.Ta(a,b,c);a.Ib=[]},Zb=(a,b,c,d,f)=>{if(0>d||0>f)throw new P(28);if(null===a.fd)throw new P(8);if(1===(a.flags&2097155))throw new P(8);if(16384===(a.node.mode&61440))throw new P(31);if(!a.Ha.read)throw new P(28);var h="undefined"!=typeof f;if(!h)f=a.position;else if(!a.seekable)throw new P(70);b=a.Ha.read(a,b,c,d,f);h||(a.position+= b);return b},ka=(a,b,c,d,f)=>{if(0>d||0>f)throw new P(28);if(null===a.fd)throw new P(8);if(0===(a.flags&2097155))throw new P(8);if(16384===(a.node.mode&61440))throw new P(31);if(!a.Ha.write)throw new P(28);a.seekable&&a.flags&1024&&Yb(a,0,2);var h="undefined"!=typeof f;if(!h)f=a.position;else if(!a.seekable)throw new P(70);b=a.Ha.write(a,b,c,d,f,void 0);h||(a.position+=b);return b},sa=a=>{var b="binary";if("utf8"!==b&&"binary"!==b)throw Error('Invalid encoding type "'+b+'"');var c;var d=ja(a,d||0); a=Ub(a).size;var f=new Uint8Array(a);Zb(d,f,0,a,0);"utf8"===b?c=Ma(f,0):"binary"===b&&(c=f);la(d);return c},$b=()=>{P||(P=function(a,b){this.node=b;this.Hb=function(c){this.Ka=c};this.Hb(a);this.message="FS error"},P.prototype=Error(),P.prototype.constructor=P,[44].forEach(a=>{xb[a]=new P(a);xb[a].stack=""}))},ac,fa=(a,b)=>{var c=0;a&&(c|=365);b&&(c|=146);return c},cc=(a,b,c)=>{a=z("/dev/"+a);var d=fa(!!b,!!c);bc||(bc=64);var f=bc++<<8|0;lb(f,{open:h=>{h.seekable=!1},close:()=> {c&&c.buffer&&c.buffer.length&&c(10)},read:(h,k,q,x)=>{for(var w=0,A=0;A{for(var w=0;w>2]=d.dev;F[c+8>>2]=d.ino;F[c+12>>2]=d.mode;J[c+16>>2]=d.nlink;F[c+20>>2]=d.uid;F[c+24>>2]=d.gid;F[c+28>>2]=d.rdev;O=[d.size>>>0,(N=d.size,1<=+Math.abs(N)?0>>0:~~+Math.ceil((N-+(~~N>>>0))/4294967296)>>>0:0)];F[c+40>>2]=O[0];F[c+44>>2]=O[1];F[c+48>>2]=4096;F[c+52>>2]=d.blocks;O=[Math.floor(d.atime.getTime()/1E3)>>>0,(N=Math.floor(d.atime.getTime()/ 1E3),1<=+Math.abs(N)?0>>0:~~+Math.ceil((N-+(~~N>>>0))/4294967296)>>>0:0)];F[c+56>>2]=O[0];F[c+60>>2]=O[1];J[c+64>>2]=0;O=[Math.floor(d.mtime.getTime()/1E3)>>>0,(N=Math.floor(d.mtime.getTime()/1E3),1<=+Math.abs(N)?0>>0:~~+Math.ceil((N-+(~~N>>>0))/4294967296)>>>0:0)];F[c+72>>2]=O[0];F[c+76>>2]=O[1];J[c+80>>2]=0;O=[Math.floor(d.ctime.getTime()/1E3)>>>0,(N=Math.floor(d.ctime.getTime()/1E3),1<=+Math.abs(N)? 0>>0:~~+Math.ceil((N-+(~~N>>>0))/4294967296)>>>0:0)];F[c+88>>2]=O[0];F[c+92>>2]=O[1];J[c+96>>2]=0;O=[d.ino>>>0,(N=d.ino,1<=+Math.abs(N)?0>>0:~~+Math.ceil((N-+(~~N>>>0))/4294967296)>>>0:0)];F[c+104>>2]=O[0];F[c+108>>2]=O[1];return 0}var fc=void 0;function Hc(){fc+=4;return F[fc-4>>2]}function X(a){a=R[a];if(!a)throw new P(8);return a}function Jc(a){return J[a>>2]+4294967296*F[a+4>>2]} function Kc(a){var b=ca(a)+1,c=da(b);c&&t(a,r,c,b);return c}function Lc(a,b,c){function d(x){return(x=x.toTimeString().match(/\(([A-Za-z ]+)\)$/))?x[1]:"GMT"}var f=(new Date).getFullYear(),h=new Date(f,0,1),k=new Date(f,6,1);f=h.getTimezoneOffset();var q=k.getTimezoneOffset();F[a>>2]=60*Math.max(f,q);F[b>>2]=Number(f!=q);a=d(h);b=d(k);a=Kc(a);b=Kc(b);q>2]=a,J[c+4>>2]=b):(J[c>>2]=b,J[c+4>>2]=a)}function Mc(a,b,c){Mc.Bb||(Mc.Bb=!0,Lc(a,b,c))}var Nc; Nc=Aa?()=>{var a=process.hrtime();return 1E3*a[0]+a[1]/1E6}:()=>performance.now();var Oc={};function Pc(){if(!Qc){var a={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:wa||"./this.program"},b;for(b in Oc)void 0===Oc[b]?delete a[b]:a[b]=Oc[b];var c=[];for(b in a)c.push(b+"="+a[b]);Qc=c}return Qc}var Qc,Y=void 0,Rc=[]; function ua(a,b){if(!Y){Y=new WeakMap;var c=K.length;if(Y)for(var d=0;d<0+c;d++){var f=K.get(d);f&&Y.set(f,d)}}if(Y.has(a))return Y.get(a);if(Rc.length)c=Rc.pop();else{try{K.grow(1)}catch(q){if(!(q instanceof RangeError))throw q;throw"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.";}c=K.length-1}try{K.set(c,a)}catch(q){if(!(q instanceof TypeError))throw q;if("function"==typeof WebAssembly.Function){d=WebAssembly.Function;f={i:"i32",j:"i64",f:"f32",d:"f64",p:"i32"};for(var h={parameters:[],results:"v"== b[0]?[]:[f[b[0]]]},k=1;kk?d.push(k):d.push(k%128|128,k>>7);for(k=0;kf?b.push(f):b.push(f%128|128,f>>7);b.push.apply(b,d);b.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);b=new WebAssembly.Module(new Uint8Array(b));b=(new WebAssembly.Instance(b,{e:{f:a}})).exports.f}K.set(c, b)}Y.set(a,c);return c}function ra(a){Y.delete(K.get(a));Rc.push(a)}var Sc=0,Tc=1;function aa(a){var b=Sc==Tc?B(a.length):da(a.length);a.subarray||a.slice||(a=new Uint8Array(a));u.set(a,b);return b} function Uc(a,b,c,d){var f={string:w=>{var A=0;if(null!==w&&void 0!==w&&0!==w){var S=(w.length<<2)+1;A=B(S);t(w,u,A,S)}return A},array:w=>{var A=B(w.length);r.set(w,A);return A}};a=e["_"+a];var h=[],k=0;if(d)for(var q=0;q{V("/dev");lb(259,{read:()=>0,write:(b,c,d,f)=>f});Rb("/dev/null",259);jb(1280,tb);jb(1536,ub);Rb("/dev/tty",1280);Rb("/dev/tty1",1536);var a=gb();cc("random",a);cc("urandom",a);V("/dev/shm");V("/dev/shm/tmp")})();(()=>{V("/proc");var a=V("/proc/self");V("/proc/self/fd");Qb({Ra:()=>{var b=wb(a,"fd",16895,73);b.Ga={lookup:(c,d)=>{var f=R[+d];if(!f)throw new P(8);c={parent:null,Ra:{ub:"fake"},Ga:{readlink:()=>f.path}};return c.parent=c}};return b}},"/proc/self/fd")})(); var Wc={a:function(a,b,c,d){E("Assertion failed: "+C(a)+", at: "+[b?C(b):"unknown filename",c,d?C(d):"unknown function"])},h:function(a,b){try{return a=C(a),ia(a,b),0}catch(c){if("undefined"==typeof W||!(c instanceof P))throw c;return-c.Ka}},H:function(a,b,c){try{b=C(b);b=dc(a,b);if(c&-8)return-28;var d=U(b,{Sa:!0}).node;if(!d)return-44;a="";c&4&&(a+="r");c&2&&(a+="w");c&1&&(a+="x");return a&&Hb(d,a)?-2:0}catch(f){if("undefined"==typeof W||!(f instanceof P))throw f;return-f.Ka}},i:function(a,b){try{var c= R[a];if(!c)throw new P(8);ia(c.node,b);return 0}catch(d){if("undefined"==typeof W||!(d instanceof P))throw d;return-d.Ka}},g:function(a){try{var b=R[a];if(!b)throw new P(8);var c=b.node;var d="string"==typeof c?U(c,{Sa:!0}).node:c;if(!d.Ga.Oa)throw new P(63);d.Ga.Oa(d,{timestamp:Date.now()});return 0}catch(f){if("undefined"==typeof W||!(f instanceof P))throw f;return-f.Ka}},b:function(a,b,c){fc=c;try{var d=X(a);switch(b){case 0:var f=Hc();return 0>f?-28:Pb(d,f).fd;case 1:case 2:return 0;case 3:return d.flags; case 4:return f=Hc(),d.flags|=f,0;case 5:return f=Hc(),Oa[f+0>>1]=2,0;case 6:case 7:return 0;case 16:case 8:return-28;case 9:return F[Vc()>>2]=28,-1;default:return-28}}catch(h){if("undefined"==typeof W||!(h instanceof P))throw h;return-h.Ka}},G:function(a,b){try{var c=X(a);return ec(Ub,c.path,b)}catch(d){if("undefined"==typeof W||!(d instanceof P))throw d;return-d.Ka}},l:function(a,b,c){try{b=c+2097152>>>0<4194305-!!b?(b>>>0)+4294967296*c:NaN;if(isNaN(b))return-61;var d=R[a];if(!d)throw new P(8); if(0===(d.flags&2097155))throw new P(28);Wb(d.node,b);return 0}catch(f){if("undefined"==typeof W||!(f instanceof P))throw f;return-f.Ka}},B:function(a,b){try{if(0===b)return-28;var c=ca("/")+1;if(b=d)return-28;var f=Eb(b),h=Math.min(d, ca(f)),k=r[c+h];t(f,u,c,d+1);r[c+h]=k;return h}catch(q){if("undefined"==typeof W||!(q instanceof P))throw q;return-q.Ka}},s:function(a){try{return a=C(a),Tb(a),0}catch(b){if("undefined"==typeof W||!(b instanceof P))throw b;return-b.Ka}},F:function(a,b){try{return a=C(a),ec(Ub,a,b)}catch(c){if("undefined"==typeof W||!(c instanceof P))throw c;return-c.Ka}},p:function(a,b,c){try{return b=C(b),b=dc(a,b),0===c?ta(b):512===c?Tb(b):E("Invalid flags passed to unlinkat"),0}catch(d){if("undefined"==typeof W|| !(d instanceof P))throw d;return-d.Ka}},o:function(a,b,c){try{b=C(b);b=dc(a,b,!0);if(c){var d=Jc(c),f=F[c+8>>2];h=1E3*d+f/1E6;c+=16;d=Jc(c);f=F[c+8>>2];k=1E3*d+f/1E6}else var h=Date.now(),k=h;a=h;var q=U(b,{Sa:!0}).node;q.Ga.Oa(q,{timestamp:Math.max(a,k)});return 0}catch(x){if("undefined"==typeof W||!(x instanceof P))throw x;return-x.Ka}},e:function(){return Date.now()},j:function(a,b){a=new Date(1E3*Jc(a));F[b>>2]=a.getSeconds();F[b+4>>2]=a.getMinutes();F[b+8>>2]=a.getHours();F[b+12>>2]=a.getDate(); F[b+16>>2]=a.getMonth();F[b+20>>2]=a.getFullYear()-1900;F[b+24>>2]=a.getDay();var c=new Date(a.getFullYear(),0,1);F[b+28>>2]=(a.getTime()-c.getTime())/864E5|0;F[b+36>>2]=-(60*a.getTimezoneOffset());var d=(new Date(a.getFullYear(),6,1)).getTimezoneOffset();c=c.getTimezoneOffset();F[b+32>>2]=(d!=c&&a.getTimezoneOffset()==Math.min(c,d))|0},w:function(a,b,c,d,f,h){try{var k=X(d);if(0!==(b&2)&&0===(c&2)&&2!==(k.flags&2097155))throw new P(2);if(1===(k.flags&2097155))throw new P(2);if(!k.Ha.bb)throw new P(43); var q=k.Ha.bb(k,a,f,b,c);var x=q.Fb;F[h>>2]=q.vb;return x}catch(w){if("undefined"==typeof W||!(w instanceof P))throw w;return-w.Ka}},x:function(a,b,c,d,f,h){try{var k=X(f);if(c&2){var q=u.slice(a,a+b);k&&k.Ha.cb&&k.Ha.cb(k,q,h,b,d)}}catch(x){if("undefined"==typeof W||!(x instanceof P))throw x;return-x.Ka}},n:Mc,q:function(){return 2147483648},d:Nc,c:function(a){var b=u.length;a>>>=0;if(2147483648=c;c*=2){var d=b*(1+.2/c);d=Math.min(d,a+100663296);var f=Math;d=Math.max(a, d);f=f.min.call(f,2147483648,d+(65536-d%65536)%65536);a:{try{Ja.grow(f-Na.byteLength+65535>>>16);Ra();var h=1;break a}catch(k){}h=void 0}if(h)return!0}return!1},z:function(a,b){var c=0;Pc().forEach(function(d,f){var h=b+c;f=J[a+4*f>>2]=h;for(h=0;h>0]=d.charCodeAt(h);r[f>>0]=0;c+=d.length+1});return 0},A:function(a,b){var c=Pc();J[a>>2]=c.length;var d=0;c.forEach(function(f){d+=f.length+1});J[b>>2]=d;return 0},f:function(a){try{var b=X(a);la(b);return 0}catch(c){if("undefined"== typeof W||!(c instanceof P))throw c;return c.Ka}},m:function(a,b){try{var c=X(a);r[b>>0]=c.tty?2:16384===(c.mode&61440)?3:40960===(c.mode&61440)?7:4;return 0}catch(d){if("undefined"==typeof W||!(d instanceof P))throw d;return d.Ka}},u:function(a,b,c,d){try{a:{var f=X(a);a=b;for(var h=b=0;h>2],q=J[a+4>>2];a+=8;var x=Zb(f,r,k,q);if(0>x){var w=-1;break a}b+=x;if(x>2]=w;return 0}catch(A){if("undefined"==typeof W||!(A instanceof P))throw A;return A.Ka}},k:function(a, b,c,d,f){try{b=c+2097152>>>0<4194305-!!b?(b>>>0)+4294967296*c:NaN;if(isNaN(b))return 61;var h=X(a);Yb(h,b,d);O=[h.position>>>0,(N=h.position,1<=+Math.abs(N)?0>>0:~~+Math.ceil((N-+(~~N>>>0))/4294967296)>>>0:0)];F[f>>2]=O[0];F[f+4>>2]=O[1];h.hb&&0===b&&0===d&&(h.hb=null);return 0}catch(k){if("undefined"==typeof W||!(k instanceof P))throw k;return k.Ka}},C:function(a){try{var b=X(a);return b.Ha&&b.Ha.fsync?b.Ha.fsync(b):0}catch(c){if("undefined"== typeof W||!(c instanceof P))throw c;return c.Ka}},r:function(a,b,c,d){try{a:{var f=X(a);a=b;for(var h=b=0;h>2],q=J[a+4>>2];a+=8;var x=ka(f,r,k,q);if(0>x){var w=-1;break a}b+=x}w=b}J[d>>2]=w;return 0}catch(A){if("undefined"==typeof W||!(A instanceof P))throw A;return A.Ka}}}; (function(){function a(f){e.asm=f.exports;Ja=e.asm.I;Ra();K=e.asm.Aa;Ta.unshift(e.asm.J);Wa--;e.monitorRunDependencies&&e.monitorRunDependencies(Wa);0==Wa&&(null!==Xa&&(clearInterval(Xa),Xa=null),Ya&&(f=Ya,Ya=null,f()))}function b(f){a(f.instance)}function c(f){return bb().then(function(h){return WebAssembly.instantiate(h,d)}).then(function(h){return h}).then(f,function(h){Ha("failed to asynchronously prepare wasm: "+h);E(h)})}var d={a:Wc};Wa++;e.monitorRunDependencies&&e.monitorRunDependencies(Wa); if(e.instantiateWasm)try{return e.instantiateWasm(d,a)}catch(f){return Ha("Module.instantiateWasm callback failed with error: "+f),!1}(function(){return Ia||"function"!=typeof WebAssembly.instantiateStreaming||Za()||M.startsWith("file://")||Aa||"function"!=typeof fetch?c(b):fetch(M,{credentials:"same-origin"}).then(function(f){return WebAssembly.instantiateStreaming(f,d).then(b,function(h){Ha("wasm streaming compile failed: "+h);Ha("falling back to ArrayBuffer instantiation");return c(b)})})})(); return{}})();e.___wasm_call_ctors=function(){return(e.___wasm_call_ctors=e.asm.J).apply(null,arguments)};e._sqlite3_free=function(){return(e._sqlite3_free=e.asm.K).apply(null,arguments)};e._sqlite3_value_double=function(){return(e._sqlite3_value_double=e.asm.L).apply(null,arguments)};e._sqlite3_value_text=function(){return(e._sqlite3_value_text=e.asm.M).apply(null,arguments)};var Vc=e.___errno_location=function(){return(Vc=e.___errno_location=e.asm.N).apply(null,arguments)}; e._sqlite3_prepare_v2=function(){return(e._sqlite3_prepare_v2=e.asm.O).apply(null,arguments)};e._sqlite3_step=function(){return(e._sqlite3_step=e.asm.P).apply(null,arguments)};e._sqlite3_finalize=function(){return(e._sqlite3_finalize=e.asm.Q).apply(null,arguments)};e._sqlite3_reset=function(){return(e._sqlite3_reset=e.asm.R).apply(null,arguments)};e._sqlite3_value_int=function(){return(e._sqlite3_value_int=e.asm.S).apply(null,arguments)}; e._sqlite3_clear_bindings=function(){return(e._sqlite3_clear_bindings=e.asm.T).apply(null,arguments)};e._sqlite3_value_blob=function(){return(e._sqlite3_value_blob=e.asm.U).apply(null,arguments)};e._sqlite3_value_bytes=function(){return(e._sqlite3_value_bytes=e.asm.V).apply(null,arguments)};e._sqlite3_value_type=function(){return(e._sqlite3_value_type=e.asm.W).apply(null,arguments)};e._sqlite3_result_blob=function(){return(e._sqlite3_result_blob=e.asm.X).apply(null,arguments)}; e._sqlite3_result_double=function(){return(e._sqlite3_result_double=e.asm.Y).apply(null,arguments)};e._sqlite3_result_error=function(){return(e._sqlite3_result_error=e.asm.Z).apply(null,arguments)};e._sqlite3_result_int=function(){return(e._sqlite3_result_int=e.asm._).apply(null,arguments)};e._sqlite3_result_int64=function(){return(e._sqlite3_result_int64=e.asm.$).apply(null,arguments)};e._sqlite3_result_null=function(){return(e._sqlite3_result_null=e.asm.aa).apply(null,arguments)}; e._sqlite3_result_text=function(){return(e._sqlite3_result_text=e.asm.ba).apply(null,arguments)};e._sqlite3_sql=function(){return(e._sqlite3_sql=e.asm.ca).apply(null,arguments)};e._sqlite3_aggregate_context=function(){return(e._sqlite3_aggregate_context=e.asm.da).apply(null,arguments)};e._sqlite3_column_count=function(){return(e._sqlite3_column_count=e.asm.ea).apply(null,arguments)};e._sqlite3_data_count=function(){return(e._sqlite3_data_count=e.asm.fa).apply(null,arguments)}; e._sqlite3_column_blob=function(){return(e._sqlite3_column_blob=e.asm.ga).apply(null,arguments)};e._sqlite3_column_bytes=function(){return(e._sqlite3_column_bytes=e.asm.ha).apply(null,arguments)};e._sqlite3_column_double=function(){return(e._sqlite3_column_double=e.asm.ia).apply(null,arguments)};e._sqlite3_column_text=function(){return(e._sqlite3_column_text=e.asm.ja).apply(null,arguments)};e._sqlite3_column_type=function(){return(e._sqlite3_column_type=e.asm.ka).apply(null,arguments)}; e._sqlite3_column_name=function(){return(e._sqlite3_column_name=e.asm.la).apply(null,arguments)};e._sqlite3_bind_blob=function(){return(e._sqlite3_bind_blob=e.asm.ma).apply(null,arguments)};e._sqlite3_bind_double=function(){return(e._sqlite3_bind_double=e.asm.na).apply(null,arguments)};e._sqlite3_bind_int=function(){return(e._sqlite3_bind_int=e.asm.oa).apply(null,arguments)};e._sqlite3_bind_text=function(){return(e._sqlite3_bind_text=e.asm.pa).apply(null,arguments)}; e._sqlite3_bind_parameter_index=function(){return(e._sqlite3_bind_parameter_index=e.asm.qa).apply(null,arguments)};e._sqlite3_normalized_sql=function(){return(e._sqlite3_normalized_sql=e.asm.ra).apply(null,arguments)};e._sqlite3_errmsg=function(){return(e._sqlite3_errmsg=e.asm.sa).apply(null,arguments)};e._sqlite3_exec=function(){return(e._sqlite3_exec=e.asm.ta).apply(null,arguments)};e._sqlite3_changes=function(){return(e._sqlite3_changes=e.asm.ua).apply(null,arguments)}; e._sqlite3_close_v2=function(){return(e._sqlite3_close_v2=e.asm.va).apply(null,arguments)};e._sqlite3_create_function_v2=function(){return(e._sqlite3_create_function_v2=e.asm.wa).apply(null,arguments)};e._sqlite3_open=function(){return(e._sqlite3_open=e.asm.xa).apply(null,arguments)};var da=e._malloc=function(){return(da=e._malloc=e.asm.ya).apply(null,arguments)},ba=e._free=function(){return(ba=e._free=e.asm.za).apply(null,arguments)}; e._RegisterExtensionFunctions=function(){return(e._RegisterExtensionFunctions=e.asm.Ba).apply(null,arguments)};var zb=e._emscripten_builtin_memalign=function(){return(zb=e._emscripten_builtin_memalign=e.asm.Ca).apply(null,arguments)},oa=e.stackSave=function(){return(oa=e.stackSave=e.asm.Da).apply(null,arguments)},qa=e.stackRestore=function(){return(qa=e.stackRestore=e.asm.Ea).apply(null,arguments)},B=e.stackAlloc=function(){return(B=e.stackAlloc=e.asm.Fa).apply(null,arguments)};e.UTF8ToString=C; e.stackAlloc=B;e.stackSave=oa;e.stackRestore=qa;e.cwrap=function(a,b,c,d){c=c||[];var f=c.every(h=>"number"===h||"boolean"===h);return"string"!==b&&f&&!d?e["_"+a]:function(){return Uc(a,b,c,arguments)}};var Xc;Ya=function Yc(){Xc||Zc();Xc||(Ya=Yc)}; function Zc(){function a(){if(!Xc&&(Xc=!0,e.calledRun=!0,!Ka)){e.noFSInit||ac||(ac=!0,$b(),e.stdin=e.stdin,e.stdout=e.stdout,e.stderr=e.stderr,e.stdin?cc("stdin",e.stdin):Sb("/dev/tty","/dev/stdin"),e.stdout?cc("stdout",null,e.stdout):Sb("/dev/tty","/dev/stdout"),e.stderr?cc("stderr",null,e.stderr):Sb("/dev/tty1","/dev/stderr"),ja("/dev/stdin",0),ja("/dev/stdout",1),ja("/dev/stderr",1));Db=!1;cb(Ta);if(e.onRuntimeInitialized)e.onRuntimeInitialized();if(e.postRun)for("function"==typeof e.postRun&& (e.postRun=[e.postRun]);e.postRun.length;){var b=e.postRun.shift();Ua.unshift(b)}cb(Ua)}}if(!(0 { "use strict"; const { Duplex: DuplexStream, Readable: ReadableStream, Writable: WritableStream, } = __webpack_require__(12781); const { CHANNEL_EXTENDED_DATATYPE: { STDERR }, } = __webpack_require__(3190); const { bufferSlice } = __webpack_require__(39205); const PACKET_SIZE = 32 * 1024; const MAX_WINDOW = 2 * 1024 * 1024; const WINDOW_THRESHOLD = MAX_WINDOW / 2; class ClientStderr extends ReadableStream { constructor(channel, streamOpts) { super(streamOpts); this._channel = channel; } _read(n) { if (this._channel._waitChanDrain) { this._channel._waitChanDrain = false; if (this._channel.incoming.window <= WINDOW_THRESHOLD) windowAdjust(this._channel); } } } class ServerStderr extends WritableStream { constructor(channel) { super({ highWaterMark: MAX_WINDOW }); this._channel = channel; } _write(data, encoding, cb) { const channel = this._channel; const protocol = channel._client._protocol; const outgoing = channel.outgoing; const packetSize = outgoing.packetSize; const id = outgoing.id; let window = outgoing.window; const len = data.length; let p = 0; if (outgoing.state !== 'open') return; while (len - p > 0 && window > 0) { let sliceLen = len - p; if (sliceLen > window) sliceLen = window; if (sliceLen > packetSize) sliceLen = packetSize; if (p === 0 && sliceLen === len) protocol.channelExtData(id, data, STDERR); else protocol.channelExtData(id, bufferSlice(data, p, p + sliceLen), STDERR); p += sliceLen; window -= sliceLen; } outgoing.window = window; if (len - p > 0) { if (window === 0) channel._waitWindow = true; if (p > 0) channel._chunkErr = bufferSlice(data, p, len); else channel._chunkErr = data; channel._chunkcbErr = cb; return; } cb(); } } class Channel extends DuplexStream { constructor(client, info, opts) { const streamOpts = { highWaterMark: MAX_WINDOW, allowHalfOpen: (!opts || (opts && opts.allowHalfOpen !== false)), emitClose: false, }; super(streamOpts); this.allowHalfOpen = streamOpts.allowHalfOpen; const server = !!(opts && opts.server); this.server = server; this.type = info.type; this.subtype = undefined; /* incoming and outgoing contain these properties: { id: undefined, window: undefined, packetSize: undefined, state: 'closed' } */ this.incoming = info.incoming; this.outgoing = info.outgoing; this._callbacks = []; this._client = client; this._hasX11 = false; this._exit = { code: undefined, signal: undefined, dump: undefined, desc: undefined, }; this.stdin = this.stdout = this; if (server) this.stderr = new ServerStderr(this); else this.stderr = new ClientStderr(this, streamOpts); // Outgoing data this._waitWindow = false; // SSH-level backpressure // Incoming data this._waitChanDrain = false; // Channel Readable side backpressure this._chunk = undefined; this._chunkcb = undefined; this._chunkErr = undefined; this._chunkcbErr = undefined; this.on('finish', onFinish) .on('prefinish', onFinish); // For node v0.11+ this.on('end', onEnd).on('close', onEnd); } _read(n) { if (this._waitChanDrain) { this._waitChanDrain = false; if (this.incoming.window <= WINDOW_THRESHOLD) windowAdjust(this); } } _write(data, encoding, cb) { const protocol = this._client._protocol; const outgoing = this.outgoing; const packetSize = outgoing.packetSize; const id = outgoing.id; let window = outgoing.window; const len = data.length; let p = 0; if (outgoing.state !== 'open') return; while (len - p > 0 && window > 0) { let sliceLen = len - p; if (sliceLen > window) sliceLen = window; if (sliceLen > packetSize) sliceLen = packetSize; if (p === 0 && sliceLen === len) protocol.channelData(id, data); else protocol.channelData(id, bufferSlice(data, p, p + sliceLen)); p += sliceLen; window -= sliceLen; } outgoing.window = window; if (len - p > 0) { if (window === 0) this._waitWindow = true; if (p > 0) this._chunk = bufferSlice(data, p, len); else this._chunk = data; this._chunkcb = cb; return; } cb(); } eof() { if (this.outgoing.state === 'open') { this.outgoing.state = 'eof'; this._client._protocol.channelEOF(this.outgoing.id); } } close() { if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') { this.outgoing.state = 'closing'; this._client._protocol.channelClose(this.outgoing.id); } } destroy() { this.end(); this.close(); return this; } // Session type-specific methods ============================================= setWindow(rows, cols, height, width) { if (this.server) throw new Error('Client-only method called in server mode'); if (this.type === 'session' && (this.subtype === 'shell' || this.subtype === 'exec') && this.writable && this.outgoing.state === 'open') { this._client._protocol.windowChange(this.outgoing.id, rows, cols, height, width); } } signal(signalName) { if (this.server) throw new Error('Client-only method called in server mode'); if (this.type === 'session' && this.writable && this.outgoing.state === 'open') { this._client._protocol.signal(this.outgoing.id, signalName); } } exit(statusOrSignal, coreDumped, msg) { if (!this.server) throw new Error('Server-only method called in client mode'); if (this.type === 'session' && this.writable && this.outgoing.state === 'open') { if (typeof statusOrSignal === 'number') { this._client._protocol.exitStatus(this.outgoing.id, statusOrSignal); } else { this._client._protocol.exitSignal(this.outgoing.id, statusOrSignal, coreDumped, msg); } } } } function onFinish() { this.eof(); if (this.server || !this.allowHalfOpen) this.close(); this.writable = false; } function onEnd() { this.readable = false; } function windowAdjust(self) { if (self.outgoing.state === 'closed') return; const amt = MAX_WINDOW - self.incoming.window; if (amt <= 0) return; self.incoming.window += amt; self._client._protocol.channelWindowAdjust(self.outgoing.id, amt); } module.exports = { Channel, MAX_WINDOW, PACKET_SIZE, windowAdjust, WINDOW_THRESHOLD, }; /***/ }), /***/ 81119: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const { Socket } = __webpack_require__(41808); const { Duplex } = __webpack_require__(12781); const { resolve } = __webpack_require__(71017); const { readFile } = __webpack_require__(57147); const { execFile, spawn } = __webpack_require__(32081); const { isParsedKey, parseKey } = __webpack_require__(13781); const { makeBufferParser, readUInt32BE, writeUInt32BE, writeUInt32LE, } = __webpack_require__(39205); function once(cb) { let called = false; return (...args) => { if (called) return; called = true; cb(...args); }; } function concat(buf1, buf2) { const combined = Buffer.allocUnsafe(buf1.length + buf2.length); buf1.copy(combined, 0); buf2.copy(combined, buf1.length); return combined; } function noop() {} const EMPTY_BUF = Buffer.alloc(0); const binaryParser = makeBufferParser(); class BaseAgent { getIdentities(cb) { cb(new Error('Missing getIdentities() implementation')); } sign(pubKey, data, options, cb) { if (typeof options === 'function') cb = options; cb(new Error('Missing sign() implementation')); } } class OpenSSHAgent extends BaseAgent { constructor(socketPath) { super(); this.socketPath = socketPath; } getStream(cb) { cb = once(cb); const sock = new Socket(); sock.on('connect', () => { cb(null, sock); }); sock.on('close', onFail) .on('end', onFail) .on('error', onFail); sock.connect(this.socketPath); function onFail() { try { sock.destroy(); } catch {} cb(new Error('Failed to connect to agent')); } } getIdentities(cb) { cb = once(cb); this.getStream((err, stream) => { function onFail(err) { if (stream) { try { stream.destroy(); } catch {} } if (!err) err = new Error('Failed to retrieve identities from agent'); cb(err); } if (err) return onFail(err); const protocol = new AgentProtocol(true); protocol.on('error', onFail); protocol.pipe(stream).pipe(protocol); stream.on('close', onFail) .on('end', onFail) .on('error', onFail); protocol.getIdentities((err, keys) => { if (err) return onFail(err); try { stream.destroy(); } catch {} cb(null, keys); }); }); } sign(pubKey, data, options, cb) { if (typeof options === 'function') { cb = options; options = undefined; } else if (typeof options !== 'object' || options === null) { options = undefined; } cb = once(cb); this.getStream((err, stream) => { function onFail(err) { if (stream) { try { stream.destroy(); } catch {} } if (!err) err = new Error('Failed to sign data with agent'); cb(err); } if (err) return onFail(err); const protocol = new AgentProtocol(true); protocol.on('error', onFail); protocol.pipe(stream).pipe(protocol); stream.on('close', onFail) .on('end', onFail) .on('error', onFail); protocol.sign(pubKey, data, options, (err, sig) => { if (err) return onFail(err); try { stream.destroy(); } catch {} cb(null, sig); }); }); } } const PageantAgent = (() => { const RET_ERR_BADARGS = 10; const RET_ERR_UNAVAILABLE = 11; const RET_ERR_NOMAP = 12; const RET_ERR_BINSTDIN = 13; const RET_ERR_BINSTDOUT = 14; const RET_ERR_BADLEN = 15; const EXEPATH = resolve(__dirname, '..', 'util/pagent.exe'); const ERROR = { [RET_ERR_BADARGS]: new Error('Invalid pagent.exe arguments'), [RET_ERR_UNAVAILABLE]: new Error('Pageant is not running'), [RET_ERR_NOMAP]: new Error('pagent.exe could not create an mmap'), [RET_ERR_BINSTDIN]: new Error('pagent.exe could not set mode for stdin'), [RET_ERR_BINSTDOUT]: new Error('pagent.exe could not set mode for stdout'), [RET_ERR_BADLEN]: new Error('pagent.exe did not get expected input payload'), }; function destroy(stream) { stream.buffer = null; if (stream.proc) { stream.proc.kill(); stream.proc = undefined; } } class PageantSocket extends Duplex { constructor() { super(); this.proc = undefined; this.buffer = null; } _read(n) {} _write(data, encoding, cb) { if (this.buffer === null) { this.buffer = data; } else { const newBuffer = Buffer.allocUnsafe(this.buffer.length + data.length); this.buffer.copy(newBuffer, 0); data.copy(newBuffer, this.buffer.length); this.buffer = newBuffer; } // Wait for at least all length bytes if (this.buffer.length < 4) return cb(); const len = readUInt32BE(this.buffer, 0); // Make sure we have a full message before querying pageant if ((this.buffer.length - 4) < len) return cb(); data = this.buffer.slice(0, 4 + len); if (this.buffer.length > (4 + len)) return cb(new Error('Unexpected multiple agent requests')); this.buffer = null; let error; const proc = this.proc = spawn(EXEPATH, [ data.length ]); proc.stdout.on('data', (data) => { this.push(data); }); proc.on('error', (err) => { error = err; cb(error); }); proc.on('close', (code) => { this.proc = undefined; if (!error) { if (error = ERROR[code]) return cb(error); cb(); } }); proc.stdin.end(data); } _final(cb) { destroy(this); cb(); } _destroy(err, cb) { destroy(this); cb(); } } return class PageantAgent extends OpenSSHAgent { getStream(cb) { cb(null, new PageantSocket()); } }; })(); const CygwinAgent = (() => { const RE_CYGWIN_SOCK = /^!(\d+) s ([A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8})/; return class CygwinAgent extends OpenSSHAgent { getStream(cb) { cb = once(cb); // The cygwin ssh-agent connection process looks like this: // 1. Read the "socket" as a file to get the underlying TCP port and a // special "secret" that must be sent to the TCP server. // 2. Connect to the server listening on localhost at the TCP port. // 3. Send the "secret" to the server. // 4. The server sends back the same "secret". // 5. Send three 32-bit integer values of zero. This is ordinarily the // pid, uid, and gid of this process, but cygwin will actually // send us the correct values as a response. // 6. The server sends back the pid, uid, gid. // 7. Disconnect. // 8. Repeat steps 2-6, except send the received pid, uid, and gid in // step 5 instead of zeroes. // 9. Connection is ready to be used. let socketPath = this.socketPath; let triedCygpath = false; readFile(socketPath, function readCygsocket(err, data) { if (err) { if (triedCygpath) return cb(new Error('Invalid cygwin unix socket path')); // Try using `cygpath` to convert a possible *nix-style path to the // real Windows path before giving up ... execFile('cygpath', ['-w', socketPath], (err, stdout, stderr) => { if (err || stdout.length === 0) return cb(new Error('Invalid cygwin unix socket path')); triedCygpath = true; socketPath = stdout.toString().replace(/[\r\n]/g, ''); readFile(socketPath, readCygsocket); }); return; } const m = RE_CYGWIN_SOCK.exec(data.toString('ascii')); if (!m) return cb(new Error('Malformed cygwin unix socket file')); let state; let bc = 0; let isRetrying = false; const inBuf = []; let sock; // Use 0 for pid, uid, and gid to ensure we get an error and also // a valid uid and gid from cygwin so that we don't have to figure it // out ourselves let credsBuf = Buffer.alloc(12); // Parse cygwin unix socket file contents const port = parseInt(m[1], 10); const secret = m[2].replace(/-/g, ''); const secretBuf = Buffer.allocUnsafe(16); for (let i = 0, j = 0; j < 32; ++i, j += 2) secretBuf[i] = parseInt(secret.substring(j, j + 2), 16); // Convert to host order (always LE for Windows) for (let i = 0; i < 16; i += 4) writeUInt32LE(secretBuf, readUInt32BE(secretBuf, i), i); tryConnect(); function _onconnect() { bc = 0; state = 'secret'; sock.write(secretBuf); } function _ondata(data) { bc += data.length; if (state === 'secret') { // The secret we sent is echoed back to us by cygwin, not sure of // the reason for that, but we ignore it nonetheless ... if (bc === 16) { bc = 0; state = 'creds'; sock.write(credsBuf); } return; } if (state === 'creds') { // If this is the first attempt, make sure to gather the valid // uid and gid for our next attempt if (!isRetrying) inBuf.push(data); if (bc === 12) { sock.removeListener('connect', _onconnect); sock.removeListener('data', _ondata); sock.removeListener('error', onFail); sock.removeListener('end', onFail); sock.removeListener('close', onFail); if (isRetrying) return cb(null, sock); isRetrying = true; credsBuf = Buffer.concat(inBuf); writeUInt32LE(credsBuf, process.pid, 0); sock.on('error', () => {}); sock.destroy(); tryConnect(); } } } function onFail() { cb(new Error('Problem negotiating cygwin unix socket security')); } function tryConnect() { sock = new Socket(); sock.on('connect', _onconnect); sock.on('data', _ondata); sock.on('error', onFail); sock.on('end', onFail); sock.on('close', onFail); sock.connect(port); } }); } }; })(); // Format of `//./pipe/ANYTHING`, with forward slashes and backward slashes // being interchangeable const WINDOWS_PIPE_REGEX = /^[/\\][/\\]\.[/\\]pipe[/\\].+/; function createAgent(path) { if (process.platform === 'win32' && !WINDOWS_PIPE_REGEX.test(path)) { return (path === 'pageant' ? new PageantAgent() : new CygwinAgent(path)); } return new OpenSSHAgent(path); } const AgentProtocol = (() => { // Client->Server messages const SSH_AGENTC_REQUEST_IDENTITIES = 11; const SSH_AGENTC_SIGN_REQUEST = 13; // const SSH_AGENTC_ADD_IDENTITY = 17; // const SSH_AGENTC_REMOVE_IDENTITY = 18; // const SSH_AGENTC_REMOVE_ALL_IDENTITIES = 19; // const SSH_AGENTC_ADD_SMARTCARD_KEY = 20; // const SSH_AGENTC_REMOVE_SMARTCARD_KEY = 21; // const SSH_AGENTC_LOCK = 22; // const SSH_AGENTC_UNLOCK = 23; // const SSH_AGENTC_ADD_ID_CONSTRAINED = 25; // const SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED = 26; // const SSH_AGENTC_EXTENSION = 27; // Server->Client messages const SSH_AGENT_FAILURE = 5; // const SSH_AGENT_SUCCESS = 6; const SSH_AGENT_IDENTITIES_ANSWER = 12; const SSH_AGENT_SIGN_RESPONSE = 14; // const SSH_AGENT_EXTENSION_FAILURE = 28; // const SSH_AGENT_CONSTRAIN_LIFETIME = 1; // const SSH_AGENT_CONSTRAIN_CONFIRM = 2; // const SSH_AGENT_CONSTRAIN_EXTENSION = 255; const SSH_AGENT_RSA_SHA2_256 = (1 << 1); const SSH_AGENT_RSA_SHA2_512 = (1 << 2); const ROLE_CLIENT = 0; const ROLE_SERVER = 1; // Ensures that responses get sent back in the same order the requests were // received function processResponses(protocol) { let ret; while (protocol[SYM_REQS].length) { const nextResponse = protocol[SYM_REQS][0][SYM_RESP]; if (nextResponse === undefined) break; protocol[SYM_REQS].shift(); ret = protocol.push(nextResponse); } return ret; } const SYM_TYPE = Symbol('Inbound Request Type'); const SYM_RESP = Symbol('Inbound Request Response'); const SYM_CTX = Symbol('Inbound Request Context'); class AgentInboundRequest { constructor(type, ctx) { this[SYM_TYPE] = type; this[SYM_RESP] = undefined; this[SYM_CTX] = ctx; } hasResponded() { return (this[SYM_RESP] !== undefined); } getType() { return this[SYM_TYPE]; } getContext() { return this[SYM_CTX]; } } function respond(protocol, req, data) { req[SYM_RESP] = data; return processResponses(protocol); } function cleanup(protocol) { protocol[SYM_BUFFER] = null; if (protocol[SYM_MODE] === ROLE_CLIENT) { const reqs = protocol[SYM_REQS]; if (reqs && reqs.length) { protocol[SYM_REQS] = []; for (const req of reqs) req.cb(new Error('No reply from server')); } } // Node streams hackery to make streams do the "right thing" try { protocol.end(); } catch {} setImmediate(() => { if (!protocol[SYM_ENDED]) protocol.emit('end'); if (!protocol[SYM_CLOSED]) protocol.emit('close'); }); } function onClose() { this[SYM_CLOSED] = true; } function onEnd() { this[SYM_ENDED] = true; } const SYM_REQS = Symbol('Requests'); const SYM_MODE = Symbol('Agent Protocol Role'); const SYM_BUFFER = Symbol('Agent Protocol Buffer'); const SYM_MSGLEN = Symbol('Agent Protocol Current Message Length'); const SYM_CLOSED = Symbol('Agent Protocol Closed'); const SYM_ENDED = Symbol('Agent Protocol Ended'); // Implementation based on: // https://tools.ietf.org/html/draft-miller-ssh-agent-04 return class AgentProtocol extends Duplex { /* Notes: - `constraint` type consists of: byte constraint_type byte[] constraint_data where `constraint_type` is one of: * SSH_AGENT_CONSTRAIN_LIFETIME - `constraint_data` consists of: uint32 seconds * SSH_AGENT_CONSTRAIN_CONFIRM - `constraint_data` N/A * SSH_AGENT_CONSTRAIN_EXTENSION - `constraint_data` consists of: string extension name byte[] extension-specific details */ constructor(isClient) { super({ autoDestroy: true, emitClose: false }); this[SYM_MODE] = (isClient ? ROLE_CLIENT : ROLE_SERVER); this[SYM_REQS] = []; this[SYM_BUFFER] = null; this[SYM_MSGLEN] = -1; this.once('end', onEnd); this.once('close', onClose); } _read(n) {} _write(data, encoding, cb) { /* Messages are of the format: uint32 message length byte message type byte[message length - 1] message contents */ if (this[SYM_BUFFER] === null) this[SYM_BUFFER] = data; else this[SYM_BUFFER] = concat(this[SYM_BUFFER], data); let buffer = this[SYM_BUFFER]; let bufferLen = buffer.length; let p = 0; while (p < bufferLen) { // Wait for length + type if (bufferLen < 5) break; if (this[SYM_MSGLEN] === -1) this[SYM_MSGLEN] = readUInt32BE(buffer, p); // Check if we have the entire message if (bufferLen < (4 + this[SYM_MSGLEN])) break; const msgType = buffer[p += 4]; ++p; if (this[SYM_MODE] === ROLE_CLIENT) { if (this[SYM_REQS].length === 0) return cb(new Error('Received unexpected message from server')); const req = this[SYM_REQS].shift(); switch (msgType) { case SSH_AGENT_FAILURE: req.cb(new Error('Agent responded with failure')); break; case SSH_AGENT_IDENTITIES_ANSWER: { if (req.type !== SSH_AGENTC_REQUEST_IDENTITIES) return cb(new Error('Agent responded with wrong message type')); /* byte SSH_AGENT_IDENTITIES_ANSWER uint32 nkeys where `nkeys` is 0 or more of: string key blob string comment */ binaryParser.init(buffer, p); const numKeys = binaryParser.readUInt32BE(); if (numKeys === undefined) { binaryParser.clear(); return cb(new Error('Malformed agent response')); } const keys = []; for (let i = 0; i < numKeys; ++i) { let pubKey = binaryParser.readString(); if (pubKey === undefined) { binaryParser.clear(); return cb(new Error('Malformed agent response')); } const comment = binaryParser.readString(true); if (comment === undefined) { binaryParser.clear(); return cb(new Error('Malformed agent response')); } pubKey = parseKey(pubKey); // We continue parsing the packet if we encounter an error // in case the error is due to the key being an unsupported // type if (pubKey instanceof Error) continue; pubKey.comment = pubKey.comment || comment; keys.push(pubKey); } p = binaryParser.pos(); binaryParser.clear(); req.cb(null, keys); break; } case SSH_AGENT_SIGN_RESPONSE: { if (req.type !== SSH_AGENTC_SIGN_REQUEST) return cb(new Error('Agent responded with wrong message type')); /* byte SSH_AGENT_SIGN_RESPONSE string signature */ binaryParser.init(buffer, p); let signature = binaryParser.readString(); p = binaryParser.pos(); binaryParser.clear(); if (signature === undefined) return cb(new Error('Malformed agent response')); // We strip the algorithm from OpenSSH's output and assume it's // using the algorithm we specified. This makes it easier on // custom Agent implementations so they don't have to construct // the correct binary format for a (OpenSSH-style) signature. // TODO: verify signature type based on key and options used // during initial sign request binaryParser.init(signature, 0); binaryParser.readString(true); signature = binaryParser.readString(); binaryParser.clear(); if (signature === undefined) return cb(new Error('Malformed OpenSSH signature format')); req.cb(null, signature); break; } default: return cb( new Error('Agent responded with unsupported message type') ); } } else { switch (msgType) { case SSH_AGENTC_REQUEST_IDENTITIES: { const req = new AgentInboundRequest(msgType); this[SYM_REQS].push(req); /* byte SSH_AGENTC_REQUEST_IDENTITIES */ this.emit('identities', req); break; } case SSH_AGENTC_SIGN_REQUEST: { /* byte SSH_AGENTC_SIGN_REQUEST string key_blob string data uint32 flags */ binaryParser.init(buffer, p); let pubKey = binaryParser.readString(); const data = binaryParser.readString(); const flagsVal = binaryParser.readUInt32BE(); p = binaryParser.pos(); binaryParser.clear(); if (flagsVal === undefined) { const req = new AgentInboundRequest(msgType); this[SYM_REQS].push(req); return this.failureReply(req); } pubKey = parseKey(pubKey); if (pubKey instanceof Error) { const req = new AgentInboundRequest(msgType); this[SYM_REQS].push(req); return this.failureReply(req); } const flags = { hash: undefined, }; let ctx; if (pubKey.type === 'ssh-rsa') { if (flagsVal & SSH_AGENT_RSA_SHA2_256) { ctx = 'rsa-sha2-256'; flags.hash = 'sha256'; } else if (flagsVal & SSH_AGENT_RSA_SHA2_512) { ctx = 'rsa-sha2-512'; flags.hash = 'sha512'; } } if (ctx === undefined) ctx = pubKey.type; const req = new AgentInboundRequest(msgType, ctx); this[SYM_REQS].push(req); this.emit('sign', req, pubKey, data, flags); break; } default: { const req = new AgentInboundRequest(msgType); this[SYM_REQS].push(req); this.failureReply(req); } } } // Get ready for next message this[SYM_MSGLEN] = -1; if (p === bufferLen) { // Nothing left to process for now this[SYM_BUFFER] = null; break; } else { this[SYM_BUFFER] = buffer = buffer.slice(p); bufferLen = buffer.length; p = 0; } } cb(); } _destroy(err, cb) { cleanup(this); cb(); } _final(cb) { cleanup(this); cb(); } // Client->Server messages ================================================= sign(pubKey, data, options, cb) { if (this[SYM_MODE] !== ROLE_CLIENT) throw new Error('Client-only method called with server role'); if (typeof options === 'function') { cb = options; options = undefined; } else if (typeof options !== 'object' || options === null) { options = undefined; } let flags = 0; pubKey = parseKey(pubKey); if (pubKey instanceof Error) throw new Error('Invalid public key argument'); if (pubKey.type === 'ssh-rsa' && options) { switch (options.hash) { case 'sha256': flags = SSH_AGENT_RSA_SHA2_256; break; case 'sha512': flags = SSH_AGENT_RSA_SHA2_512; break; } } pubKey = pubKey.getPublicSSH(); /* byte SSH_AGENTC_SIGN_REQUEST string key_blob string data uint32 flags */ const type = SSH_AGENTC_SIGN_REQUEST; const keyLen = pubKey.length; const dataLen = data.length; let p = 0; const buf = Buffer.allocUnsafe(4 + 1 + 4 + keyLen + 4 + dataLen + 4); writeUInt32BE(buf, buf.length - 4, p); buf[p += 4] = type; writeUInt32BE(buf, keyLen, ++p); pubKey.copy(buf, p += 4); writeUInt32BE(buf, dataLen, p += keyLen); data.copy(buf, p += 4); writeUInt32BE(buf, flags, p += dataLen); if (typeof cb !== 'function') cb = noop; this[SYM_REQS].push({ type, cb }); return this.push(buf); } getIdentities(cb) { if (this[SYM_MODE] !== ROLE_CLIENT) throw new Error('Client-only method called with server role'); /* byte SSH_AGENTC_REQUEST_IDENTITIES */ const type = SSH_AGENTC_REQUEST_IDENTITIES; let p = 0; const buf = Buffer.allocUnsafe(4 + 1); writeUInt32BE(buf, buf.length - 4, p); buf[p += 4] = type; if (typeof cb !== 'function') cb = noop; this[SYM_REQS].push({ type, cb }); return this.push(buf); } // Server->Client messages ================================================= failureReply(req) { if (this[SYM_MODE] !== ROLE_SERVER) throw new Error('Server-only method called with client role'); if (!(req instanceof AgentInboundRequest)) throw new Error('Wrong request argument'); if (req.hasResponded()) return true; let p = 0; const buf = Buffer.allocUnsafe(4 + 1); writeUInt32BE(buf, buf.length - 4, p); buf[p += 4] = SSH_AGENT_FAILURE; return respond(this, req, buf); } getIdentitiesReply(req, keys) { if (this[SYM_MODE] !== ROLE_SERVER) throw new Error('Server-only method called with client role'); if (!(req instanceof AgentInboundRequest)) throw new Error('Wrong request argument'); if (req.hasResponded()) return true; /* byte SSH_AGENT_IDENTITIES_ANSWER uint32 nkeys where `nkeys` is 0 or more of: string key blob string comment */ if (req.getType() !== SSH_AGENTC_REQUEST_IDENTITIES) throw new Error('Invalid response to request'); if (!Array.isArray(keys)) throw new Error('Keys argument must be an array'); let totalKeysLen = 4; // Include `nkeys` size const newKeys = []; for (let i = 0; i < keys.length; ++i) { const entry = keys[i]; if (typeof entry !== 'object' || entry === null) throw new Error(`Invalid key entry: ${entry}`); let pubKey; let comment; if (isParsedKey(entry)) { pubKey = entry; } else if (isParsedKey(entry.pubKey)) { pubKey = entry.pubKey; } else { if (typeof entry.pubKey !== 'object' || entry.pubKey === null) continue; ({ pubKey, comment } = entry.pubKey); pubKey = parseKey(pubKey); if (pubKey instanceof Error) continue; // TODO: add debug output } comment = pubKey.comment || comment; pubKey = pubKey.getPublicSSH(); totalKeysLen += 4 + pubKey.length; if (comment && typeof comment === 'string') comment = Buffer.from(comment); else if (!Buffer.isBuffer(comment)) comment = EMPTY_BUF; totalKeysLen += 4 + comment.length; newKeys.push({ pubKey, comment }); } let p = 0; const buf = Buffer.allocUnsafe(4 + 1 + totalKeysLen); writeUInt32BE(buf, buf.length - 4, p); buf[p += 4] = SSH_AGENT_IDENTITIES_ANSWER; writeUInt32BE(buf, newKeys.length, ++p); p += 4; for (let i = 0; i < newKeys.length; ++i) { const { pubKey, comment } = newKeys[i]; writeUInt32BE(buf, pubKey.length, p); pubKey.copy(buf, p += 4); writeUInt32BE(buf, comment.length, p += pubKey.length); p += 4; if (comment.length) { comment.copy(buf, p); p += comment.length; } } return respond(this, req, buf); } signReply(req, signature) { if (this[SYM_MODE] !== ROLE_SERVER) throw new Error('Server-only method called with client role'); if (!(req instanceof AgentInboundRequest)) throw new Error('Wrong request argument'); if (req.hasResponded()) return true; /* byte SSH_AGENT_SIGN_RESPONSE string signature */ if (req.getType() !== SSH_AGENTC_SIGN_REQUEST) throw new Error('Invalid response to request'); if (!Buffer.isBuffer(signature)) throw new Error('Signature argument must be a Buffer'); if (signature.length === 0) throw new Error('Signature argument must be non-empty'); /* OpenSSH agent signatures are encoded as: string signature format identifier (as specified by the public key/certificate format) byte[n] signature blob in format specific encoding. - This is actually a `string` for: rsa, dss, ecdsa, and ed25519 types */ let p = 0; const sigFormat = req.getContext(); const sigFormatLen = Buffer.byteLength(sigFormat); const buf = Buffer.allocUnsafe( 4 + 1 + 4 + 4 + sigFormatLen + 4 + signature.length ); writeUInt32BE(buf, buf.length - 4, p); buf[p += 4] = SSH_AGENT_SIGN_RESPONSE; writeUInt32BE(buf, 4 + sigFormatLen + 4 + signature.length, ++p); writeUInt32BE(buf, sigFormatLen, p += 4); buf.utf8Write(sigFormat, p += 4, sigFormatLen); writeUInt32BE(buf, signature.length, p += sigFormatLen); signature.copy(buf, p += 4); return respond(this, req, buf); } }; })(); const SYM_AGENT = Symbol('Agent'); const SYM_AGENT_KEYS = Symbol('Agent Keys'); const SYM_AGENT_KEYS_IDX = Symbol('Agent Keys Index'); const SYM_AGENT_CBS = Symbol('Agent Init Callbacks'); class AgentContext { constructor(agent) { if (typeof agent === 'string') agent = createAgent(agent); else if (!isAgent(agent)) throw new Error('Invalid agent argument'); this[SYM_AGENT] = agent; this[SYM_AGENT_KEYS] = null; this[SYM_AGENT_KEYS_IDX] = -1; this[SYM_AGENT_CBS] = null; } init(cb) { if (typeof cb !== 'function') cb = noop; if (this[SYM_AGENT_KEYS] === null) { if (this[SYM_AGENT_CBS] === null) { this[SYM_AGENT_CBS] = [cb]; const doCbs = (...args) => { process.nextTick(() => { const cbs = this[SYM_AGENT_CBS]; this[SYM_AGENT_CBS] = null; for (const cb of cbs) cb(...args); }); }; this[SYM_AGENT].getIdentities(once((err, keys) => { if (err) return doCbs(err); if (!Array.isArray(keys)) { return doCbs(new Error( 'Agent implementation failed to provide keys' )); } const newKeys = []; for (let key of keys) { key = parseKey(key); if (key instanceof Error) { // TODO: add debug output continue; } newKeys.push(key); } this[SYM_AGENT_KEYS] = newKeys; this[SYM_AGENT_KEYS_IDX] = -1; doCbs(); })); } else { this[SYM_AGENT_CBS].push(cb); } } else { process.nextTick(cb); } } nextKey() { if (this[SYM_AGENT_KEYS] === null || ++this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { return false; } return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]]; } currentKey() { if (this[SYM_AGENT_KEYS] === null || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { return null; } return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]]; } pos() { if (this[SYM_AGENT_KEYS] === null || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { return -1; } return this[SYM_AGENT_KEYS_IDX]; } reset() { this[SYM_AGENT_KEYS_IDX] = -1; } sign(...args) { this[SYM_AGENT].sign(...args); } } function isAgent(val) { return (val instanceof BaseAgent); } module.exports = { AgentContext, AgentProtocol, BaseAgent, createAgent, CygwinAgent, isAgent, OpenSSHAgent, PageantAgent, }; /***/ }), /***/ 92353: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // TODO: // * add `.connected` or similar property to allow immediate connection // status checking // * add/improve debug output during user authentication phase const { createHash, getHashes, randomFillSync, } = __webpack_require__(6113); const { Socket } = __webpack_require__(41808); const { lookup: dnsLookup } = __webpack_require__(9523); const EventEmitter = __webpack_require__(82361); const HASHES = getHashes(); const { COMPAT, CHANNEL_EXTENDED_DATATYPE: { STDERR }, CHANNEL_OPEN_FAILURE, DEFAULT_CIPHER, DEFAULT_COMPRESSION, DEFAULT_KEX, DEFAULT_MAC, DEFAULT_SERVER_HOST_KEY, DISCONNECT_REASON, DISCONNECT_REASON_BY_VALUE, SUPPORTED_CIPHER, SUPPORTED_COMPRESSION, SUPPORTED_KEX, SUPPORTED_MAC, SUPPORTED_SERVER_HOST_KEY, } = __webpack_require__(3190); const { init: cryptoInit } = __webpack_require__(83877); const Protocol = __webpack_require__(53603); const { parseKey } = __webpack_require__(13781); const { SFTP } = __webpack_require__(64061); const { bufferCopy, makeBufferParser, makeError, readUInt32BE, sigSSHToASN1, writeUInt32BE, } = __webpack_require__(39205); const { AgentContext, createAgent, isAgent } = __webpack_require__(81119); const { Channel, MAX_WINDOW, PACKET_SIZE, windowAdjust, WINDOW_THRESHOLD, } = __webpack_require__(50491); const { ChannelManager, generateAlgorithmList, isWritable, onChannelOpenFailure, onCHANNEL_CLOSE, } = __webpack_require__(17236); const bufferParser = makeBufferParser(); const sigParser = makeBufferParser(); const RE_OPENSSH = /^OpenSSH_(?:(?![0-4])\d)|(?:\d{2,})/; const noop = (err) => {}; class Client extends EventEmitter { constructor() { super(); this.config = { host: undefined, port: undefined, localAddress: undefined, localPort: undefined, forceIPv4: undefined, forceIPv6: undefined, keepaliveCountMax: undefined, keepaliveInterval: undefined, readyTimeout: undefined, ident: undefined, username: undefined, password: undefined, privateKey: undefined, tryKeyboard: undefined, agent: undefined, allowAgentFwd: undefined, authHandler: undefined, hostHashAlgo: undefined, hostHashCb: undefined, strictVendor: undefined, debug: undefined }; this._agent = undefined; this._readyTimeout = undefined; this._chanMgr = undefined; this._callbacks = undefined; this._forwarding = undefined; this._forwardingUnix = undefined; this._acceptX11 = undefined; this._agentFwdEnabled = undefined; this._remoteVer = undefined; this._protocol = undefined; this._sock = undefined; this._resetKA = undefined; } connect(cfg) { if (this._sock && isWritable(this._sock)) { this.once('close', () => { this.connect(cfg); }); this.end(); return this; } this.config.host = cfg.hostname || cfg.host || 'localhost'; this.config.port = cfg.port || 22; this.config.localAddress = (typeof cfg.localAddress === 'string' ? cfg.localAddress : undefined); this.config.localPort = (typeof cfg.localPort === 'string' || typeof cfg.localPort === 'number' ? cfg.localPort : undefined); this.config.forceIPv4 = cfg.forceIPv4 || false; this.config.forceIPv6 = cfg.forceIPv6 || false; this.config.keepaliveCountMax = (typeof cfg.keepaliveCountMax === 'number' && cfg.keepaliveCountMax >= 0 ? cfg.keepaliveCountMax : 3); this.config.keepaliveInterval = (typeof cfg.keepaliveInterval === 'number' && cfg.keepaliveInterval > 0 ? cfg.keepaliveInterval : 0); this.config.readyTimeout = (typeof cfg.readyTimeout === 'number' && cfg.readyTimeout >= 0 ? cfg.readyTimeout : 20000); this.config.ident = (typeof cfg.ident === 'string' || Buffer.isBuffer(cfg.ident) ? cfg.ident : undefined); const algorithms = { kex: undefined, serverHostKey: undefined, cs: { cipher: undefined, mac: undefined, compress: undefined, lang: [], }, sc: undefined, }; let allOfferDefaults = true; if (typeof cfg.algorithms === 'object' && cfg.algorithms !== null) { algorithms.kex = generateAlgorithmList(cfg.algorithms.kex, DEFAULT_KEX, SUPPORTED_KEX); if (algorithms.kex !== DEFAULT_KEX) allOfferDefaults = false; algorithms.serverHostKey = generateAlgorithmList(cfg.algorithms.serverHostKey, DEFAULT_SERVER_HOST_KEY, SUPPORTED_SERVER_HOST_KEY); if (algorithms.serverHostKey !== DEFAULT_SERVER_HOST_KEY) allOfferDefaults = false; algorithms.cs.cipher = generateAlgorithmList(cfg.algorithms.cipher, DEFAULT_CIPHER, SUPPORTED_CIPHER); if (algorithms.cs.cipher !== DEFAULT_CIPHER) allOfferDefaults = false; algorithms.cs.mac = generateAlgorithmList(cfg.algorithms.hmac, DEFAULT_MAC, SUPPORTED_MAC); if (algorithms.cs.mac !== DEFAULT_MAC) allOfferDefaults = false; algorithms.cs.compress = generateAlgorithmList(cfg.algorithms.compress, DEFAULT_COMPRESSION, SUPPORTED_COMPRESSION); if (algorithms.cs.compress !== DEFAULT_COMPRESSION) allOfferDefaults = false; if (!allOfferDefaults) algorithms.sc = algorithms.cs; } if (typeof cfg.username === 'string') this.config.username = cfg.username; else if (typeof cfg.user === 'string') this.config.username = cfg.user; else throw new Error('Invalid username'); this.config.password = (typeof cfg.password === 'string' ? cfg.password : undefined); this.config.privateKey = (typeof cfg.privateKey === 'string' || Buffer.isBuffer(cfg.privateKey) ? cfg.privateKey : undefined); this.config.localHostname = (typeof cfg.localHostname === 'string' ? cfg.localHostname : undefined); this.config.localUsername = (typeof cfg.localUsername === 'string' ? cfg.localUsername : undefined); this.config.tryKeyboard = (cfg.tryKeyboard === true); if (typeof cfg.agent === 'string' && cfg.agent.length) this.config.agent = createAgent(cfg.agent); else if (isAgent(cfg.agent)) this.config.agent = cfg.agent; else this.config.agent = undefined; this.config.allowAgentFwd = (cfg.agentForward === true && this.config.agent !== undefined); let authHandler = this.config.authHandler = ( typeof cfg.authHandler === 'function' || Array.isArray(cfg.authHandler) ? cfg.authHandler : undefined ); this.config.strictVendor = (typeof cfg.strictVendor === 'boolean' ? cfg.strictVendor : true); const debug = this.config.debug = (typeof cfg.debug === 'function' ? cfg.debug : undefined); if (cfg.agentForward === true && !this.config.allowAgentFwd) { throw new Error( 'You must set a valid agent path to allow agent forwarding' ); } let callbacks = this._callbacks = []; this._chanMgr = new ChannelManager(this); this._forwarding = {}; this._forwardingUnix = {}; this._acceptX11 = 0; this._agentFwdEnabled = false; this._agent = (this.config.agent ? this.config.agent : undefined); this._remoteVer = undefined; let privateKey; if (this.config.privateKey) { privateKey = parseKey(this.config.privateKey, cfg.passphrase); if (privateKey instanceof Error) throw new Error(`Cannot parse privateKey: ${privateKey.message}`); if (Array.isArray(privateKey)) { // OpenSSH's newer format only stores 1 key for now privateKey = privateKey[0]; } if (privateKey.getPrivatePEM() === null) { throw new Error( 'privateKey value does not contain a (valid) private key' ); } } let hostVerifier; if (typeof cfg.hostVerifier === 'function') { const hashCb = cfg.hostVerifier; let hasher; if (HASHES.indexOf(cfg.hostHash) !== -1) { // Default to old behavior of hashing on user's behalf hasher = createHash(cfg.hostHash); } hostVerifier = (key, verify) => { if (hasher) { hasher.update(key); key = hasher.digest('hex'); } const ret = hashCb(key, verify); if (ret !== undefined) verify(ret); }; } const sock = this._sock = (cfg.sock || new Socket()); let ready = false; let sawHeader = false; if (this._protocol) this._protocol.cleanup(); const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => { debug(`Debug output from server: ${JSON.stringify(msg)}`); }); let serverSigAlgs; const proto = this._protocol = new Protocol({ ident: this.config.ident, offer: (allOfferDefaults ? undefined : algorithms), onWrite: (data) => { if (isWritable(sock)) sock.write(data); }, onError: (err) => { if (err.level === 'handshake') clearTimeout(this._readyTimeout); if (!proto._destruct) sock.removeAllListeners('data'); this.emit('error', err); try { sock.end(); } catch {} }, onHeader: (header) => { sawHeader = true; this._remoteVer = header.versions.software; if (header.greeting) this.emit('greeting', header.greeting); }, onHandshakeComplete: (negotiated) => { this.emit('handshake', negotiated); if (!ready) { ready = true; proto.service('ssh-userauth'); } }, debug, hostVerifier, messageHandlers: { DEBUG: DEBUG_HANDLER, DISCONNECT: (p, reason, desc) => { if (reason !== DISCONNECT_REASON.BY_APPLICATION) { if (!desc) { desc = DISCONNECT_REASON_BY_VALUE[reason]; if (desc === undefined) desc = `Unexpected disconnection reason: ${reason}`; } const err = new Error(desc); err.code = reason; this.emit('error', err); } sock.end(); }, SERVICE_ACCEPT: (p, name) => { if (name === 'ssh-userauth') tryNextAuth(); }, EXT_INFO: (p, exts) => { if (serverSigAlgs === undefined) { for (const ext of exts) { if (ext.name === 'server-sig-algs') { serverSigAlgs = ext.algs; return; } } serverSigAlgs = null; } }, USERAUTH_BANNER: (p, msg) => { this.emit('banner', msg); }, USERAUTH_SUCCESS: (p) => { // Start keepalive mechanism resetKA(); clearTimeout(this._readyTimeout); this.emit('ready'); }, USERAUTH_FAILURE: (p, authMethods, partialSuccess) => { // For key-based authentication, check if we should retry the current // key with a different algorithm first if (curAuth.keyAlgos) { const oldKeyAlgo = curAuth.keyAlgos[0][0]; if (debug) debug(`Client: ${curAuth.type} (${oldKeyAlgo}) auth failed`); curAuth.keyAlgos.shift(); if (curAuth.keyAlgos.length) { const [keyAlgo, hashAlgo] = curAuth.keyAlgos[0]; switch (curAuth.type) { case 'agent': proto.authPK( curAuth.username, curAuth.agentCtx.currentKey(), keyAlgo ); return; case 'publickey': proto.authPK(curAuth.username, curAuth.key, keyAlgo); return; case 'hostbased': proto.authHostbased(curAuth.username, curAuth.key, curAuth.localHostname, curAuth.localUsername, keyAlgo, (buf, cb) => { const signature = curAuth.key.sign(buf, hashAlgo); if (signature instanceof Error) { signature.message = `Error while signing with key: ${signature.message}`; signature.level = 'client-authentication'; this.emit('error', signature); return tryNextAuth(); } cb(signature); }); return; } } else { curAuth.keyAlgos = undefined; } } if (curAuth.type === 'agent') { const pos = curAuth.agentCtx.pos(); debug && debug(`Client: Agent key #${pos + 1} failed`); return tryNextAgentKey(); } debug && debug(`Client: ${curAuth.type} auth failed`); curPartial = partialSuccess; curAuthsLeft = authMethods; tryNextAuth(); }, USERAUTH_PASSWD_CHANGEREQ: (p, prompt) => { if (curAuth.type === 'password') { // TODO: support a `changePrompt()` on `curAuth` that defaults to // emitting 'change password' as before this.emit('change password', prompt, (newPassword) => { proto.authPassword( this.config.username, this.config.password, newPassword ); }); } }, USERAUTH_PK_OK: (p) => { let keyAlgo; let hashAlgo; if (curAuth.keyAlgos) [keyAlgo, hashAlgo] = curAuth.keyAlgos[0]; if (curAuth.type === 'agent') { const key = curAuth.agentCtx.currentKey(); proto.authPK(curAuth.username, key, keyAlgo, (buf, cb) => { const opts = { hash: hashAlgo }; curAuth.agentCtx.sign(key, buf, opts, (err, signed) => { if (err) { err.level = 'agent'; this.emit('error', err); } else { return cb(signed); } tryNextAgentKey(); }); }); } else if (curAuth.type === 'publickey') { proto.authPK(curAuth.username, curAuth.key, keyAlgo, (buf, cb) => { const signature = curAuth.key.sign(buf, hashAlgo); if (signature instanceof Error) { signature.message = `Error signing data with key: ${signature.message}`; signature.level = 'client-authentication'; this.emit('error', signature); return tryNextAuth(); } cb(signature); }); } }, USERAUTH_INFO_REQUEST: (p, name, instructions, prompts) => { if (curAuth.type === 'keyboard-interactive') { const nprompts = (Array.isArray(prompts) ? prompts.length : 0); if (nprompts === 0) { debug && debug( 'Client: Sending automatic USERAUTH_INFO_RESPONSE' ); proto.authInfoRes(); return; } // We sent a keyboard-interactive user authentication request and // now the server is sending us the prompts we need to present to // the user curAuth.prompt( name, instructions, '', prompts, (answers) => { proto.authInfoRes(answers); } ); } }, REQUEST_SUCCESS: (p, data) => { if (callbacks.length) callbacks.shift()(false, data); }, REQUEST_FAILURE: (p) => { if (callbacks.length) callbacks.shift()(true); }, GLOBAL_REQUEST: (p, name, wantReply, data) => { switch (name) { case 'hostkeys-00@openssh.com': // Automatically verify keys before passing to end user hostKeysProve(this, data, (err, keys) => { if (err) return; this.emit('hostkeys', keys); }); if (wantReply) proto.requestSuccess(); break; default: // Auto-reject all other global requests, this can be especially // useful if the server is sending us dummy keepalive global // requests if (wantReply) proto.requestFailure(); } }, CHANNEL_OPEN: (p, info) => { // Handle incoming requests from server, typically a forwarded TCP or // X11 connection onCHANNEL_OPEN(this, info); }, CHANNEL_OPEN_CONFIRMATION: (p, info) => { const channel = this._chanMgr.get(info.recipient); if (typeof channel !== 'function') return; const isSFTP = (channel.type === 'sftp'); const type = (isSFTP ? 'session' : channel.type); const chanInfo = { type, incoming: { id: info.recipient, window: MAX_WINDOW, packetSize: PACKET_SIZE, state: 'open' }, outgoing: { id: info.sender, window: info.window, packetSize: info.packetSize, state: 'open' } }; const instance = ( isSFTP ? new SFTP(this, chanInfo, { debug }) : new Channel(this, chanInfo) ); this._chanMgr.update(info.recipient, instance); channel(undefined, instance); }, CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => { const channel = this._chanMgr.get(recipient); if (typeof channel !== 'function') return; const info = { reason, description }; onChannelOpenFailure(this, recipient, info, channel); }, CHANNEL_DATA: (p, recipient, data) => { const channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; // The remote party should not be sending us data if there is no // window space available ... // TODO: raise error on data with not enough window? if (channel.incoming.window === 0) return; channel.incoming.window -= data.length; if (channel.push(data) === false) { channel._waitChanDrain = true; return; } if (channel.incoming.window <= WINDOW_THRESHOLD) windowAdjust(channel); }, CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => { if (type !== STDERR) return; const channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; // The remote party should not be sending us data if there is no // window space available ... // TODO: raise error on data with not enough window? if (channel.incoming.window === 0) return; channel.incoming.window -= data.length; if (!channel.stderr.push(data)) { channel._waitChanDrain = true; return; } if (channel.incoming.window <= WINDOW_THRESHOLD) windowAdjust(channel); }, CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => { const channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; // The other side is allowing us to send `amount` more bytes of data channel.outgoing.window += amount; if (channel._waitWindow) { channel._waitWindow = false; if (channel._chunk) { channel._write(channel._chunk, null, channel._chunkcb); } else if (channel._chunkcb) { channel._chunkcb(); } else if (channel._chunkErr) { channel.stderr._write(channel._chunkErr, null, channel._chunkcbErr); } else if (channel._chunkcbErr) { channel._chunkcbErr(); } } }, CHANNEL_SUCCESS: (p, recipient) => { const channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; this._resetKA(); if (channel._callbacks.length) channel._callbacks.shift()(false); }, CHANNEL_FAILURE: (p, recipient) => { const channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; this._resetKA(); if (channel._callbacks.length) channel._callbacks.shift()(true); }, CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => { const channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; const exit = channel._exit; if (exit.code !== undefined) return; switch (type) { case 'exit-status': channel.emit('exit', exit.code = data); return; case 'exit-signal': channel.emit('exit', exit.code = null, exit.signal = `SIG${data.signal}`, exit.dump = data.coreDumped, exit.desc = data.errorMessage); return; } // Keepalive request? OpenSSH will send one as a channel request if // there is a channel open if (wantReply) p.channelFailure(channel.outgoing.id); }, CHANNEL_EOF: (p, recipient) => { const channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; if (channel.incoming.state !== 'open') return; channel.incoming.state = 'eof'; if (channel.readable) channel.push(null); if (channel.stderr.readable) channel.stderr.push(null); }, CHANNEL_CLOSE: (p, recipient) => { onCHANNEL_CLOSE(this, recipient, this._chanMgr.get(recipient)); }, }, }); sock.pause(); // TODO: check keepalive implementation // Keepalive-related const kainterval = this.config.keepaliveInterval; const kacountmax = this.config.keepaliveCountMax; let kacount = 0; let katimer; const sendKA = () => { if (++kacount > kacountmax) { clearInterval(katimer); if (sock.readable) { const err = new Error('Keepalive timeout'); err.level = 'client-timeout'; this.emit('error', err); sock.destroy(); } return; } if (isWritable(sock)) { // Append dummy callback to keep correct callback order callbacks.push(resetKA); proto.ping(); } else { clearInterval(katimer); } }; function resetKA() { if (kainterval > 0) { kacount = 0; clearInterval(katimer); if (isWritable(sock)) katimer = setInterval(sendKA, kainterval); } } this._resetKA = resetKA; const onDone = (() => { let called = false; return () => { if (called) return; called = true; if (wasConnected && !sawHeader) { const err = makeError('Connection lost before handshake', 'protocol', true); this.emit('error', err); } }; })(); const onConnect = (() => { let called = false; return () => { if (called) return; called = true; wasConnected = true; debug && debug('Socket connected'); this.emit('connect'); cryptoInit.then(() => { proto.start(); sock.on('data', (data) => { try { proto.parse(data, 0, data.length); } catch (ex) { this.emit('error', ex); try { if (isWritable(sock)) sock.end(); } catch {} } }); // Drain stderr if we are connection hopping using an exec stream if (sock.stderr && typeof sock.stderr.resume === 'function') sock.stderr.resume(); sock.resume(); }).catch((err) => { this.emit('error', err); try { if (isWritable(sock)) sock.end(); } catch {} }); }; })(); let wasConnected = false; sock.on('connect', onConnect) .on('timeout', () => { this.emit('timeout'); }).on('error', (err) => { debug && debug(`Socket error: ${err.message}`); clearTimeout(this._readyTimeout); err.level = 'client-socket'; this.emit('error', err); }).on('end', () => { debug && debug('Socket ended'); onDone(); proto.cleanup(); clearTimeout(this._readyTimeout); clearInterval(katimer); this.emit('end'); }).on('close', () => { debug && debug('Socket closed'); onDone(); proto.cleanup(); clearTimeout(this._readyTimeout); clearInterval(katimer); this.emit('close'); // Notify outstanding channel requests of disconnection ... const callbacks_ = callbacks; callbacks = this._callbacks = []; const err = new Error('No response from server'); for (let i = 0; i < callbacks_.length; ++i) callbacks_[i](err); // Simulate error for any channels waiting to be opened this._chanMgr.cleanup(err); }); // Begin authentication handling =========================================== let curAuth; let curPartial = null; let curAuthsLeft = null; const authsAllowed = ['none']; if (this.config.password !== undefined) authsAllowed.push('password'); if (privateKey !== undefined) authsAllowed.push('publickey'); if (this._agent !== undefined) authsAllowed.push('agent'); if (this.config.tryKeyboard) authsAllowed.push('keyboard-interactive'); if (privateKey !== undefined && this.config.localHostname !== undefined && this.config.localUsername !== undefined) { authsAllowed.push('hostbased'); } if (Array.isArray(authHandler)) authHandler = makeSimpleAuthHandler(authHandler); else if (typeof authHandler !== 'function') authHandler = makeSimpleAuthHandler(authsAllowed); let hasSentAuth = false; const doNextAuth = (nextAuth) => { if (hasSentAuth) return; hasSentAuth = true; if (nextAuth === false) { const err = new Error('All configured authentication methods failed'); err.level = 'client-authentication'; this.emit('error', err); this.end(); return; } if (typeof nextAuth === 'string') { // Remain backwards compatible with original `authHandler()` usage, // which only supported passing names of next method to try using data // from the `connect()` config object const type = nextAuth; if (authsAllowed.indexOf(type) === -1) return skipAuth(`Authentication method not allowed: ${type}`); const username = this.config.username; switch (type) { case 'password': nextAuth = { type, username, password: this.config.password }; break; case 'publickey': nextAuth = { type, username, key: privateKey }; break; case 'hostbased': nextAuth = { type, username, key: privateKey, localHostname: this.config.localHostname, localUsername: this.config.localUsername, }; break; case 'agent': nextAuth = { type, username, agentCtx: new AgentContext(this._agent), }; break; case 'keyboard-interactive': nextAuth = { type, username, prompt: (...args) => this.emit('keyboard-interactive', ...args), }; break; case 'none': nextAuth = { type, username }; break; default: return skipAuth( `Skipping unsupported authentication method: ${nextAuth}` ); } } else if (typeof nextAuth !== 'object' || nextAuth === null) { return skipAuth( `Skipping invalid authentication attempt: ${nextAuth}` ); } else { const username = nextAuth.username; if (typeof username !== 'string') { return skipAuth( `Skipping invalid authentication attempt: ${nextAuth}` ); } const type = nextAuth.type; switch (type) { case 'password': { const { password } = nextAuth; if (typeof password !== 'string' && !Buffer.isBuffer(password)) return skipAuth('Skipping invalid password auth attempt'); nextAuth = { type, username, password }; break; } case 'publickey': { const key = parseKey(nextAuth.key, nextAuth.passphrase); if (key instanceof Error) return skipAuth('Skipping invalid key auth attempt'); if (!key.isPrivateKey()) return skipAuth('Skipping non-private key'); nextAuth = { type, username, key }; break; } case 'hostbased': { const { localHostname, localUsername } = nextAuth; const key = parseKey(nextAuth.key, nextAuth.passphrase); if (key instanceof Error || typeof localHostname !== 'string' || typeof localUsername !== 'string') { return skipAuth('Skipping invalid hostbased auth attempt'); } if (!key.isPrivateKey()) return skipAuth('Skipping non-private key'); nextAuth = { type, username, key, localHostname, localUsername }; break; } case 'agent': { let agent = nextAuth.agent; if (typeof agent === 'string' && agent.length) { agent = createAgent(agent); } else if (!isAgent(agent)) { return skipAuth( `Skipping invalid agent: ${nextAuth.agent}` ); } nextAuth = { type, username, agentCtx: new AgentContext(agent) }; break; } case 'keyboard-interactive': { const { prompt } = nextAuth; if (typeof prompt !== 'function') { return skipAuth( 'Skipping invalid keyboard-interactive auth attempt' ); } nextAuth = { type, username, prompt }; break; } case 'none': nextAuth = { type, username }; break; default: return skipAuth( `Skipping unsupported authentication method: ${nextAuth}` ); } } curAuth = nextAuth; // Begin authentication method's process try { const username = curAuth.username; switch (curAuth.type) { case 'password': proto.authPassword(username, curAuth.password); break; case 'publickey': { let keyAlgo; curAuth.keyAlgos = getKeyAlgos(this, curAuth.key, serverSigAlgs); if (curAuth.keyAlgos) { if (curAuth.keyAlgos.length) { keyAlgo = curAuth.keyAlgos[0][0]; } else { return skipAuth( 'Skipping key authentication (no mutual hash algorithm)' ); } } proto.authPK(username, curAuth.key, keyAlgo); break; } case 'hostbased': { let keyAlgo; let hashAlgo; curAuth.keyAlgos = getKeyAlgos(this, curAuth.key, serverSigAlgs); if (curAuth.keyAlgos) { if (curAuth.keyAlgos.length) { [keyAlgo, hashAlgo] = curAuth.keyAlgos[0]; } else { return skipAuth( 'Skipping hostbased authentication (no mutual hash algorithm)' ); } } proto.authHostbased(username, curAuth.key, curAuth.localHostname, curAuth.localUsername, keyAlgo, (buf, cb) => { const signature = curAuth.key.sign(buf, hashAlgo); if (signature instanceof Error) { signature.message = `Error while signing with key: ${signature.message}`; signature.level = 'client-authentication'; this.emit('error', signature); return tryNextAuth(); } cb(signature); }); break; } case 'agent': curAuth.agentCtx.init((err) => { if (err) { err.level = 'agent'; this.emit('error', err); return tryNextAuth(); } tryNextAgentKey(); }); break; case 'keyboard-interactive': proto.authKeyboard(username); break; case 'none': proto.authNone(username); break; } } finally { hasSentAuth = false; } }; function skipAuth(msg) { debug && debug(msg); process.nextTick(tryNextAuth); } function tryNextAuth() { hasSentAuth = false; const auth = authHandler(curAuthsLeft, curPartial, doNextAuth); if (hasSentAuth || auth === undefined) return; doNextAuth(auth); } const tryNextAgentKey = () => { if (curAuth.type === 'agent') { const key = curAuth.agentCtx.nextKey(); if (key === false) { debug && debug('Agent: No more keys left to try'); debug && debug('Client: agent auth failed'); tryNextAuth(); } else { const pos = curAuth.agentCtx.pos(); let keyAlgo; curAuth.keyAlgos = getKeyAlgos(this, key, serverSigAlgs); if (curAuth.keyAlgos) { if (curAuth.keyAlgos.length) { keyAlgo = curAuth.keyAlgos[0][0]; } else { debug && debug( `Agent: Skipping key #${pos + 1} (no mutual hash algorithm)` ); tryNextAgentKey(); return; } } debug && debug(`Agent: Trying key #${pos + 1}`); proto.authPK(curAuth.username, key, keyAlgo); } } }; const startTimeout = () => { if (this.config.readyTimeout > 0) { this._readyTimeout = setTimeout(() => { const err = new Error('Timed out while waiting for handshake'); err.level = 'client-timeout'; this.emit('error', err); sock.destroy(); }, this.config.readyTimeout); } }; if (!cfg.sock) { let host = this.config.host; const forceIPv4 = this.config.forceIPv4; const forceIPv6 = this.config.forceIPv6; debug && debug(`Client: Trying ${host} on port ${this.config.port} ...`); const doConnect = () => { startTimeout(); sock.connect({ host, port: this.config.port, localAddress: this.config.localAddress, localPort: this.config.localPort }); sock.setMaxListeners(0); sock.setTimeout(typeof cfg.timeout === 'number' ? cfg.timeout : 0); }; if ((!forceIPv4 && !forceIPv6) || (forceIPv4 && forceIPv6)) { doConnect(); } else { dnsLookup(host, (forceIPv4 ? 4 : 6), (err, address, family) => { if (err) { const type = (forceIPv4 ? 'IPv4' : 'IPv6'); const error = new Error( `Error while looking up ${type} address for '${host}': ${err}` ); clearTimeout(this._readyTimeout); error.level = 'client-dns'; this.emit('error', error); this.emit('close'); return; } host = address; doConnect(); }); } } else { // Custom socket passed in startTimeout(); if (typeof sock.connecting === 'boolean') { // net.Socket if (!sock.connecting) { // Already connected onConnect(); } } else { // Assume socket/stream is already "connected" onConnect(); } } return this; } end() { if (this._sock && isWritable(this._sock)) { this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION); this._sock.end(); } return this; } destroy() { this._sock && isWritable(this._sock) && this._sock.destroy(); return this; } exec(cmd, opts, cb) { if (!this._sock || !isWritable(this._sock)) throw new Error('Not connected'); if (typeof opts === 'function') { cb = opts; opts = {}; } const extraOpts = { allowHalfOpen: (opts.allowHalfOpen !== false) }; openChannel(this, 'session', extraOpts, (err, chan) => { if (err) { cb(err); return; } const todo = []; function reqCb(err) { if (err) { chan.close(); cb(err); return; } if (todo.length) todo.shift()(); } if (this.config.allowAgentFwd === true || (opts && opts.agentForward === true && this._agent !== undefined)) { todo.push(() => reqAgentFwd(chan, reqCb)); } if (typeof opts === 'object' && opts !== null) { if (typeof opts.env === 'object' && opts.env !== null) reqEnv(chan, opts.env); if ((typeof opts.pty === 'object' && opts.pty !== null) || opts.pty === true) { todo.push(() => reqPty(chan, opts.pty, reqCb)); } if ((typeof opts.x11 === 'object' && opts.x11 !== null) || opts.x11 === 'number' || opts.x11 === true) { todo.push(() => reqX11(chan, opts.x11, reqCb)); } } todo.push(() => reqExec(chan, cmd, opts, cb)); todo.shift()(); }); return this; } shell(wndopts, opts, cb) { if (!this._sock || !isWritable(this._sock)) throw new Error('Not connected'); if (typeof wndopts === 'function') { cb = wndopts; wndopts = opts = undefined; } else if (typeof opts === 'function') { cb = opts; opts = undefined; } if (wndopts && (wndopts.x11 !== undefined || wndopts.env !== undefined)) { opts = wndopts; wndopts = undefined; } openChannel(this, 'session', (err, chan) => { if (err) { cb(err); return; } const todo = []; function reqCb(err) { if (err) { chan.close(); cb(err); return; } if (todo.length) todo.shift()(); } if (this.config.allowAgentFwd === true || (opts && opts.agentForward === true && this._agent !== undefined)) { todo.push(() => reqAgentFwd(chan, reqCb)); } if (wndopts !== false) todo.push(() => reqPty(chan, wndopts, reqCb)); if (typeof opts === 'object' && opts !== null) { if (typeof opts.env === 'object' && opts.env !== null) reqEnv(chan, opts.env); if ((typeof opts.x11 === 'object' && opts.x11 !== null) || opts.x11 === 'number' || opts.x11 === true) { todo.push(() => reqX11(chan, opts.x11, reqCb)); } } todo.push(() => reqShell(chan, cb)); todo.shift()(); }); return this; } subsys(name, cb) { if (!this._sock || !isWritable(this._sock)) throw new Error('Not connected'); openChannel(this, 'session', (err, chan) => { if (err) { cb(err); return; } reqSubsystem(chan, name, (err, stream) => { if (err) { cb(err); return; } cb(undefined, stream); }); }); return this; } forwardIn(bindAddr, bindPort, cb) { if (!this._sock || !isWritable(this._sock)) throw new Error('Not connected'); // Send a request for the server to start forwarding TCP connections to us // on a particular address and port const wantReply = (typeof cb === 'function'); if (wantReply) { this._callbacks.push((had_err, data) => { if (had_err) { cb(had_err !== true ? had_err : new Error(`Unable to bind to ${bindAddr}:${bindPort}`)); return; } let realPort = bindPort; if (bindPort === 0 && data && data.length >= 4) { realPort = readUInt32BE(data, 0); if (!(this._protocol._compatFlags & COMPAT.DYN_RPORT_BUG)) bindPort = realPort; } this._forwarding[`${bindAddr}:${bindPort}`] = realPort; cb(undefined, realPort); }); } this._protocol.tcpipForward(bindAddr, bindPort, wantReply); return this; } unforwardIn(bindAddr, bindPort, cb) { if (!this._sock || !isWritable(this._sock)) throw new Error('Not connected'); // Send a request to stop forwarding us new connections for a particular // address and port const wantReply = (typeof cb === 'function'); if (wantReply) { this._callbacks.push((had_err) => { if (had_err) { cb(had_err !== true ? had_err : new Error(`Unable to unbind from ${bindAddr}:${bindPort}`)); return; } delete this._forwarding[`${bindAddr}:${bindPort}`]; cb(); }); } this._protocol.cancelTcpipForward(bindAddr, bindPort, wantReply); return this; } forwardOut(srcIP, srcPort, dstIP, dstPort, cb) { if (!this._sock || !isWritable(this._sock)) throw new Error('Not connected'); // Send a request to forward a TCP connection to the server const cfg = { srcIP: srcIP, srcPort: srcPort, dstIP: dstIP, dstPort: dstPort }; if (typeof cb !== 'function') cb = noop; openChannel(this, 'direct-tcpip', cfg, cb); return this; } openssh_noMoreSessions(cb) { if (!this._sock || !isWritable(this._sock)) throw new Error('Not connected'); const wantReply = (typeof cb === 'function'); if (!this.config.strictVendor || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { if (wantReply) { this._callbacks.push((had_err) => { if (had_err) { cb(had_err !== true ? had_err : new Error('Unable to disable future sessions')); return; } cb(); }); } this._protocol.openssh_noMoreSessions(wantReply); return this; } if (!wantReply) return this; process.nextTick( cb, new Error( 'strictVendor enabled and server is not OpenSSH or compatible version' ) ); return this; } openssh_forwardInStreamLocal(socketPath, cb) { if (!this._sock || !isWritable(this._sock)) throw new Error('Not connected'); const wantReply = (typeof cb === 'function'); if (!this.config.strictVendor || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { if (wantReply) { this._callbacks.push((had_err) => { if (had_err) { cb(had_err !== true ? had_err : new Error(`Unable to bind to ${socketPath}`)); return; } this._forwardingUnix[socketPath] = true; cb(); }); } this._protocol.openssh_streamLocalForward(socketPath, wantReply); return this; } if (!wantReply) return this; process.nextTick( cb, new Error( 'strictVendor enabled and server is not OpenSSH or compatible version' ) ); return this; } openssh_unforwardInStreamLocal(socketPath, cb) { if (!this._sock || !isWritable(this._sock)) throw new Error('Not connected'); const wantReply = (typeof cb === 'function'); if (!this.config.strictVendor || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { if (wantReply) { this._callbacks.push((had_err) => { if (had_err) { cb(had_err !== true ? had_err : new Error(`Unable to unbind from ${socketPath}`)); return; } delete this._forwardingUnix[socketPath]; cb(); }); } this._protocol.openssh_cancelStreamLocalForward(socketPath, wantReply); return this; } if (!wantReply) return this; process.nextTick( cb, new Error( 'strictVendor enabled and server is not OpenSSH or compatible version' ) ); return this; } openssh_forwardOutStreamLocal(socketPath, cb) { if (!this._sock || !isWritable(this._sock)) throw new Error('Not connected'); if (typeof cb !== 'function') cb = noop; if (!this.config.strictVendor || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { openChannel(this, 'direct-streamlocal@openssh.com', { socketPath }, cb); return this; } process.nextTick( cb, new Error( 'strictVendor enabled and server is not OpenSSH or compatible version' ) ); return this; } sftp(cb) { if (!this._sock || !isWritable(this._sock)) throw new Error('Not connected'); openChannel(this, 'sftp', (err, sftp) => { if (err) { cb(err); return; } reqSubsystem(sftp, 'sftp', (err, sftp_) => { if (err) { cb(err); return; } function removeListeners() { sftp.removeListener('ready', onReady); sftp.removeListener('error', onError); sftp.removeListener('exit', onExit); sftp.removeListener('close', onExit); } function onReady() { // TODO: do not remove exit/close in case remote end closes the // channel abruptly and we need to notify outstanding callbacks removeListeners(); cb(undefined, sftp); } function onError(err) { removeListeners(); cb(err); } function onExit(code, signal) { removeListeners(); let msg; if (typeof code === 'number') msg = `Received exit code ${code} while establishing SFTP session`; else if (signal !== undefined) msg = `Received signal ${signal} while establishing SFTP session`; else msg = 'Received unexpected SFTP session termination'; const err = new Error(msg); err.code = code; err.signal = signal; cb(err); } sftp.on('ready', onReady) .on('error', onError) .on('exit', onExit) .on('close', onExit); sftp._init(); }); }); return this; } setNoDelay(noDelay) { if (this._sock && typeof this._sock.setNoDelay === 'function') this._sock.setNoDelay(noDelay); return this; } } function openChannel(self, type, opts, cb) { // Ask the server to open a channel for some purpose // (e.g. session (sftp, exec, shell), or forwarding a TCP connection const initWindow = MAX_WINDOW; const maxPacket = PACKET_SIZE; if (typeof opts === 'function') { cb = opts; opts = {}; } const wrapper = (err, stream) => { cb(err, stream); }; wrapper.type = type; const localChan = self._chanMgr.add(wrapper); if (localChan === -1) { cb(new Error('No free channels available')); return; } switch (type) { case 'session': case 'sftp': self._protocol.session(localChan, initWindow, maxPacket); break; case 'direct-tcpip': self._protocol.directTcpip(localChan, initWindow, maxPacket, opts); break; case 'direct-streamlocal@openssh.com': self._protocol.openssh_directStreamLocal( localChan, initWindow, maxPacket, opts ); break; default: throw new Error(`Unsupported channel type: ${type}`); } } function reqX11(chan, screen, cb) { // Asks server to start sending us X11 connections const cfg = { single: false, protocol: 'MIT-MAGIC-COOKIE-1', cookie: undefined, screen: 0 }; if (typeof screen === 'function') { cb = screen; } else if (typeof screen === 'object' && screen !== null) { if (typeof screen.single === 'boolean') cfg.single = screen.single; if (typeof screen.screen === 'number') cfg.screen = screen.screen; if (typeof screen.protocol === 'string') cfg.protocol = screen.protocol; if (typeof screen.cookie === 'string') cfg.cookie = screen.cookie; else if (Buffer.isBuffer(screen.cookie)) cfg.cookie = screen.cookie.hexSlice(0, screen.cookie.length); } if (cfg.cookie === undefined) cfg.cookie = randomCookie(); const wantReply = (typeof cb === 'function'); if (chan.outgoing.state !== 'open') { if (wantReply) cb(new Error('Channel is not open')); return; } if (wantReply) { chan._callbacks.push((had_err) => { if (had_err) { cb(had_err !== true ? had_err : new Error('Unable to request X11')); return; } chan._hasX11 = true; ++chan._client._acceptX11; chan.once('close', () => { if (chan._client._acceptX11) --chan._client._acceptX11; }); cb(); }); } chan._client._protocol.x11Forward(chan.outgoing.id, cfg, wantReply); } function reqPty(chan, opts, cb) { let rows = 24; let cols = 80; let width = 640; let height = 480; let term = 'vt100'; let modes = null; if (typeof opts === 'function') { cb = opts; } else if (typeof opts === 'object' && opts !== null) { if (typeof opts.rows === 'number') rows = opts.rows; if (typeof opts.cols === 'number') cols = opts.cols; if (typeof opts.width === 'number') width = opts.width; if (typeof opts.height === 'number') height = opts.height; if (typeof opts.term === 'string') term = opts.term; if (typeof opts.modes === 'object') modes = opts.modes; } const wantReply = (typeof cb === 'function'); if (chan.outgoing.state !== 'open') { if (wantReply) cb(new Error('Channel is not open')); return; } if (wantReply) { chan._callbacks.push((had_err) => { if (had_err) { cb(had_err !== true ? had_err : new Error('Unable to request a pseudo-terminal')); return; } cb(); }); } chan._client._protocol.pty(chan.outgoing.id, rows, cols, height, width, term, modes, wantReply); } function reqAgentFwd(chan, cb) { const wantReply = (typeof cb === 'function'); if (chan.outgoing.state !== 'open') { wantReply && cb(new Error('Channel is not open')); return; } if (chan._client._agentFwdEnabled) { wantReply && cb(false); return; } chan._client._agentFwdEnabled = true; chan._callbacks.push((had_err) => { if (had_err) { chan._client._agentFwdEnabled = false; if (wantReply) { cb(had_err !== true ? had_err : new Error('Unable to request agent forwarding')); } return; } if (wantReply) cb(); }); chan._client._protocol.openssh_agentForward(chan.outgoing.id, true); } function reqShell(chan, cb) { if (chan.outgoing.state !== 'open') { cb(new Error('Channel is not open')); return; } chan._callbacks.push((had_err) => { if (had_err) { cb(had_err !== true ? had_err : new Error('Unable to open shell')); return; } chan.subtype = 'shell'; cb(undefined, chan); }); chan._client._protocol.shell(chan.outgoing.id, true); } function reqExec(chan, cmd, opts, cb) { if (chan.outgoing.state !== 'open') { cb(new Error('Channel is not open')); return; } chan._callbacks.push((had_err) => { if (had_err) { cb(had_err !== true ? had_err : new Error('Unable to exec')); return; } chan.subtype = 'exec'; chan.allowHalfOpen = (opts.allowHalfOpen !== false); cb(undefined, chan); }); chan._client._protocol.exec(chan.outgoing.id, cmd, true); } function reqEnv(chan, env) { if (chan.outgoing.state !== 'open') return; const keys = Object.keys(env || {}); for (let i = 0; i < keys.length; ++i) { const key = keys[i]; const val = env[key]; chan._client._protocol.env(chan.outgoing.id, key, val, false); } } function reqSubsystem(chan, name, cb) { if (chan.outgoing.state !== 'open') { cb(new Error('Channel is not open')); return; } chan._callbacks.push((had_err) => { if (had_err) { cb(had_err !== true ? had_err : new Error(`Unable to start subsystem: ${name}`)); return; } chan.subtype = 'subsystem'; cb(undefined, chan); }); chan._client._protocol.subsystem(chan.outgoing.id, name, true); } // TODO: inline implementation into single call site function onCHANNEL_OPEN(self, info) { // The server is trying to open a channel with us, this is usually when // we asked the server to forward us connections on some port and now they // are asking us to accept/deny an incoming connection on their side let localChan = -1; let reason; const accept = () => { const chanInfo = { type: info.type, incoming: { id: localChan, window: MAX_WINDOW, packetSize: PACKET_SIZE, state: 'open' }, outgoing: { id: info.sender, window: info.window, packetSize: info.packetSize, state: 'open' } }; const stream = new Channel(self, chanInfo); self._chanMgr.update(localChan, stream); self._protocol.channelOpenConfirm(info.sender, localChan, MAX_WINDOW, PACKET_SIZE); return stream; }; const reject = () => { if (reason === undefined) { if (localChan === -1) reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; else reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; } if (localChan !== -1) self._chanMgr.remove(localChan); self._protocol.channelOpenFail(info.sender, reason, ''); }; const reserveChannel = () => { localChan = self._chanMgr.add(); if (localChan === -1) { reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; if (self.config.debug) { self.config.debug( 'Client: Automatic rejection of incoming channel open: ' + 'no channels available' ); } } return (localChan !== -1); }; const data = info.data; switch (info.type) { case 'forwarded-tcpip': { const val = self._forwarding[`${data.destIP}:${data.destPort}`]; if (val !== undefined && reserveChannel()) { if (data.destPort === 0) data.destPort = val; self.emit('tcp connection', data, accept, reject); return; } break; } case 'forwarded-streamlocal@openssh.com': if (self._forwardingUnix[data.socketPath] !== undefined && reserveChannel()) { self.emit('unix connection', data, accept, reject); return; } break; case 'auth-agent@openssh.com': if (self._agentFwdEnabled && typeof self._agent.getStream === 'function' && reserveChannel()) { self._agent.getStream((err, stream) => { if (err) return reject(); const upstream = accept(); upstream.pipe(stream).pipe(upstream); }); return; } break; case 'x11': if (self._acceptX11 !== 0 && reserveChannel()) { self.emit('x11', data, accept, reject); return; } break; default: // Automatically reject any unsupported channel open requests reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; if (self.config.debug) { self.config.debug( 'Client: Automatic rejection of unsupported incoming channel open ' + `type: ${info.type}` ); } } if (reason === undefined) { reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; if (self.config.debug) { self.config.debug( 'Client: Automatic rejection of unexpected incoming channel open for: ' + info.type ); } } reject(); } const randomCookie = (() => { const buffer = Buffer.allocUnsafe(16); return () => { randomFillSync(buffer, 0, 16); return buffer.hexSlice(0, 16); }; })(); function makeSimpleAuthHandler(authList) { if (!Array.isArray(authList)) throw new Error('authList must be an array'); let a = 0; return (authsLeft, partialSuccess, cb) => { if (a === authList.length) return false; return authList[a++]; }; } function hostKeysProve(client, keys_, cb) { if (!client._sock || !isWritable(client._sock)) return; if (typeof cb !== 'function') cb = noop; if (!Array.isArray(keys_)) throw new TypeError('Invalid keys argument type'); const keys = []; for (const key of keys_) { const parsed = parseKey(key); if (parsed instanceof Error) throw parsed; keys.push(parsed); } if (!client.config.strictVendor || (client.config.strictVendor && RE_OPENSSH.test(client._remoteVer))) { client._callbacks.push((had_err, data) => { if (had_err) { cb(had_err !== true ? had_err : new Error('Server failed to prove supplied keys')); return; } // TODO: move all of this parsing/verifying logic out of the client? const ret = []; let keyIdx = 0; bufferParser.init(data, 0); while (bufferParser.avail()) { if (keyIdx === keys.length) break; const key = keys[keyIdx++]; const keyPublic = key.getPublicSSH(); const sigEntry = bufferParser.readString(); sigParser.init(sigEntry, 0); const type = sigParser.readString(true); let value = sigParser.readString(); let algo; if (type !== key.type) { if (key.type === 'ssh-rsa') { switch (type) { case 'rsa-sha2-256': algo = 'sha256'; break; case 'rsa-sha2-512': algo = 'sha512'; break; default: continue; } } else { continue; } } const sessionID = client._protocol._kex.sessionID; const verifyData = Buffer.allocUnsafe( 4 + 29 + 4 + sessionID.length + 4 + keyPublic.length ); let p = 0; writeUInt32BE(verifyData, 29, p); verifyData.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29); writeUInt32BE(verifyData, sessionID.length, p += 29); bufferCopy(sessionID, verifyData, 0, sessionID.length, p += 4); writeUInt32BE(verifyData, keyPublic.length, p += sessionID.length); bufferCopy(keyPublic, verifyData, 0, keyPublic.length, p += 4); if (!(value = sigSSHToASN1(value, type))) continue; if (key.verify(verifyData, value, algo) === true) ret.push(key); } sigParser.clear(); bufferParser.clear(); cb(null, ret); }); client._protocol.openssh_hostKeysProve(keys); return; } process.nextTick( cb, new Error( 'strictVendor enabled and server is not OpenSSH or compatible version' ) ); } function getKeyAlgos(client, key, serverSigAlgs) { switch (key.type) { case 'ssh-rsa': if (client._protocol._compatFlags & COMPAT.IMPLY_RSA_SHA2_SIGALGS) { if (!Array.isArray(serverSigAlgs)) serverSigAlgs = ['rsa-sha2-256', 'rsa-sha2-512']; else serverSigAlgs = ['rsa-sha2-256', 'rsa-sha2-512', ...serverSigAlgs]; } if (Array.isArray(serverSigAlgs)) { if (serverSigAlgs.indexOf('rsa-sha2-256') !== -1) return [['rsa-sha2-256', 'sha256']]; if (serverSigAlgs.indexOf('rsa-sha2-512') !== -1) return [['rsa-sha2-512', 'sha512']]; if (serverSigAlgs.indexOf('ssh-rsa') === -1) return []; } return [['ssh-rsa', 'sha1']]; } } module.exports = Client; /***/ }), /***/ 13657: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; const { Agent: HttpAgent } = __webpack_require__(13685); const { Agent: HttpsAgent } = __webpack_require__(95687); const { connect: tlsConnect } = __webpack_require__(24404); let Client; for (const ctor of [HttpAgent, HttpsAgent]) { class SSHAgent extends ctor { constructor(connectCfg, agentOptions) { super(agentOptions); this._connectCfg = connectCfg; this._defaultSrcIP = (agentOptions && agentOptions.srcIP) || 'localhost'; } createConnection(options, cb) { const srcIP = (options && options.localAddress) || this._defaultSrcIP; const srcPort = (options && options.localPort) || 0; const dstIP = options.host; const dstPort = options.port; if (Client === undefined) Client = __webpack_require__(92353); const client = new Client(); let triedForward = false; client.on('ready', () => { client.forwardOut(srcIP, srcPort, dstIP, dstPort, (err, stream) => { triedForward = true; if (err) { client.end(); return cb(err); } stream.once('close', () => client.end()); cb(null, decorateStream(stream, ctor, options)); }); }).on('error', cb).on('close', () => { if (!triedForward) cb(new Error('Unexpected connection close')); }).connect(this._connectCfg); } } exports[ctor === HttpAgent ? 'SSHTTPAgent' : 'SSHTTPSAgent'] = SSHAgent; } function noop() {} function decorateStream(stream, ctor, options) { if (ctor === HttpAgent) { // HTTP stream.setKeepAlive = noop; stream.setNoDelay = noop; stream.setTimeout = noop; stream.ref = noop; stream.unref = noop; stream.destroySoon = stream.destroy; return stream; } // HTTPS options.socket = stream; const wrapped = tlsConnect(options); // This is a workaround for a regression in node v12.16.3+ // https://github.com/nodejs/node/issues/35904 const onClose = (() => { let called = false; return () => { if (called) return; called = true; if (stream.isPaused()) stream.resume(); }; })(); // 'end' listener is needed because 'close' is not emitted in some scenarios // in node v12.x for some unknown reason wrapped.on('end', onClose).on('close', onClose); return wrapped; } /***/ }), /***/ 29005: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const { AgentProtocol, BaseAgent, createAgent, CygwinAgent, OpenSSHAgent, PageantAgent, } = __webpack_require__(81119); const { SSHTTPAgent: HTTPAgent, SSHTTPSAgent: HTTPSAgent, } = __webpack_require__(13657); const { parseKey } = __webpack_require__(13781); const { flagsToString, OPEN_MODE, STATUS_CODE, stringToFlags, } = __webpack_require__(64061); module.exports = { AgentProtocol, BaseAgent, createAgent, Client: __webpack_require__(92353), CygwinAgent, HTTPAgent, HTTPSAgent, OpenSSHAgent, PageantAgent, Server: __webpack_require__(37465), utils: { parseKey, ...__webpack_require__(88970), sftp: { flagsToString, OPEN_MODE, STATUS_CODE, stringToFlags, }, }, }; /***/ }), /***/ 88970: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const { createCipheriv, generateKeyPair: generateKeyPair_, generateKeyPairSync: generateKeyPairSync_, getCurves, randomBytes, } = __webpack_require__(6113); const { Ber } = __webpack_require__(90476); const bcrypt_pbkdf = __webpack_require__(62703).pbkdf; const { CIPHER_INFO } = __webpack_require__(83877); const SALT_LEN = 16; const DEFAULT_ROUNDS = 16; const curves = getCurves(); const ciphers = new Map(Object.entries(CIPHER_INFO)); function makeArgs(type, opts) { if (typeof type !== 'string') throw new TypeError('Key type must be a string'); const publicKeyEncoding = { type: 'spki', format: 'der' }; const privateKeyEncoding = { type: 'pkcs8', format: 'der' }; switch (type.toLowerCase()) { case 'rsa': { if (typeof opts !== 'object' || opts === null) throw new TypeError('Missing options object for RSA key'); const modulusLength = opts.bits; if (!Number.isInteger(modulusLength)) throw new TypeError('RSA bits must be an integer'); if (modulusLength <= 0 || modulusLength > 16384) throw new RangeError('RSA bits must be non-zero and <= 16384'); return ['rsa', { modulusLength, publicKeyEncoding, privateKeyEncoding }]; } case 'ecdsa': { if (typeof opts !== 'object' || opts === null) throw new TypeError('Missing options object for ECDSA key'); if (!Number.isInteger(opts.bits)) throw new TypeError('ECDSA bits must be an integer'); let namedCurve; switch (opts.bits) { case 256: namedCurve = 'prime256v1'; break; case 384: namedCurve = 'secp384r1'; break; case 521: namedCurve = 'secp521r1'; break; default: throw new Error('ECDSA bits must be 256, 384, or 521'); } if (!curves.includes(namedCurve)) throw new Error('Unsupported ECDSA bits value'); return ['ec', { namedCurve, publicKeyEncoding, privateKeyEncoding }]; } case 'ed25519': return ['ed25519', { publicKeyEncoding, privateKeyEncoding }]; default: throw new Error(`Unsupported key type: ${type}`); } } function parseDERs(keyType, pub, priv) { switch (keyType) { case 'rsa': { // Note: we don't need to parse the public key since the PKCS8 private key // already includes the public key parameters // Parse private key let reader = new Ber.Reader(priv); reader.readSequence(); // - Version if (reader.readInt() !== 0) throw new Error('Unsupported version in RSA private key'); // - Algorithm reader.readSequence(); if (reader.readOID() !== '1.2.840.113549.1.1.1') throw new Error('Bad RSA private OID'); // - Algorithm parameters (RSA has none) if (reader.readByte() !== Ber.Null) throw new Error('Malformed RSA private key (expected null)'); if (reader.readByte() !== 0x00) { throw new Error( 'Malformed RSA private key (expected zero-length null)' ); } reader = new Ber.Reader(reader.readString(Ber.OctetString, true)); reader.readSequence(); if (reader.readInt() !== 0) throw new Error('Unsupported version in RSA private key'); const n = reader.readString(Ber.Integer, true); const e = reader.readString(Ber.Integer, true); const d = reader.readString(Ber.Integer, true); const p = reader.readString(Ber.Integer, true); const q = reader.readString(Ber.Integer, true); reader.readString(Ber.Integer, true); // dmp1 reader.readString(Ber.Integer, true); // dmq1 const iqmp = reader.readString(Ber.Integer, true); /* OpenSSH RSA private key: string "ssh-rsa" string n -- public string e -- public string d -- private string iqmp -- private string p -- private string q -- private */ const keyName = Buffer.from('ssh-rsa'); const privBuf = Buffer.allocUnsafe( 4 + keyName.length + 4 + n.length + 4 + e.length + 4 + d.length + 4 + iqmp.length + 4 + p.length + 4 + q.length ); let pos = 0; privBuf.writeUInt32BE(keyName.length, pos += 0); privBuf.set(keyName, pos += 4); privBuf.writeUInt32BE(n.length, pos += keyName.length); privBuf.set(n, pos += 4); privBuf.writeUInt32BE(e.length, pos += n.length); privBuf.set(e, pos += 4); privBuf.writeUInt32BE(d.length, pos += e.length); privBuf.set(d, pos += 4); privBuf.writeUInt32BE(iqmp.length, pos += d.length); privBuf.set(iqmp, pos += 4); privBuf.writeUInt32BE(p.length, pos += iqmp.length); privBuf.set(p, pos += 4); privBuf.writeUInt32BE(q.length, pos += p.length); privBuf.set(q, pos += 4); /* OpenSSH RSA public key: string "ssh-rsa" string e -- public string n -- public */ const pubBuf = Buffer.allocUnsafe( 4 + keyName.length + 4 + e.length + 4 + n.length ); pos = 0; pubBuf.writeUInt32BE(keyName.length, pos += 0); pubBuf.set(keyName, pos += 4); pubBuf.writeUInt32BE(e.length, pos += keyName.length); pubBuf.set(e, pos += 4); pubBuf.writeUInt32BE(n.length, pos += e.length); pubBuf.set(n, pos += 4); return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf }; } case 'ec': { // Parse public key let reader = new Ber.Reader(pub); reader.readSequence(); reader.readSequence(); if (reader.readOID() !== '1.2.840.10045.2.1') throw new Error('Bad ECDSA public OID'); // Skip curve OID, we'll get it from the private key reader.readOID(); let pubBin = reader.readString(Ber.BitString, true); { // Remove leading zero bytes let i = 0; for (; i < pubBin.length && pubBin[i] === 0x00; ++i); if (i > 0) pubBin = pubBin.slice(i); } // Parse private key reader = new Ber.Reader(priv); reader.readSequence(); // - Version if (reader.readInt() !== 0) throw new Error('Unsupported version in ECDSA private key'); reader.readSequence(); if (reader.readOID() !== '1.2.840.10045.2.1') throw new Error('Bad ECDSA private OID'); const curveOID = reader.readOID(); let sshCurveName; switch (curveOID) { case '1.2.840.10045.3.1.7': // prime256v1/secp256r1 sshCurveName = 'nistp256'; break; case '1.3.132.0.34': // secp384r1 sshCurveName = 'nistp384'; break; case '1.3.132.0.35': // secp521r1 sshCurveName = 'nistp521'; break; default: throw new Error('Unsupported curve in ECDSA private key'); } reader = new Ber.Reader(reader.readString(Ber.OctetString, true)); reader.readSequence(); // - Version if (reader.readInt() !== 1) throw new Error('Unsupported version in ECDSA private key'); // Add leading zero byte to prevent negative bignum in private key const privBin = Buffer.concat([ Buffer.from([0x00]), reader.readString(Ber.OctetString, true) ]); /* OpenSSH ECDSA private key: string "ecdsa-sha2-" string curve name string Q -- public string d -- private */ const keyName = Buffer.from(`ecdsa-sha2-${sshCurveName}`); sshCurveName = Buffer.from(sshCurveName); const privBuf = Buffer.allocUnsafe( 4 + keyName.length + 4 + sshCurveName.length + 4 + pubBin.length + 4 + privBin.length ); let pos = 0; privBuf.writeUInt32BE(keyName.length, pos += 0); privBuf.set(keyName, pos += 4); privBuf.writeUInt32BE(sshCurveName.length, pos += keyName.length); privBuf.set(sshCurveName, pos += 4); privBuf.writeUInt32BE(pubBin.length, pos += sshCurveName.length); privBuf.set(pubBin, pos += 4); privBuf.writeUInt32BE(privBin.length, pos += pubBin.length); privBuf.set(privBin, pos += 4); /* OpenSSH ECDSA public key: string "ecdsa-sha2-" string curve name string Q -- public */ const pubBuf = Buffer.allocUnsafe( 4 + keyName.length + 4 + sshCurveName.length + 4 + pubBin.length ); pos = 0; pubBuf.writeUInt32BE(keyName.length, pos += 0); pubBuf.set(keyName, pos += 4); pubBuf.writeUInt32BE(sshCurveName.length, pos += keyName.length); pubBuf.set(sshCurveName, pos += 4); pubBuf.writeUInt32BE(pubBin.length, pos += sshCurveName.length); pubBuf.set(pubBin, pos += 4); return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf }; } case 'ed25519': { // Parse public key let reader = new Ber.Reader(pub); reader.readSequence(); // - Algorithm reader.readSequence(); if (reader.readOID() !== '1.3.101.112') throw new Error('Bad ED25519 public OID'); // - Attributes (absent for ED25519) let pubBin = reader.readString(Ber.BitString, true); { // Remove leading zero bytes let i = 0; for (; i < pubBin.length && pubBin[i] === 0x00; ++i); if (i > 0) pubBin = pubBin.slice(i); } // Parse private key reader = new Ber.Reader(priv); reader.readSequence(); // - Version if (reader.readInt() !== 0) throw new Error('Unsupported version in ED25519 private key'); // - Algorithm reader.readSequence(); if (reader.readOID() !== '1.3.101.112') throw new Error('Bad ED25519 private OID'); // - Attributes (absent) reader = new Ber.Reader(reader.readString(Ber.OctetString, true)); const privBin = reader.readString(Ber.OctetString, true); /* OpenSSH ed25519 private key: string "ssh-ed25519" string public key string private key + public key */ const keyName = Buffer.from('ssh-ed25519'); const privBuf = Buffer.allocUnsafe( 4 + keyName.length + 4 + pubBin.length + 4 + (privBin.length + pubBin.length) ); let pos = 0; privBuf.writeUInt32BE(keyName.length, pos += 0); privBuf.set(keyName, pos += 4); privBuf.writeUInt32BE(pubBin.length, pos += keyName.length); privBuf.set(pubBin, pos += 4); privBuf.writeUInt32BE( privBin.length + pubBin.length, pos += pubBin.length ); privBuf.set(privBin, pos += 4); privBuf.set(pubBin, pos += privBin.length); /* OpenSSH ed25519 public key: string "ssh-ed25519" string public key */ const pubBuf = Buffer.allocUnsafe( 4 + keyName.length + 4 + pubBin.length ); pos = 0; pubBuf.writeUInt32BE(keyName.length, pos += 0); pubBuf.set(keyName, pos += 4); pubBuf.writeUInt32BE(pubBin.length, pos += keyName.length); pubBuf.set(pubBin, pos += 4); return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf }; } } } function convertKeys(keyType, pub, priv, opts) { let format = 'new'; let encrypted; let comment = ''; if (typeof opts === 'object' && opts !== null) { if (typeof opts.comment === 'string' && opts.comment) comment = opts.comment; if (typeof opts.format === 'string' && opts.format) format = opts.format; if (opts.passphrase) { let passphrase; if (typeof opts.passphrase === 'string') passphrase = Buffer.from(opts.passphrase); else if (Buffer.isBuffer(opts.passphrase)) passphrase = opts.passphrase; else throw new Error('Invalid passphrase'); if (opts.cipher === undefined) throw new Error('Missing cipher name'); const cipher = ciphers.get(opts.cipher); if (cipher === undefined) throw new Error('Invalid cipher name'); if (format === 'new') { let rounds = DEFAULT_ROUNDS; if (opts.rounds !== undefined) { if (!Number.isInteger(opts.rounds)) throw new TypeError('rounds must be an integer'); if (opts.rounds > 0) rounds = opts.rounds; } const gen = Buffer.allocUnsafe(cipher.keyLen + cipher.ivLen); const salt = randomBytes(SALT_LEN); const r = bcrypt_pbkdf( passphrase, passphrase.length, salt, salt.length, gen, gen.length, rounds ); if (r !== 0) return new Error('Failed to generate information to encrypt key'); /* string salt uint32 rounds */ const kdfOptions = Buffer.allocUnsafe(4 + salt.length + 4); { let pos = 0; kdfOptions.writeUInt32BE(salt.length, pos += 0); kdfOptions.set(salt, pos += 4); kdfOptions.writeUInt32BE(rounds, pos += salt.length); } encrypted = { cipher, cipherName: opts.cipher, kdfName: 'bcrypt', kdfOptions, key: gen.slice(0, cipher.keyLen), iv: gen.slice(cipher.keyLen), }; } } } switch (format) { case 'new': { let privateB64 = '-----BEGIN OPENSSH PRIVATE KEY-----\n'; let publicB64; /* byte[] "openssh-key-v1\0" string ciphername string kdfname string kdfoptions uint32 number of keys N string publickey1 string encrypted, padded list of private keys uint32 checkint uint32 checkint byte[] privatekey1 string comment1 byte 1 byte 2 byte 3 ... byte padlen % 255 */ const cipherName = Buffer.from(encrypted ? encrypted.cipherName : 'none'); const kdfName = Buffer.from(encrypted ? encrypted.kdfName : 'none'); const kdfOptions = (encrypted ? encrypted.kdfOptions : Buffer.alloc(0)); const blockLen = (encrypted ? encrypted.cipher.blockLen : 8); const parsed = parseDERs(keyType, pub, priv); const checkInt = randomBytes(4); const commentBin = Buffer.from(comment); const privBlobLen = (4 + 4 + parsed.priv.length + 4 + commentBin.length); let padding = []; for (let i = 1; ((privBlobLen + padding.length) % blockLen); ++i) padding.push(i & 0xFF); padding = Buffer.from(padding); let privBlob = Buffer.allocUnsafe(privBlobLen + padding.length); let extra; { let pos = 0; privBlob.set(checkInt, pos += 0); privBlob.set(checkInt, pos += 4); privBlob.set(parsed.priv, pos += 4); privBlob.writeUInt32BE(commentBin.length, pos += parsed.priv.length); privBlob.set(commentBin, pos += 4); privBlob.set(padding, pos += commentBin.length); } if (encrypted) { const options = { authTagLength: encrypted.cipher.authLen }; const cipher = createCipheriv( encrypted.cipher.sslName, encrypted.key, encrypted.iv, options ); cipher.setAutoPadding(false); privBlob = Buffer.concat([ cipher.update(privBlob), cipher.final() ]); if (encrypted.cipher.authLen > 0) extra = cipher.getAuthTag(); else extra = Buffer.alloc(0); encrypted.key.fill(0); encrypted.iv.fill(0); } else { extra = Buffer.alloc(0); } const magicBytes = Buffer.from('openssh-key-v1\0'); const privBin = Buffer.allocUnsafe( magicBytes.length + 4 + cipherName.length + 4 + kdfName.length + 4 + kdfOptions.length + 4 + 4 + parsed.pub.length + 4 + privBlob.length + extra.length ); { let pos = 0; privBin.set(magicBytes, pos += 0); privBin.writeUInt32BE(cipherName.length, pos += magicBytes.length); privBin.set(cipherName, pos += 4); privBin.writeUInt32BE(kdfName.length, pos += cipherName.length); privBin.set(kdfName, pos += 4); privBin.writeUInt32BE(kdfOptions.length, pos += kdfName.length); privBin.set(kdfOptions, pos += 4); privBin.writeUInt32BE(1, pos += kdfOptions.length); privBin.writeUInt32BE(parsed.pub.length, pos += 4); privBin.set(parsed.pub, pos += 4); privBin.writeUInt32BE(privBlob.length, pos += parsed.pub.length); privBin.set(privBlob, pos += 4); privBin.set(extra, pos += privBlob.length); } { const b64 = privBin.base64Slice(0, privBin.length); let formatted = b64.replace(/.{64}/g, '$&\n'); if (b64.length & 63) formatted += '\n'; privateB64 += formatted; } { const b64 = parsed.pub.base64Slice(0, parsed.pub.length); publicB64 = `${parsed.sshName} ${b64}${comment ? ` ${comment}` : ''}`; } privateB64 += '-----END OPENSSH PRIVATE KEY-----\n'; return { private: privateB64, public: publicB64, }; } default: throw new Error('Invalid output key format'); } } function noop() {} module.exports = { generateKeyPair: (keyType, opts, cb) => { if (typeof opts === 'function') { cb = opts; opts = undefined; } if (typeof cb !== 'function') cb = noop; const args = makeArgs(keyType, opts); generateKeyPair_(...args, (err, pub, priv) => { if (err) return cb(err); let ret; try { ret = convertKeys(args[0], pub, priv, opts); } catch (ex) { return cb(ex); } cb(null, ret); }); }, generateKeyPairSync: (keyType, opts) => { const args = makeArgs(keyType, opts); const { publicKey: pub, privateKey: priv } = generateKeyPairSync_(...args); return convertKeys(args[0], pub, priv, opts); } }; /***/ }), /***/ 53603: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* TODO: * Replace `buffer._pos` usage in keyParser.js and elsewhere * Utilize optional "writev" support when writing packets from cipher.encrypt() * Built-in support for automatic re-keying, on by default * Revisit receiving unexpected/unknown packets * Error (fatal or otherwise) or ignore or pass on to user (in some or all cases)? * Including server/client check for single directional packet types? * Check packets for validity or bail as early as possible? * Automatic re-key every 2**31 packets after the last key exchange (sent or received), as suggested by RFC4344. OpenSSH currently does this. * Automatic re-key every so many blocks depending on cipher. RFC4344: Because of a birthday property of block ciphers and some modes of operation, implementations must be careful not to encrypt too many blocks with the same encryption key. Let L be the block length (in bits) of an SSH encryption method's block cipher (e.g., 128 for AES). If L is at least 128, then, after rekeying, an SSH implementation SHOULD NOT encrypt more than 2**(L/4) blocks before rekeying again. If L is at least 128, then SSH implementations should also attempt to force a rekey before receiving more than 2**(L/4) blocks. If L is less than 128 (which is the case for older ciphers such as 3DES, Blowfish, CAST-128, and IDEA), then, although it may be too expensive to rekey every 2**(L/4) blocks, it is still advisable for SSH implementations to follow the original recommendation in [RFC4253]: rekey at least once for every gigabyte of transmitted data. Note that if L is less than or equal to 128, then the recommendation in this subsection supersedes the recommendation in Section 3.1. If an SSH implementation uses a block cipher with a larger block size (e.g., Rijndael with 256-bit blocks), then the recommendations in Section 3.1 may supersede the recommendations in this subsection (depending on the lengths of the packets). */ const { inspect } = __webpack_require__(73837); const { bindingAvailable, NullCipher, NullDecipher } = __webpack_require__(83877); const { COMPAT_CHECKS, DISCONNECT_REASON, eddsaSupported, MESSAGE, SIGNALS, TERMINAL_MODE, } = __webpack_require__(3190); const { DEFAULT_KEXINIT_CLIENT, DEFAULT_KEXINIT_SERVER, KexInit, kexinit, onKEXPayload, } = __webpack_require__(65260); const { parseKey, } = __webpack_require__(13781); const MESSAGE_HANDLERS = __webpack_require__(92908); const { bufferCopy, bufferFill, bufferSlice, convertSignature, sendPacket, writeUInt32BE, } = __webpack_require__(39205); const { PacketReader, PacketWriter, ZlibPacketReader, ZlibPacketWriter, } = __webpack_require__(36993); const MODULE_VER = __webpack_require__(66674)/* .version */ .i8; const VALID_DISCONNECT_REASONS = new Map( Object.values(DISCONNECT_REASON).map((n) => [n, 1]) ); const IDENT_RAW = Buffer.from(`SSH-2.0-ssh2js${MODULE_VER}`); const IDENT = Buffer.from(`${IDENT_RAW}\r\n`); const MAX_LINE_LEN = 8192; const MAX_LINES = 1024; const PING_PAYLOAD = Buffer.from([ MESSAGE.GLOBAL_REQUEST, // "keepalive@openssh.com" 0, 0, 0, 21, 107, 101, 101, 112, 97, 108, 105, 118, 101, 64, 111, 112, 101, 110, 115, 115, 104, 46, 99, 111, 109, // Request a reply 1, ]); const NO_TERMINAL_MODES_BUFFER = Buffer.from([ TERMINAL_MODE.TTY_OP_END ]); function noop() {} /* Inbound: * kexinit payload (needed only until exchange hash is generated) * raw ident * rekey packet queue * expected packet (implemented as separate _parse() function?) Outbound: * kexinit payload (needed only until exchange hash is generated) * rekey packet queue * kex secret (needed only until NEWKEYS) * exchange hash (needed only until NEWKEYS) * session ID (set to exchange hash from initial handshake) */ class Protocol { constructor(config) { const onWrite = config.onWrite; if (typeof onWrite !== 'function') throw new Error('Missing onWrite function'); this._onWrite = (data) => { onWrite(data); }; const onError = config.onError; if (typeof onError !== 'function') throw new Error('Missing onError function'); this._onError = (err) => { onError(err); }; const debug = config.debug; this._debug = (typeof debug === 'function' ? (msg) => { debug(msg); } : undefined); const onHeader = config.onHeader; this._onHeader = (typeof onHeader === 'function' ? (...args) => { onHeader(...args); } : noop); const onPacket = config.onPacket; this._onPacket = (typeof onPacket === 'function' ? () => { onPacket(); } : noop); let onHandshakeComplete = config.onHandshakeComplete; if (typeof onHandshakeComplete !== 'function') onHandshakeComplete = noop; let firstHandshake; this._onHandshakeComplete = (...args) => { this._debug && this._debug('Handshake completed'); if (firstHandshake === undefined) firstHandshake = true; else firstHandshake = false; // Process packets queued during a rekey where necessary const oldQueue = this._queue; if (oldQueue) { this._queue = undefined; this._debug && this._debug( `Draining outbound queue (${oldQueue.length}) ...` ); for (let i = 0; i < oldQueue.length; ++i) { const data = oldQueue[i]; // data === payload only // XXX: hacky let finalized = this._packetRW.write.finalize(data); if (finalized === data) { const packet = this._cipher.allocPacket(data.length); packet.set(data, 5); finalized = packet; } sendPacket(this, finalized); } this._debug && this._debug('... finished draining outbound queue'); } if (firstHandshake && this._server && this._kex.remoteExtInfoEnabled) sendExtInfo(this); onHandshakeComplete(...args); }; this._queue = undefined; const messageHandlers = config.messageHandlers; if (typeof messageHandlers === 'object' && messageHandlers !== null) this._handlers = messageHandlers; else this._handlers = {}; this._onPayload = onPayload.bind(this); this._server = !!config.server; this._banner = undefined; let greeting; if (this._server) { if (typeof config.hostKeys !== 'object' || config.hostKeys === null) throw new Error('Missing server host key(s)'); this._hostKeys = config.hostKeys; // Greeting displayed before the ssh identification string is sent, this // is usually ignored by most clients if (typeof config.greeting === 'string' && config.greeting.length) { greeting = (config.greeting.slice(-2) === '\r\n' ? config.greeting : `${config.greeting}\r\n`); } // Banner shown after the handshake completes, but before user // authentication begins if (typeof config.banner === 'string' && config.banner.length) { this._banner = (config.banner.slice(-2) === '\r\n' ? config.banner : `${config.banner}\r\n`); } } else { this._hostKeys = undefined; } let offer = config.offer; if (typeof offer !== 'object' || offer === null) { offer = (this._server ? DEFAULT_KEXINIT_SERVER : DEFAULT_KEXINIT_CLIENT); } else if (offer.constructor !== KexInit) { if (!this._server) offer.kex = offer.kex.concat(['ext-info-c']); offer = new KexInit(offer); } this._kex = undefined; this._kexinit = undefined; this._offer = offer; this._cipher = new NullCipher(0, this._onWrite); this._decipher = undefined; this._skipNextInboundPacket = false; this._packetRW = { read: new PacketReader(), write: new PacketWriter(this), }; this._hostVerifier = (!this._server && typeof config.hostVerifier === 'function' ? config.hostVerifier : undefined); this._parse = parseHeader; this._buffer = undefined; this._authsQueue = []; this._authenticated = false; this._remoteIdentRaw = undefined; let sentIdent; if (typeof config.ident === 'string') { this._identRaw = Buffer.from(`SSH-2.0-${config.ident}`); sentIdent = Buffer.allocUnsafe(this._identRaw.length + 2); sentIdent.set(this._identRaw, 0); sentIdent[sentIdent.length - 2] = 13; // '\r' sentIdent[sentIdent.length - 1] = 10; // '\n' } else if (Buffer.isBuffer(config.ident)) { const fullIdent = Buffer.allocUnsafe(8 + config.ident.length); fullIdent.latin1Write('SSH-2.0-', 0, 8); fullIdent.set(config.ident, 8); this._identRaw = fullIdent; sentIdent = Buffer.allocUnsafe(fullIdent.length + 2); sentIdent.set(fullIdent, 0); sentIdent[sentIdent.length - 2] = 13; // '\r' sentIdent[sentIdent.length - 1] = 10; // '\n' } else { this._identRaw = IDENT_RAW; sentIdent = IDENT; } this._compatFlags = 0; if (this._debug) { if (bindingAvailable) this._debug('Custom crypto binding available'); else this._debug('Custom crypto binding not available'); } this._debug && this._debug( `Local ident: ${inspect(this._identRaw.toString())}` ); this.start = () => { this.start = undefined; if (greeting) this._onWrite(greeting); this._onWrite(sentIdent); }; } _destruct(reason) { this._packetRW.read.cleanup(); this._packetRW.write.cleanup(); this._cipher && this._cipher.free(); this._decipher && this._decipher.free(); if (typeof reason !== 'string' || reason.length === 0) reason = 'fatal error'; this.parse = () => { throw new Error(`Instance unusable after ${reason}`); }; this._onWrite = () => { throw new Error(`Instance unusable after ${reason}`); }; this._destruct = undefined; } cleanup() { this._destruct && this._destruct(); } parse(chunk, i, len) { while (i < len) i = this._parse(chunk, i, len); } // Protocol message API // =========================================================================== // Common/Shared ============================================================= // =========================================================================== // Global // ------ disconnect(reason) { const pktLen = 1 + 4 + 4 + 4; // We don't use _packetRW.write.* here because we need to make sure that // we always get a full packet allocated because this message can be sent // at any time -- even during a key exchange let p = this._packetRW.write.allocStartKEX; const packet = this._packetRW.write.alloc(pktLen, true); const end = p + pktLen; if (!VALID_DISCONNECT_REASONS.has(reason)) reason = DISCONNECT_REASON.PROTOCOL_ERROR; packet[p] = MESSAGE.DISCONNECT; writeUInt32BE(packet, reason, ++p); packet.fill(0, p += 4, end); this._debug && this._debug(`Outbound: Sending DISCONNECT (${reason})`); sendPacket(this, this._packetRW.write.finalize(packet, true), true); } ping() { const p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(PING_PAYLOAD.length); packet.set(PING_PAYLOAD, p); this._debug && this._debug( 'Outbound: Sending ping (GLOBAL_REQUEST: keepalive@openssh.com)' ); sendPacket(this, this._packetRW.write.finalize(packet)); } rekey() { if (this._kexinit === undefined) { this._debug && this._debug('Outbound: Initiated explicit rekey'); this._queue = []; kexinit(this); } else { this._debug && this._debug('Outbound: Ignoring rekey during handshake'); } } // 'ssh-connection' service-specific // --------------------------------- requestSuccess(data) { let p = this._packetRW.write.allocStart; let packet; if (Buffer.isBuffer(data)) { packet = this._packetRW.write.alloc(1 + data.length); packet[p] = MESSAGE.REQUEST_SUCCESS; packet.set(data, ++p); } else { packet = this._packetRW.write.alloc(1); packet[p] = MESSAGE.REQUEST_SUCCESS; } this._debug && this._debug('Outbound: Sending REQUEST_SUCCESS'); sendPacket(this, this._packetRW.write.finalize(packet)); } requestFailure() { const p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1); packet[p] = MESSAGE.REQUEST_FAILURE; this._debug && this._debug('Outbound: Sending REQUEST_FAILURE'); sendPacket(this, this._packetRW.write.finalize(packet)); } channelSuccess(chan) { // Does not consume window space let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4); packet[p] = MESSAGE.CHANNEL_SUCCESS; writeUInt32BE(packet, chan, ++p); this._debug && this._debug(`Outbound: Sending CHANNEL_SUCCESS (r:${chan})`); sendPacket(this, this._packetRW.write.finalize(packet)); } channelFailure(chan) { // Does not consume window space let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4); packet[p] = MESSAGE.CHANNEL_FAILURE; writeUInt32BE(packet, chan, ++p); this._debug && this._debug(`Outbound: Sending CHANNEL_FAILURE (r:${chan})`); sendPacket(this, this._packetRW.write.finalize(packet)); } channelEOF(chan) { // Does not consume window space let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4); packet[p] = MESSAGE.CHANNEL_EOF; writeUInt32BE(packet, chan, ++p); this._debug && this._debug(`Outbound: Sending CHANNEL_EOF (r:${chan})`); sendPacket(this, this._packetRW.write.finalize(packet)); } channelClose(chan) { // Does not consume window space let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4); packet[p] = MESSAGE.CHANNEL_CLOSE; writeUInt32BE(packet, chan, ++p); this._debug && this._debug(`Outbound: Sending CHANNEL_CLOSE (r:${chan})`); sendPacket(this, this._packetRW.write.finalize(packet)); } channelWindowAdjust(chan, amount) { // Does not consume window space let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 4); packet[p] = MESSAGE.CHANNEL_WINDOW_ADJUST; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, amount, p += 4); this._debug && this._debug( `Outbound: Sending CHANNEL_WINDOW_ADJUST (r:${chan}, ${amount})` ); sendPacket(this, this._packetRW.write.finalize(packet)); } channelData(chan, data) { const isBuffer = Buffer.isBuffer(data); const dataLen = (isBuffer ? data.length : Buffer.byteLength(data)); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 4 + dataLen); packet[p] = MESSAGE.CHANNEL_DATA; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, dataLen, p += 4); if (isBuffer) packet.set(data, p += 4); else packet.utf8Write(data, p += 4, dataLen); this._debug && this._debug( `Outbound: Sending CHANNEL_DATA (r:${chan}, ${dataLen})` ); sendPacket(this, this._packetRW.write.finalize(packet)); } channelExtData(chan, data, type) { const isBuffer = Buffer.isBuffer(data); const dataLen = (isBuffer ? data.length : Buffer.byteLength(data)); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + dataLen); packet[p] = MESSAGE.CHANNEL_EXTENDED_DATA; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, type, p += 4); writeUInt32BE(packet, dataLen, p += 4); if (isBuffer) packet.set(data, p += 4); else packet.utf8Write(data, p += 4, dataLen); this._debug && this._debug(`Outbound: Sending CHANNEL_EXTENDED_DATA (r:${chan})`); sendPacket(this, this._packetRW.write.finalize(packet)); } channelOpenConfirm(remote, local, initWindow, maxPacket) { let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 4); packet[p] = MESSAGE.CHANNEL_OPEN_CONFIRMATION; writeUInt32BE(packet, remote, ++p); writeUInt32BE(packet, local, p += 4); writeUInt32BE(packet, initWindow, p += 4); writeUInt32BE(packet, maxPacket, p += 4); this._debug && this._debug( `Outbound: Sending CHANNEL_OPEN_CONFIRMATION (r:${remote}, l:${local})` ); sendPacket(this, this._packetRW.write.finalize(packet)); } channelOpenFail(remote, reason, desc) { if (typeof desc !== 'string') desc = ''; const descLen = Buffer.byteLength(desc); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + descLen + 4); packet[p] = MESSAGE.CHANNEL_OPEN_FAILURE; writeUInt32BE(packet, remote, ++p); writeUInt32BE(packet, reason, p += 4); writeUInt32BE(packet, descLen, p += 4); p += 4; if (descLen) { packet.utf8Write(desc, p, descLen); p += descLen; } writeUInt32BE(packet, 0, p); // Empty language tag this._debug && this._debug(`Outbound: Sending CHANNEL_OPEN_FAILURE (r:${remote})`); sendPacket(this, this._packetRW.write.finalize(packet)); } // =========================================================================== // Client-specific =========================================================== // =========================================================================== // Global // ------ service(name) { if (this._server) throw new Error('Client-only method called in server mode'); const nameLen = Buffer.byteLength(name); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + nameLen); packet[p] = MESSAGE.SERVICE_REQUEST; writeUInt32BE(packet, nameLen, ++p); packet.utf8Write(name, p += 4, nameLen); this._debug && this._debug(`Outbound: Sending SERVICE_REQUEST (${name})`); sendPacket(this, this._packetRW.write.finalize(packet)); } // 'ssh-userauth' service-specific // ------------------------------- authPassword(username, password, newPassword) { if (this._server) throw new Error('Client-only method called in server mode'); const userLen = Buffer.byteLength(username); const passLen = Buffer.byteLength(password); const newPassLen = (newPassword ? Buffer.byteLength(newPassword) : 0); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + userLen + 4 + 14 + 4 + 8 + 1 + 4 + passLen + (newPassword ? 4 + newPassLen : 0) ); packet[p] = MESSAGE.USERAUTH_REQUEST; writeUInt32BE(packet, userLen, ++p); packet.utf8Write(username, p += 4, userLen); writeUInt32BE(packet, 14, p += userLen); packet.utf8Write('ssh-connection', p += 4, 14); writeUInt32BE(packet, 8, p += 14); packet.utf8Write('password', p += 4, 8); packet[p += 8] = (newPassword ? 1 : 0); writeUInt32BE(packet, passLen, ++p); if (Buffer.isBuffer(password)) bufferCopy(password, packet, 0, passLen, p += 4); else packet.utf8Write(password, p += 4, passLen); if (newPassword) { writeUInt32BE(packet, newPassLen, p += passLen); if (Buffer.isBuffer(newPassword)) bufferCopy(newPassword, packet, 0, newPassLen, p += 4); else packet.utf8Write(newPassword, p += 4, newPassLen); this._debug && this._debug( 'Outbound: Sending USERAUTH_REQUEST (changed password)' ); } else { this._debug && this._debug( 'Outbound: Sending USERAUTH_REQUEST (password)' ); } this._authsQueue.push('password'); sendPacket(this, this._packetRW.write.finalize(packet)); } authPK(username, pubKey, keyAlgo, cbSign) { if (this._server) throw new Error('Client-only method called in server mode'); pubKey = parseKey(pubKey); if (pubKey instanceof Error) throw new Error('Invalid key'); const keyType = pubKey.type; pubKey = pubKey.getPublicSSH(); if (typeof keyAlgo === 'function') { cbSign = keyAlgo; keyAlgo = undefined; } if (!keyAlgo) keyAlgo = keyType; const userLen = Buffer.byteLength(username); const algoLen = Buffer.byteLength(keyAlgo); const pubKeyLen = pubKey.length; const sessionID = this._kex.sessionID; const sesLen = sessionID.length; const payloadLen = (cbSign ? 4 + sesLen : 0) + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen; let packet; let p; if (cbSign) { packet = Buffer.allocUnsafe(payloadLen); p = 0; writeUInt32BE(packet, sesLen, p); packet.set(sessionID, p += 4); p += sesLen; } else { packet = this._packetRW.write.alloc(payloadLen); p = this._packetRW.write.allocStart; } packet[p] = MESSAGE.USERAUTH_REQUEST; writeUInt32BE(packet, userLen, ++p); packet.utf8Write(username, p += 4, userLen); writeUInt32BE(packet, 14, p += userLen); packet.utf8Write('ssh-connection', p += 4, 14); writeUInt32BE(packet, 9, p += 14); packet.utf8Write('publickey', p += 4, 9); packet[p += 9] = (cbSign ? 1 : 0); writeUInt32BE(packet, algoLen, ++p); packet.utf8Write(keyAlgo, p += 4, algoLen); writeUInt32BE(packet, pubKeyLen, p += algoLen); packet.set(pubKey, p += 4); if (!cbSign) { this._authsQueue.push('publickey'); this._debug && this._debug( 'Outbound: Sending USERAUTH_REQUEST (publickey -- check)' ); sendPacket(this, this._packetRW.write.finalize(packet)); return; } cbSign(packet, (signature) => { signature = convertSignature(signature, keyType); if (signature === false) throw new Error('Error while converting handshake signature'); const sigLen = signature.length; p = this._packetRW.write.allocStart; packet = this._packetRW.write.alloc( 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen + 4 + 4 + algoLen + 4 + sigLen ); // TODO: simply copy from original "packet" to new `packet` to avoid // having to write each individual field a second time? packet[p] = MESSAGE.USERAUTH_REQUEST; writeUInt32BE(packet, userLen, ++p); packet.utf8Write(username, p += 4, userLen); writeUInt32BE(packet, 14, p += userLen); packet.utf8Write('ssh-connection', p += 4, 14); writeUInt32BE(packet, 9, p += 14); packet.utf8Write('publickey', p += 4, 9); packet[p += 9] = 1; writeUInt32BE(packet, algoLen, ++p); packet.utf8Write(keyAlgo, p += 4, algoLen); writeUInt32BE(packet, pubKeyLen, p += algoLen); packet.set(pubKey, p += 4); writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += pubKeyLen); writeUInt32BE(packet, algoLen, p += 4); packet.utf8Write(keyAlgo, p += 4, algoLen); writeUInt32BE(packet, sigLen, p += algoLen); packet.set(signature, p += 4); // Servers shouldn't send packet type 60 in response to signed publickey // attempts, but if they do, interpret as type 60. this._authsQueue.push('publickey'); this._debug && this._debug( 'Outbound: Sending USERAUTH_REQUEST (publickey)' ); sendPacket(this, this._packetRW.write.finalize(packet)); }); } authHostbased(username, pubKey, hostname, userlocal, keyAlgo, cbSign) { // TODO: Make DRY by sharing similar code with authPK() if (this._server) throw new Error('Client-only method called in server mode'); pubKey = parseKey(pubKey); if (pubKey instanceof Error) throw new Error('Invalid key'); const keyType = pubKey.type; pubKey = pubKey.getPublicSSH(); if (typeof keyAlgo === 'function') { cbSign = keyAlgo; keyAlgo = undefined; } if (!keyAlgo) keyAlgo = keyType; const userLen = Buffer.byteLength(username); const algoLen = Buffer.byteLength(keyAlgo); const pubKeyLen = pubKey.length; const sessionID = this._kex.sessionID; const sesLen = sessionID.length; const hostnameLen = Buffer.byteLength(hostname); const userlocalLen = Buffer.byteLength(userlocal); const data = Buffer.allocUnsafe( 4 + sesLen + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 4 + algoLen + 4 + pubKeyLen + 4 + hostnameLen + 4 + userlocalLen ); let p = 0; writeUInt32BE(data, sesLen, p); data.set(sessionID, p += 4); data[p += sesLen] = MESSAGE.USERAUTH_REQUEST; writeUInt32BE(data, userLen, ++p); data.utf8Write(username, p += 4, userLen); writeUInt32BE(data, 14, p += userLen); data.utf8Write('ssh-connection', p += 4, 14); writeUInt32BE(data, 9, p += 14); data.utf8Write('hostbased', p += 4, 9); writeUInt32BE(data, algoLen, p += 9); data.utf8Write(keyAlgo, p += 4, algoLen); writeUInt32BE(data, pubKeyLen, p += algoLen); data.set(pubKey, p += 4); writeUInt32BE(data, hostnameLen, p += pubKeyLen); data.utf8Write(hostname, p += 4, hostnameLen); writeUInt32BE(data, userlocalLen, p += hostnameLen); data.utf8Write(userlocal, p += 4, userlocalLen); cbSign(data, (signature) => { signature = convertSignature(signature, keyType); if (!signature) throw new Error('Error while converting handshake signature'); const sigLen = signature.length; const reqDataLen = (data.length - sesLen - 4); p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( reqDataLen + 4 + 4 + algoLen + 4 + sigLen ); bufferCopy(data, packet, 4 + sesLen, data.length, p); writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += reqDataLen); writeUInt32BE(packet, algoLen, p += 4); packet.utf8Write(keyAlgo, p += 4, algoLen); writeUInt32BE(packet, sigLen, p += algoLen); packet.set(signature, p += 4); this._authsQueue.push('hostbased'); this._debug && this._debug( 'Outbound: Sending USERAUTH_REQUEST (hostbased)' ); sendPacket(this, this._packetRW.write.finalize(packet)); }); } authKeyboard(username) { if (this._server) throw new Error('Client-only method called in server mode'); const userLen = Buffer.byteLength(username); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + userLen + 4 + 14 + 4 + 20 + 4 + 4 ); packet[p] = MESSAGE.USERAUTH_REQUEST; writeUInt32BE(packet, userLen, ++p); packet.utf8Write(username, p += 4, userLen); writeUInt32BE(packet, 14, p += userLen); packet.utf8Write('ssh-connection', p += 4, 14); writeUInt32BE(packet, 20, p += 14); packet.utf8Write('keyboard-interactive', p += 4, 20); writeUInt32BE(packet, 0, p += 20); writeUInt32BE(packet, 0, p += 4); this._authsQueue.push('keyboard-interactive'); this._debug && this._debug( 'Outbound: Sending USERAUTH_REQUEST (keyboard-interactive)' ); sendPacket(this, this._packetRW.write.finalize(packet)); } authNone(username) { if (this._server) throw new Error('Client-only method called in server mode'); const userLen = Buffer.byteLength(username); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + userLen + 4 + 14 + 4 + 4); packet[p] = MESSAGE.USERAUTH_REQUEST; writeUInt32BE(packet, userLen, ++p); packet.utf8Write(username, p += 4, userLen); writeUInt32BE(packet, 14, p += userLen); packet.utf8Write('ssh-connection', p += 4, 14); writeUInt32BE(packet, 4, p += 14); packet.utf8Write('none', p += 4, 4); this._authsQueue.push('none'); this._debug && this._debug('Outbound: Sending USERAUTH_REQUEST (none)'); sendPacket(this, this._packetRW.write.finalize(packet)); } authInfoRes(responses) { if (this._server) throw new Error('Client-only method called in server mode'); let responsesTotalLen = 0; let responseLens; if (responses) { responseLens = new Array(responses.length); for (let i = 0; i < responses.length; ++i) { const len = Buffer.byteLength(responses[i]); responseLens[i] = len; responsesTotalLen += 4 + len; } } let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + responsesTotalLen); packet[p] = MESSAGE.USERAUTH_INFO_RESPONSE; if (responses) { writeUInt32BE(packet, responses.length, ++p); p += 4; for (let i = 0; i < responses.length; ++i) { const len = responseLens[i]; writeUInt32BE(packet, len, p); p += 4; if (len) { packet.utf8Write(responses[i], p, len); p += len; } } } else { writeUInt32BE(packet, 0, ++p); } this._debug && this._debug('Outbound: Sending USERAUTH_INFO_RESPONSE'); sendPacket(this, this._packetRW.write.finalize(packet)); } // 'ssh-connection' service-specific // --------------------------------- tcpipForward(bindAddr, bindPort, wantReply) { if (this._server) throw new Error('Client-only method called in server mode'); const addrLen = Buffer.byteLength(bindAddr); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 13 + 1 + 4 + addrLen + 4); packet[p] = MESSAGE.GLOBAL_REQUEST; writeUInt32BE(packet, 13, ++p); packet.utf8Write('tcpip-forward', p += 4, 13); packet[p += 13] = (wantReply === undefined || wantReply === true ? 1 : 0); writeUInt32BE(packet, addrLen, ++p); packet.utf8Write(bindAddr, p += 4, addrLen); writeUInt32BE(packet, bindPort, p += addrLen); this._debug && this._debug('Outbound: Sending GLOBAL_REQUEST (tcpip-forward)'); sendPacket(this, this._packetRW.write.finalize(packet)); } cancelTcpipForward(bindAddr, bindPort, wantReply) { if (this._server) throw new Error('Client-only method called in server mode'); const addrLen = Buffer.byteLength(bindAddr); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 20 + 1 + 4 + addrLen + 4); packet[p] = MESSAGE.GLOBAL_REQUEST; writeUInt32BE(packet, 20, ++p); packet.utf8Write('cancel-tcpip-forward', p += 4, 20); packet[p += 20] = (wantReply === undefined || wantReply === true ? 1 : 0); writeUInt32BE(packet, addrLen, ++p); packet.utf8Write(bindAddr, p += 4, addrLen); writeUInt32BE(packet, bindPort, p += addrLen); this._debug && this._debug('Outbound: Sending GLOBAL_REQUEST (cancel-tcpip-forward)'); sendPacket(this, this._packetRW.write.finalize(packet)); } openssh_streamLocalForward(socketPath, wantReply) { if (this._server) throw new Error('Client-only method called in server mode'); const socketPathLen = Buffer.byteLength(socketPath); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 31 + 1 + 4 + socketPathLen ); packet[p] = MESSAGE.GLOBAL_REQUEST; writeUInt32BE(packet, 31, ++p); packet.utf8Write('streamlocal-forward@openssh.com', p += 4, 31); packet[p += 31] = (wantReply === undefined || wantReply === true ? 1 : 0); writeUInt32BE(packet, socketPathLen, ++p); packet.utf8Write(socketPath, p += 4, socketPathLen); this._debug && this._debug( 'Outbound: Sending GLOBAL_REQUEST (streamlocal-forward@openssh.com)' ); sendPacket(this, this._packetRW.write.finalize(packet)); } openssh_cancelStreamLocalForward(socketPath, wantReply) { if (this._server) throw new Error('Client-only method called in server mode'); const socketPathLen = Buffer.byteLength(socketPath); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 38 + 1 + 4 + socketPathLen ); packet[p] = MESSAGE.GLOBAL_REQUEST; writeUInt32BE(packet, 38, ++p); packet.utf8Write('cancel-streamlocal-forward@openssh.com', p += 4, 38); packet[p += 38] = (wantReply === undefined || wantReply === true ? 1 : 0); writeUInt32BE(packet, socketPathLen, ++p); packet.utf8Write(socketPath, p += 4, socketPathLen); if (this._debug) { this._debug( 'Outbound: Sending GLOBAL_REQUEST ' + '(cancel-streamlocal-forward@openssh.com)' ); } sendPacket(this, this._packetRW.write.finalize(packet)); } directTcpip(chan, initWindow, maxPacket, cfg) { if (this._server) throw new Error('Client-only method called in server mode'); const srcLen = Buffer.byteLength(cfg.srcIP); const dstLen = Buffer.byteLength(cfg.dstIP); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 12 + 4 + 4 + 4 + 4 + srcLen + 4 + 4 + dstLen + 4 ); packet[p] = MESSAGE.CHANNEL_OPEN; writeUInt32BE(packet, 12, ++p); packet.utf8Write('direct-tcpip', p += 4, 12); writeUInt32BE(packet, chan, p += 12); writeUInt32BE(packet, initWindow, p += 4); writeUInt32BE(packet, maxPacket, p += 4); writeUInt32BE(packet, dstLen, p += 4); packet.utf8Write(cfg.dstIP, p += 4, dstLen); writeUInt32BE(packet, cfg.dstPort, p += dstLen); writeUInt32BE(packet, srcLen, p += 4); packet.utf8Write(cfg.srcIP, p += 4, srcLen); writeUInt32BE(packet, cfg.srcPort, p += srcLen); this._debug && this._debug( `Outbound: Sending CHANNEL_OPEN (r:${chan}, direct-tcpip)` ); sendPacket(this, this._packetRW.write.finalize(packet)); } openssh_directStreamLocal(chan, initWindow, maxPacket, cfg) { if (this._server) throw new Error('Client-only method called in server mode'); const pathLen = Buffer.byteLength(cfg.socketPath); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 30 + 4 + 4 + 4 + 4 + pathLen + 4 + 4 ); packet[p] = MESSAGE.CHANNEL_OPEN; writeUInt32BE(packet, 30, ++p); packet.utf8Write('direct-streamlocal@openssh.com', p += 4, 30); writeUInt32BE(packet, chan, p += 30); writeUInt32BE(packet, initWindow, p += 4); writeUInt32BE(packet, maxPacket, p += 4); writeUInt32BE(packet, pathLen, p += 4); packet.utf8Write(cfg.socketPath, p += 4, pathLen); // zero-fill reserved fields (string and uint32) bufferFill(packet, 0, p += pathLen, p + 8); if (this._debug) { this._debug( 'Outbound: Sending CHANNEL_OPEN ' + `(r:${chan}, direct-streamlocal@openssh.com)` ); } sendPacket(this, this._packetRW.write.finalize(packet)); } openssh_noMoreSessions(wantReply) { if (this._server) throw new Error('Client-only method called in server mode'); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 28 + 1); packet[p] = MESSAGE.GLOBAL_REQUEST; writeUInt32BE(packet, 28, ++p); packet.utf8Write('no-more-sessions@openssh.com', p += 4, 28); packet[p += 28] = (wantReply === undefined || wantReply === true ? 1 : 0); this._debug && this._debug( 'Outbound: Sending GLOBAL_REQUEST (no-more-sessions@openssh.com)' ); sendPacket(this, this._packetRW.write.finalize(packet)); } session(chan, initWindow, maxPacket) { if (this._server) throw new Error('Client-only method called in server mode'); // Does not consume window space let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 7 + 4 + 4 + 4); packet[p] = MESSAGE.CHANNEL_OPEN; writeUInt32BE(packet, 7, ++p); packet.utf8Write('session', p += 4, 7); writeUInt32BE(packet, chan, p += 7); writeUInt32BE(packet, initWindow, p += 4); writeUInt32BE(packet, maxPacket, p += 4); this._debug && this._debug(`Outbound: Sending CHANNEL_OPEN (r:${chan}, session)`); sendPacket(this, this._packetRW.write.finalize(packet)); } windowChange(chan, rows, cols, height, width) { if (this._server) throw new Error('Client-only method called in server mode'); // Does not consume window space let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 4 + 13 + 1 + 4 + 4 + 4 + 4 ); packet[p] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, 13, p += 4); packet.utf8Write('window-change', p += 4, 13); packet[p += 13] = 0; writeUInt32BE(packet, cols, ++p); writeUInt32BE(packet, rows, p += 4); writeUInt32BE(packet, width, p += 4); writeUInt32BE(packet, height, p += 4); this._debug && this._debug( `Outbound: Sending CHANNEL_REQUEST (r:${chan}, window-change)` ); sendPacket(this, this._packetRW.write.finalize(packet)); } pty(chan, rows, cols, height, width, term, modes, wantReply) { if (this._server) throw new Error('Client-only method called in server mode'); // Does not consume window space if (!term || !term.length) term = 'vt100'; if (modes && !Buffer.isBuffer(modes) && !Array.isArray(modes) && typeof modes === 'object' && modes !== null) { modes = modesToBytes(modes); } if (!modes || !modes.length) modes = NO_TERMINAL_MODES_BUFFER; const termLen = term.length; const modesLen = modes.length; let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 4 + 7 + 1 + 4 + termLen + 4 + 4 + 4 + 4 + 4 + modesLen ); packet[p] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, 7, p += 4); packet.utf8Write('pty-req', p += 4, 7); packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0); writeUInt32BE(packet, termLen, ++p); packet.utf8Write(term, p += 4, termLen); writeUInt32BE(packet, cols, p += termLen); writeUInt32BE(packet, rows, p += 4); writeUInt32BE(packet, width, p += 4); writeUInt32BE(packet, height, p += 4); writeUInt32BE(packet, modesLen, p += 4); p += 4; if (Array.isArray(modes)) { for (let i = 0; i < modesLen; ++i) packet[p++] = modes[i]; } else if (Buffer.isBuffer(modes)) { packet.set(modes, p); } this._debug && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, pty-req)`); sendPacket(this, this._packetRW.write.finalize(packet)); } shell(chan, wantReply) { if (this._server) throw new Error('Client-only method called in server mode'); // Does not consume window space let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 4 + 5 + 1); packet[p] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, 5, p += 4); packet.utf8Write('shell', p += 4, 5); packet[p += 5] = (wantReply === undefined || wantReply === true ? 1 : 0); this._debug && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, shell)`); sendPacket(this, this._packetRW.write.finalize(packet)); } exec(chan, cmd, wantReply) { if (this._server) throw new Error('Client-only method called in server mode'); // Does not consume window space const isBuf = Buffer.isBuffer(cmd); const cmdLen = (isBuf ? cmd.length : Buffer.byteLength(cmd)); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 1 + 4 + cmdLen); packet[p] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, 4, p += 4); packet.utf8Write('exec', p += 4, 4); packet[p += 4] = (wantReply === undefined || wantReply === true ? 1 : 0); writeUInt32BE(packet, cmdLen, ++p); if (isBuf) packet.set(cmd, p += 4); else packet.utf8Write(cmd, p += 4, cmdLen); this._debug && this._debug( `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exec: ${cmd})` ); sendPacket(this, this._packetRW.write.finalize(packet)); } signal(chan, signal) { if (this._server) throw new Error('Client-only method called in server mode'); // Does not consume window space const origSignal = signal; signal = signal.toUpperCase(); if (signal.slice(0, 3) === 'SIG') signal = signal.slice(3); if (SIGNALS[signal] !== 1) throw new Error(`Invalid signal: ${origSignal}`); const signalLen = signal.length; let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 4 + 6 + 1 + 4 + signalLen ); packet[p] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, 6, p += 4); packet.utf8Write('signal', p += 4, 6); packet[p += 6] = 0; writeUInt32BE(packet, signalLen, ++p); packet.utf8Write(signal, p += 4, signalLen); this._debug && this._debug( `Outbound: Sending CHANNEL_REQUEST (r:${chan}, signal: ${signal})` ); sendPacket(this, this._packetRW.write.finalize(packet)); } env(chan, key, val, wantReply) { if (this._server) throw new Error('Client-only method called in server mode'); // Does not consume window space const keyLen = Buffer.byteLength(key); const isBuf = Buffer.isBuffer(val); const valLen = (isBuf ? val.length : Buffer.byteLength(val)); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 4 + 3 + 1 + 4 + keyLen + 4 + valLen ); packet[p] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, 3, p += 4); packet.utf8Write('env', p += 4, 3); packet[p += 3] = (wantReply === undefined || wantReply === true ? 1 : 0); writeUInt32BE(packet, keyLen, ++p); packet.utf8Write(key, p += 4, keyLen); writeUInt32BE(packet, valLen, p += keyLen); if (isBuf) packet.set(val, p += 4); else packet.utf8Write(val, p += 4, valLen); this._debug && this._debug( `Outbound: Sending CHANNEL_REQUEST (r:${chan}, env: ${key}=${val})` ); sendPacket(this, this._packetRW.write.finalize(packet)); } x11Forward(chan, cfg, wantReply) { if (this._server) throw new Error('Client-only method called in server mode'); // Does not consume window space const protocol = cfg.protocol; const cookie = cfg.cookie; const isBufProto = Buffer.isBuffer(protocol); const protoLen = (isBufProto ? protocol.length : Buffer.byteLength(protocol)); const isBufCookie = Buffer.isBuffer(cookie); const cookieLen = (isBufCookie ? cookie.length : Buffer.byteLength(cookie)); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 4 + 7 + 1 + 1 + 4 + protoLen + 4 + cookieLen + 4 ); packet[p] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, 7, p += 4); packet.utf8Write('x11-req', p += 4, 7); packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0); packet[++p] = (cfg.single ? 1 : 0); writeUInt32BE(packet, protoLen, ++p); if (isBufProto) packet.set(protocol, p += 4); else packet.utf8Write(protocol, p += 4, protoLen); writeUInt32BE(packet, cookieLen, p += protoLen); if (isBufCookie) packet.set(cookie, p += 4); else packet.latin1Write(cookie, p += 4, cookieLen); writeUInt32BE(packet, (cfg.screen || 0), p += cookieLen); this._debug && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, x11-req)`); sendPacket(this, this._packetRW.write.finalize(packet)); } subsystem(chan, name, wantReply) { if (this._server) throw new Error('Client-only method called in server mode'); // Does not consume window space const nameLen = Buffer.byteLength(name); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 4 + 9 + 1 + 4 + nameLen); packet[p] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, 9, p += 4); packet.utf8Write('subsystem', p += 4, 9); packet[p += 9] = (wantReply === undefined || wantReply === true ? 1 : 0); writeUInt32BE(packet, nameLen, ++p); packet.utf8Write(name, p += 4, nameLen); this._debug && this._debug( `Outbound: Sending CHANNEL_REQUEST (r:${chan}, subsystem: ${name})` ); sendPacket(this, this._packetRW.write.finalize(packet)); } openssh_agentForward(chan, wantReply) { if (this._server) throw new Error('Client-only method called in server mode'); // Does not consume window space let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 4 + 26 + 1); packet[p] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, 26, p += 4); packet.utf8Write('auth-agent-req@openssh.com', p += 4, 26); packet[p += 26] = (wantReply === undefined || wantReply === true ? 1 : 0); if (this._debug) { this._debug( 'Outbound: Sending CHANNEL_REQUEST ' + `(r:${chan}, auth-agent-req@openssh.com)` ); } sendPacket(this, this._packetRW.write.finalize(packet)); } openssh_hostKeysProve(keys) { if (this._server) throw new Error('Client-only method called in server mode'); let keysTotal = 0; const publicKeys = []; for (const key of keys) { const publicKey = key.getPublicSSH(); keysTotal += 4 + publicKey.length; publicKeys.push(publicKey); } let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 29 + 1 + keysTotal); packet[p] = MESSAGE.GLOBAL_REQUEST; writeUInt32BE(packet, 29, ++p); packet.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29); packet[p += 29] = 1; // want reply ++p; for (const buf of publicKeys) { writeUInt32BE(packet, buf.length, p); bufferCopy(buf, packet, 0, buf.length, p += 4); p += buf.length; } if (this._debug) { this._debug( 'Outbound: Sending GLOBAL_REQUEST (hostkeys-prove-00@openssh.com)' ); } sendPacket(this, this._packetRW.write.finalize(packet)); } // =========================================================================== // Server-specific =========================================================== // =========================================================================== // Global // ------ serviceAccept(svcName) { if (!this._server) throw new Error('Server-only method called in client mode'); const svcNameLen = Buffer.byteLength(svcName); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + svcNameLen); packet[p] = MESSAGE.SERVICE_ACCEPT; writeUInt32BE(packet, svcNameLen, ++p); packet.utf8Write(svcName, p += 4, svcNameLen); this._debug && this._debug(`Outbound: Sending SERVICE_ACCEPT (${svcName})`); sendPacket(this, this._packetRW.write.finalize(packet)); if (this._server && this._banner && svcName === 'ssh-userauth') { const banner = this._banner; this._banner = undefined; // Prevent banner from being displayed again const bannerLen = Buffer.byteLength(banner); p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + bannerLen + 4); packet[p] = MESSAGE.USERAUTH_BANNER; writeUInt32BE(packet, bannerLen, ++p); packet.utf8Write(banner, p += 4, bannerLen); writeUInt32BE(packet, 0, p += bannerLen); // Empty language tag this._debug && this._debug('Outbound: Sending USERAUTH_BANNER'); sendPacket(this, this._packetRW.write.finalize(packet)); } } // 'ssh-connection' service-specific forwardedTcpip(chan, initWindow, maxPacket, cfg) { if (!this._server) throw new Error('Server-only method called in client mode'); const boundAddrLen = Buffer.byteLength(cfg.boundAddr); const remoteAddrLen = Buffer.byteLength(cfg.remoteAddr); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 15 + 4 + 4 + 4 + 4 + boundAddrLen + 4 + 4 + remoteAddrLen + 4 ); packet[p] = MESSAGE.CHANNEL_OPEN; writeUInt32BE(packet, 15, ++p); packet.utf8Write('forwarded-tcpip', p += 4, 15); writeUInt32BE(packet, chan, p += 15); writeUInt32BE(packet, initWindow, p += 4); writeUInt32BE(packet, maxPacket, p += 4); writeUInt32BE(packet, boundAddrLen, p += 4); packet.utf8Write(cfg.boundAddr, p += 4, boundAddrLen); writeUInt32BE(packet, cfg.boundPort, p += boundAddrLen); writeUInt32BE(packet, remoteAddrLen, p += 4); packet.utf8Write(cfg.remoteAddr, p += 4, remoteAddrLen); writeUInt32BE(packet, cfg.remotePort, p += remoteAddrLen); this._debug && this._debug( `Outbound: Sending CHANNEL_OPEN (r:${chan}, forwarded-tcpip)` ); sendPacket(this, this._packetRW.write.finalize(packet)); } x11(chan, initWindow, maxPacket, cfg) { if (!this._server) throw new Error('Server-only method called in client mode'); const addrLen = Buffer.byteLength(cfg.originAddr); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 3 + 4 + 4 + 4 + 4 + addrLen + 4 ); packet[p] = MESSAGE.CHANNEL_OPEN; writeUInt32BE(packet, 3, ++p); packet.utf8Write('x11', p += 4, 3); writeUInt32BE(packet, chan, p += 3); writeUInt32BE(packet, initWindow, p += 4); writeUInt32BE(packet, maxPacket, p += 4); writeUInt32BE(packet, addrLen, p += 4); packet.utf8Write(cfg.originAddr, p += 4, addrLen); writeUInt32BE(packet, cfg.originPort, p += addrLen); this._debug && this._debug( `Outbound: Sending CHANNEL_OPEN (r:${chan}, x11)` ); sendPacket(this, this._packetRW.write.finalize(packet)); } openssh_authAgent(chan, initWindow, maxPacket) { if (!this._server) throw new Error('Server-only method called in client mode'); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 22 + 4 + 4 + 4); packet[p] = MESSAGE.CHANNEL_OPEN; writeUInt32BE(packet, 22, ++p); packet.utf8Write('auth-agent@openssh.com', p += 4, 22); writeUInt32BE(packet, chan, p += 22); writeUInt32BE(packet, initWindow, p += 4); writeUInt32BE(packet, maxPacket, p += 4); this._debug && this._debug( `Outbound: Sending CHANNEL_OPEN (r:${chan}, auth-agent@openssh.com)` ); sendPacket(this, this._packetRW.write.finalize(packet)); } openssh_forwardedStreamLocal(chan, initWindow, maxPacket, cfg) { if (!this._server) throw new Error('Server-only method called in client mode'); const pathLen = Buffer.byteLength(cfg.socketPath); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 33 + 4 + 4 + 4 + 4 + pathLen + 4 ); packet[p] = MESSAGE.CHANNEL_OPEN; writeUInt32BE(packet, 33, ++p); packet.utf8Write('forwarded-streamlocal@openssh.com', p += 4, 33); writeUInt32BE(packet, chan, p += 33); writeUInt32BE(packet, initWindow, p += 4); writeUInt32BE(packet, maxPacket, p += 4); writeUInt32BE(packet, pathLen, p += 4); packet.utf8Write(cfg.socketPath, p += 4, pathLen); writeUInt32BE(packet, 0, p += pathLen); if (this._debug) { this._debug( 'Outbound: Sending CHANNEL_OPEN ' + `(r:${chan}, forwarded-streamlocal@openssh.com)` ); } sendPacket(this, this._packetRW.write.finalize(packet)); } exitStatus(chan, status) { if (!this._server) throw new Error('Server-only method called in client mode'); // Does not consume window space let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 4 + 11 + 1 + 4); packet[p] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, 11, p += 4); packet.utf8Write('exit-status', p += 4, 11); packet[p += 11] = 0; writeUInt32BE(packet, status, ++p); this._debug && this._debug( `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-status: ${status})` ); sendPacket(this, this._packetRW.write.finalize(packet)); } exitSignal(chan, name, coreDumped, msg) { if (!this._server) throw new Error('Server-only method called in client mode'); // Does not consume window space const origSignal = name; if (typeof origSignal !== 'string' || !origSignal) throw new Error(`Invalid signal: ${origSignal}`); let signal = name.toUpperCase(); if (signal.slice(0, 3) === 'SIG') signal = signal.slice(3); if (SIGNALS[signal] !== 1) throw new Error(`Invalid signal: ${origSignal}`); const nameLen = Buffer.byteLength(signal); const msgLen = (msg ? Buffer.byteLength(msg) : 0); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 4 + 11 + 1 + 4 + nameLen + 1 + 4 + msgLen + 4 ); packet[p] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, 11, p += 4); packet.utf8Write('exit-signal', p += 4, 11); packet[p += 11] = 0; writeUInt32BE(packet, nameLen, ++p); packet.utf8Write(signal, p += 4, nameLen); packet[p += nameLen] = (coreDumped ? 1 : 0); writeUInt32BE(packet, msgLen, ++p); p += 4; if (msgLen) { packet.utf8Write(msg, p, msgLen); p += msgLen; } writeUInt32BE(packet, 0, p); this._debug && this._debug( `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-signal: ${name})` ); sendPacket(this, this._packetRW.write.finalize(packet)); } // 'ssh-userauth' service-specific authFailure(authMethods, isPartial) { if (!this._server) throw new Error('Server-only method called in client mode'); if (this._authsQueue.length === 0) throw new Error('No auth in progress'); let methods; if (typeof authMethods === 'boolean') { isPartial = authMethods; authMethods = undefined; } if (authMethods) { methods = []; for (let i = 0; i < authMethods.length; ++i) { if (authMethods[i].toLowerCase() === 'none') continue; methods.push(authMethods[i]); } methods = methods.join(','); } else { methods = ''; } const methodsLen = methods.length; let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + methodsLen + 1); packet[p] = MESSAGE.USERAUTH_FAILURE; writeUInt32BE(packet, methodsLen, ++p); packet.utf8Write(methods, p += 4, methodsLen); packet[p += methodsLen] = (isPartial === true ? 1 : 0); this._authsQueue.shift(); this._debug && this._debug('Outbound: Sending USERAUTH_FAILURE'); sendPacket(this, this._packetRW.write.finalize(packet)); } authSuccess() { if (!this._server) throw new Error('Server-only method called in client mode'); if (this._authsQueue.length === 0) throw new Error('No auth in progress'); const p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1); packet[p] = MESSAGE.USERAUTH_SUCCESS; this._authsQueue.shift(); this._authenticated = true; this._debug && this._debug('Outbound: Sending USERAUTH_SUCCESS'); sendPacket(this, this._packetRW.write.finalize(packet)); if (this._kex.negotiated.cs.compress === 'zlib@openssh.com') this._packetRW.read = new ZlibPacketReader(); if (this._kex.negotiated.sc.compress === 'zlib@openssh.com') this._packetRW.write = new ZlibPacketWriter(this); } authPKOK(keyAlgo, key) { if (!this._server) throw new Error('Server-only method called in client mode'); if (this._authsQueue.length === 0 || this._authsQueue[0] !== 'publickey') throw new Error('"publickey" auth not in progress'); // TODO: support parsed key for `key` const keyAlgoLen = Buffer.byteLength(keyAlgo); const keyLen = key.length; let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + keyAlgoLen + 4 + keyLen); packet[p] = MESSAGE.USERAUTH_PK_OK; writeUInt32BE(packet, keyAlgoLen, ++p); packet.utf8Write(keyAlgo, p += 4, keyAlgoLen); writeUInt32BE(packet, keyLen, p += keyAlgoLen); packet.set(key, p += 4); this._authsQueue.shift(); this._debug && this._debug('Outbound: Sending USERAUTH_PK_OK'); sendPacket(this, this._packetRW.write.finalize(packet)); } authPasswdChg(prompt) { if (!this._server) throw new Error('Server-only method called in client mode'); const promptLen = Buffer.byteLength(prompt); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + promptLen + 4); packet[p] = MESSAGE.USERAUTH_PASSWD_CHANGEREQ; writeUInt32BE(packet, promptLen, ++p); packet.utf8Write(prompt, p += 4, promptLen); writeUInt32BE(packet, 0, p += promptLen); // Empty language tag this._debug && this._debug('Outbound: Sending USERAUTH_PASSWD_CHANGEREQ'); sendPacket(this, this._packetRW.write.finalize(packet)); } authInfoReq(name, instructions, prompts) { if (!this._server) throw new Error('Server-only method called in client mode'); let promptsLen = 0; const nameLen = name ? Buffer.byteLength(name) : 0; const instrLen = instructions ? Buffer.byteLength(instructions) : 0; for (let i = 0; i < prompts.length; ++i) promptsLen += 4 + Buffer.byteLength(prompts[i].prompt) + 1; let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + nameLen + 4 + instrLen + 4 + 4 + promptsLen ); packet[p] = MESSAGE.USERAUTH_INFO_REQUEST; writeUInt32BE(packet, nameLen, ++p); p += 4; if (name) { packet.utf8Write(name, p, nameLen); p += nameLen; } writeUInt32BE(packet, instrLen, p); p += 4; if (instructions) { packet.utf8Write(instructions, p, instrLen); p += instrLen; } writeUInt32BE(packet, 0, p); writeUInt32BE(packet, prompts.length, p += 4); p += 4; for (let i = 0; i < prompts.length; ++i) { const prompt = prompts[i]; const promptLen = Buffer.byteLength(prompt.prompt); writeUInt32BE(packet, promptLen, p); p += 4; if (promptLen) { packet.utf8Write(prompt.prompt, p, promptLen); p += promptLen; } packet[p++] = (prompt.echo ? 1 : 0); } this._debug && this._debug('Outbound: Sending USERAUTH_INFO_REQUEST'); sendPacket(this, this._packetRW.write.finalize(packet)); } } // SSH-protoversion-softwareversion (SP comments) CR LF const RE_IDENT = /^SSH-(2\.0|1\.99)-([^ ]+)(?: (.*))?$/; // TODO: optimize this by starting n bytes from the end of this._buffer instead // of the beginning function parseHeader(chunk, p, len) { let data; let chunkOffset; if (this._buffer) { data = Buffer.allocUnsafe(this._buffer.length + (len - p)); data.set(this._buffer, 0); if (p === 0) { data.set(chunk, this._buffer.length); } else { data.set(new Uint8Array(chunk.buffer, chunk.byteOffset + p, (len - p)), this._buffer.length); } chunkOffset = this._buffer.length; p = 0; } else { data = chunk; chunkOffset = 0; } const op = p; let start = p; let end = p; let needNL = false; let lineLen = 0; let lines = 0; for (; p < data.length; ++p) { const ch = data[p]; if (ch === 13 /* '\r' */) { needNL = true; continue; } if (ch === 10 /* '\n' */) { if (end > start && end - start > 4 && data[start] === 83 /* 'S' */ && data[start + 1] === 83 /* 'S' */ && data[start + 2] === 72 /* 'H' */ && data[start + 3] === 45 /* '-' */) { const full = data.latin1Slice(op, end + 1); const identRaw = (start === op ? full : full.slice(start - op)); const m = RE_IDENT.exec(identRaw); if (!m) throw new Error('Invalid identification string'); const header = { greeting: (start === op ? '' : full.slice(0, start - op)), identRaw, versions: { protocol: m[1], software: m[2], }, comments: m[3] }; // Needed during handshake this._remoteIdentRaw = Buffer.from(identRaw); this._debug && this._debug(`Remote ident: ${inspect(identRaw)}`); this._compatFlags = getCompatFlags(header); this._buffer = undefined; this._decipher = new NullDecipher(0, onKEXPayload.bind(this, { firstPacket: true })); this._parse = parsePacket; this._onHeader(header); if (!this._destruct) { // We disconnected inside _onHeader return len; } kexinit(this); return p + 1 - chunkOffset; } // Only allow pre-ident greetings when we're a client if (this._server) throw new Error('Greetings from clients not permitted'); if (++lines > MAX_LINES) throw new Error('Max greeting lines exceeded'); needNL = false; start = p + 1; lineLen = 0; } else if (needNL) { throw new Error('Invalid header: expected newline'); } else if (++lineLen >= MAX_LINE_LEN) { throw new Error('Header line too long'); } end = p; } if (!this._buffer) this._buffer = bufferSlice(data, op); return p - chunkOffset; } function parsePacket(chunk, p, len) { return this._decipher.decrypt(chunk, p, len); } function onPayload(payload) { // XXX: move this to the Decipher implementations? this._onPacket(); if (payload.length === 0) { this._debug && this._debug('Inbound: Skipping empty packet payload'); return; } payload = this._packetRW.read.read(payload); const type = payload[0]; if (type === MESSAGE.USERAUTH_SUCCESS && !this._server && !this._authenticated) { this._authenticated = true; if (this._kex.negotiated.cs.compress === 'zlib@openssh.com') this._packetRW.write = new ZlibPacketWriter(this); if (this._kex.negotiated.sc.compress === 'zlib@openssh.com') this._packetRW.read = new ZlibPacketReader(); } const handler = MESSAGE_HANDLERS[type]; if (handler === undefined) { this._debug && this._debug(`Inbound: Unsupported message type: ${type}`); return; } return handler(this, payload); } function getCompatFlags(header) { const software = header.versions.software; let flags = 0; for (const rule of COMPAT_CHECKS) { if (typeof rule[0] === 'string') { if (software === rule[0]) flags |= rule[1]; } else if (rule[0].test(software)) { flags |= rule[1]; } } return flags; } function modesToBytes(modes) { const keys = Object.keys(modes); const bytes = Buffer.allocUnsafe((5 * keys.length) + 1); let b = 0; for (let i = 0; i < keys.length; ++i) { const key = keys[i]; if (key === 'TTY_OP_END') continue; const opcode = TERMINAL_MODE[key]; if (opcode === undefined) continue; const val = modes[key]; if (typeof val === 'number' && isFinite(val)) { bytes[b++] = opcode; bytes[b++] = val >>> 24; bytes[b++] = val >>> 16; bytes[b++] = val >>> 8; bytes[b++] = val; } } bytes[b++] = TERMINAL_MODE.TTY_OP_END; if (b < bytes.length) return bufferSlice(bytes, 0, b); return bytes; } function sendExtInfo(proto) { let serverSigAlgs = 'ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521' + 'rsa-sha2-512,rsa-sha2-256,ssh-rsa,ssh-dss'; if (eddsaSupported) serverSigAlgs = `ssh-ed25519,${serverSigAlgs}`; const algsLen = Buffer.byteLength(serverSigAlgs); let p = proto._packetRW.write.allocStart; const packet = proto._packetRW.write.alloc(1 + 4 + 4 + 15 + 4 + algsLen); packet[p] = MESSAGE.EXT_INFO; writeUInt32BE(packet, 1, ++p); writeUInt32BE(packet, 15, p += 4); packet.utf8Write('server-sig-algs', p += 4, 15); writeUInt32BE(packet, algsLen, p += 15); packet.utf8Write(serverSigAlgs, p += 4, algsLen); proto._debug && proto._debug('Outbound: Sending EXT_INFO'); sendPacket(proto, proto._packetRW.write.finalize(packet)); } module.exports = Protocol; /***/ }), /***/ 64061: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const EventEmitter = __webpack_require__(82361); const fs = __webpack_require__(57147); const { constants } = fs; const { Readable: ReadableStream, Writable: WritableStream } = __webpack_require__(12781); const { inherits, isDate } = __webpack_require__(73837); const FastBuffer = Buffer[Symbol.species]; const { bufferCopy, bufferSlice, makeBufferParser, writeUInt32BE, } = __webpack_require__(39205); const ATTR = { SIZE: 0x00000001, UIDGID: 0x00000002, PERMISSIONS: 0x00000004, ACMODTIME: 0x00000008, EXTENDED: 0x80000000, }; // Large enough to store all possible attributes const ATTRS_BUF = Buffer.alloc(28); const STATUS_CODE = { OK: 0, EOF: 1, NO_SUCH_FILE: 2, PERMISSION_DENIED: 3, FAILURE: 4, BAD_MESSAGE: 5, NO_CONNECTION: 6, CONNECTION_LOST: 7, OP_UNSUPPORTED: 8 }; const VALID_STATUS_CODES = new Map( Object.values(STATUS_CODE).map((n) => [n, 1]) ); const STATUS_CODE_STR = { [STATUS_CODE.OK]: 'No error', [STATUS_CODE.EOF]: 'End of file', [STATUS_CODE.NO_SUCH_FILE]: 'No such file or directory', [STATUS_CODE.PERMISSION_DENIED]: 'Permission denied', [STATUS_CODE.FAILURE]: 'Failure', [STATUS_CODE.BAD_MESSAGE]: 'Bad message', [STATUS_CODE.NO_CONNECTION]: 'No connection', [STATUS_CODE.CONNECTION_LOST]: 'Connection lost', [STATUS_CODE.OP_UNSUPPORTED]: 'Operation unsupported', }; const REQUEST = { INIT: 1, OPEN: 3, CLOSE: 4, READ: 5, WRITE: 6, LSTAT: 7, FSTAT: 8, SETSTAT: 9, FSETSTAT: 10, OPENDIR: 11, READDIR: 12, REMOVE: 13, MKDIR: 14, RMDIR: 15, REALPATH: 16, STAT: 17, RENAME: 18, READLINK: 19, SYMLINK: 20, EXTENDED: 200 }; const RESPONSE = { VERSION: 2, STATUS: 101, HANDLE: 102, DATA: 103, NAME: 104, ATTRS: 105, EXTENDED: 201 }; const OPEN_MODE = { READ: 0x00000001, WRITE: 0x00000002, APPEND: 0x00000004, CREAT: 0x00000008, TRUNC: 0x00000010, EXCL: 0x00000020 }; const PKT_RW_OVERHEAD = 2 * 1024; const MAX_REQID = 2 ** 32 - 1; const CLIENT_VERSION_BUFFER = Buffer.from([ 0, 0, 0, 5 /* length */, REQUEST.INIT, 0, 0, 0, 3 /* version */ ]); const SERVER_VERSION_BUFFER = Buffer.from([ 0, 0, 0, 5 /* length */, RESPONSE.VERSION, 0, 0, 0, 3 /* version */ ]); const RE_OPENSSH = /^SSH-2.0-(?:OpenSSH|dropbear)/; const OPENSSH_MAX_PKT_LEN = 256 * 1024; const bufferParser = makeBufferParser(); const fakeStderr = { readable: false, writable: false, push: (data) => {}, once: () => {}, on: () => {}, emit: () => {}, end: () => {}, }; function noop() {} // Emulates enough of `Channel` to be able to be used as a drop-in replacement // in order to process incoming data with as little overhead as possible class SFTP extends EventEmitter { constructor(client, chanInfo, cfg) { super(); if (typeof cfg !== 'object' || !cfg) cfg = {}; const remoteIdentRaw = client._protocol._remoteIdentRaw; this.server = !!cfg.server; this._debug = (typeof cfg.debug === 'function' ? cfg.debug : undefined); this._isOpenSSH = (remoteIdentRaw && RE_OPENSSH.test(remoteIdentRaw)); this._version = -1; this._extensions = {}; this._biOpt = cfg.biOpt; this._pktLenBytes = 0; this._pktLen = 0; this._pktPos = 0; this._pktType = 0; this._pktData = undefined; this._writeReqid = -1; this._requests = {}; this._maxInPktLen = OPENSSH_MAX_PKT_LEN; this._maxOutPktLen = 34000; this._maxReadLen = (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD; this._maxWriteLen = (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD; this.maxOpenHandles = undefined; // Channel compatibility this._client = client; this._protocol = client._protocol; this._callbacks = []; this._hasX11 = false; this._exit = { code: undefined, signal: undefined, dump: undefined, desc: undefined, }; this._waitWindow = false; // SSH-level backpressure this._chunkcb = undefined; this._buffer = []; this.type = chanInfo.type; this.subtype = undefined; this.incoming = chanInfo.incoming; this.outgoing = chanInfo.outgoing; this.stderr = fakeStderr; this.readable = true; } // This handles incoming data to parse push(data) { if (data === null) { cleanupRequests(this); if (!this.readable) return; // No more incoming data from the remote side this.readable = false; this.emit('end'); return; } /* uint32 length byte type byte[length - 1] data payload */ let p = 0; while (p < data.length) { if (this._pktLenBytes < 4) { let nb = Math.min(4 - this._pktLenBytes, data.length - p); this._pktLenBytes += nb; while (nb--) this._pktLen = (this._pktLen << 8) + data[p++]; if (this._pktLenBytes < 4) return; if (this._pktLen === 0) return doFatalSFTPError(this, 'Invalid packet length'); if (this._pktLen > this._maxInPktLen) { const max = this._maxInPktLen; return doFatalSFTPError( this, `Packet length ${this._pktLen} exceeds max length of ${max}` ); } if (p >= data.length) return; } if (this._pktPos < this._pktLen) { const nb = Math.min(this._pktLen - this._pktPos, data.length - p); if (p !== 0 || nb !== data.length) { if (nb === this._pktLen) { this._pkt = new FastBuffer(data.buffer, data.byteOffset + p, nb); } else { if (!this._pkt) this._pkt = Buffer.allocUnsafe(this._pktLen); this._pkt.set( new Uint8Array(data.buffer, data.byteOffset + p, nb), this._pktPos ); } } else if (nb === this._pktLen) { this._pkt = data; } else { if (!this._pkt) this._pkt = Buffer.allocUnsafe(this._pktLen); this._pkt.set(data, this._pktPos); } p += nb; this._pktPos += nb; if (this._pktPos < this._pktLen) return; } const type = this._pkt[0]; const payload = this._pkt; // Prepare for next packet this._pktLen = 0; this._pktLenBytes = 0; this._pkt = undefined; this._pktPos = 0; const handler = (this.server ? SERVER_HANDLERS[type] : CLIENT_HANDLERS[type]); if (!handler) return doFatalSFTPError(this, `Unknown packet type ${type}`); if (this._version === -1) { if (this.server) { if (type !== REQUEST.INIT) return doFatalSFTPError(this, `Expected INIT packet, got ${type}`); } else if (type !== RESPONSE.VERSION) { return doFatalSFTPError(this, `Expected VERSION packet, got ${type}`); } } if (handler(this, payload) === false) return; } } end() { this.destroy(); } destroy() { if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') { this.outgoing.state = 'closing'; this._protocol.channelClose(this.outgoing.id); } } _init() { this._init = noop; if (!this.server) sendOrBuffer(this, CLIENT_VERSION_BUFFER); } // =========================================================================== // Client-specific =========================================================== // =========================================================================== createReadStream(path, options) { if (this.server) throw new Error('Client-only method called in server mode'); return new ReadStream(this, path, options); } createWriteStream(path, options) { if (this.server) throw new Error('Client-only method called in server mode'); return new WriteStream(this, path, options); } open(path, flags_, attrs, cb) { if (this.server) throw new Error('Client-only method called in server mode'); if (typeof attrs === 'function') { cb = attrs; attrs = undefined; } const flags = (typeof flags_ === 'number' ? flags_ : stringToFlags(flags_)); if (flags === null) throw new Error(`Unknown flags string: ${flags_}`); let attrsFlags = 0; let attrsLen = 0; if (typeof attrs === 'string' || typeof attrs === 'number') attrs = { mode: attrs }; if (typeof attrs === 'object' && attrs !== null) { attrs = attrsToBytes(attrs); attrsFlags = attrs.flags; attrsLen = attrs.nb; } /* uint32 id string filename uint32 pflags ATTRS attrs */ const pathLen = Buffer.byteLength(path); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + 4 + attrsLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.OPEN; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathLen, p); buf.utf8Write(path, p += 4, pathLen); writeUInt32BE(buf, flags, p += pathLen); writeUInt32BE(buf, attrsFlags, p += 4); if (attrsLen) { p += 4; if (attrsLen === ATTRS_BUF.length) buf.set(ATTRS_BUF, p); else bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); p += attrsLen; } this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPEN` ); } close(handle, cb) { if (this.server) throw new Error('Client-only method called in server mode'); if (!Buffer.isBuffer(handle)) throw new Error('handle is not a Buffer'); /* uint32 id string handle */ const handleLen = handle.length; let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.CLOSE; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, handleLen, p); buf.set(handle, p += 4); this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} CLOSE` ); } read(handle, buf, off, len, position, cb) { if (this.server) throw new Error('Client-only method called in server mode'); if (!Buffer.isBuffer(handle)) throw new Error('handle is not a Buffer'); if (!Buffer.isBuffer(buf)) throw new Error('buffer is not a Buffer'); if (off >= buf.length) throw new Error('offset is out of bounds'); if (off + len > buf.length) throw new Error('length extends beyond buffer'); if (position === null) throw new Error('null position currently unsupported'); read_(this, handle, buf, off, len, position, cb); } readData(handle, buf, off, len, position, cb) { // Backwards compatibility this.read(handle, buf, off, len, position, cb); } write(handle, buf, off, len, position, cb) { if (this.server) throw new Error('Client-only method called in server mode'); if (!Buffer.isBuffer(handle)) throw new Error('handle is not a Buffer'); if (!Buffer.isBuffer(buf)) throw new Error('buffer is not a Buffer'); if (off > buf.length) throw new Error('offset is out of bounds'); if (off + len > buf.length) throw new Error('length extends beyond buffer'); if (position === null) throw new Error('null position currently unsupported'); if (!len) { cb && process.nextTick(cb, undefined, 0); return; } const maxDataLen = this._maxWriteLen; const overflow = Math.max(len - maxDataLen, 0); const origPosition = position; if (overflow) len = maxDataLen; /* uint32 id string handle uint64 offset string data */ const handleLen = handle.length; let p = 9; const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4 + len); writeUInt32BE(out, out.length - 4, 0); out[4] = REQUEST.WRITE; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(out, reqid, 5); writeUInt32BE(out, handleLen, p); out.set(handle, p += 4); p += handleLen; for (let i = 7; i >= 0; --i) { out[p + i] = position & 0xFF; position /= 256; } writeUInt32BE(out, len, p += 8); bufferCopy(buf, out, off, off + len, p += 4); this._requests[reqid] = { cb: (err) => { if (err) { if (typeof cb === 'function') cb(err); } else if (overflow) { this.write(handle, buf, off + len, overflow, origPosition + len, cb); } else if (typeof cb === 'function') { cb(undefined, off + len); } } }; const isSent = sendOrBuffer(this, out); if (this._debug) { const how = (isSent ? 'Sent' : 'Buffered'); this._debug(`SFTP: Outbound: ${how} WRITE (id:${reqid})`); } } writeData(handle, buf, off, len, position, cb) { // Backwards compatibility this.write(handle, buf, off, len, position, cb); } fastGet(remotePath, localPath, opts, cb) { if (this.server) throw new Error('Client-only method called in server mode'); fastXfer(this, fs, remotePath, localPath, opts, cb); } fastPut(localPath, remotePath, opts, cb) { if (this.server) throw new Error('Client-only method called in server mode'); fastXfer(fs, this, localPath, remotePath, opts, cb); } readFile(path, options, callback_) { if (this.server) throw new Error('Client-only method called in server mode'); let callback; if (typeof callback_ === 'function') { callback = callback_; } else if (typeof options === 'function') { callback = options; options = undefined; } if (typeof options === 'string') options = { encoding: options, flag: 'r' }; else if (!options) options = { encoding: null, flag: 'r' }; else if (typeof options !== 'object') throw new TypeError('Bad arguments'); const encoding = options.encoding; if (encoding && !Buffer.isEncoding(encoding)) throw new Error(`Unknown encoding: ${encoding}`); // First stat the file, so we know the size. let size; let buffer; // Single buffer with file data let buffers; // List for when size is unknown let pos = 0; let handle; // SFTPv3 does not support using -1 for read position, so we have to track // read position manually let bytesRead = 0; const flag = options.flag || 'r'; const read = () => { if (size === 0) { buffer = Buffer.allocUnsafe(8192); this.read(handle, buffer, 0, 8192, bytesRead, afterRead); } else { this.read(handle, buffer, pos, size - pos, bytesRead, afterRead); } }; const afterRead = (er, nbytes) => { let eof; if (er) { eof = (er.code === STATUS_CODE.EOF); if (!eof) { return this.close(handle, () => { return callback && callback(er); }); } } else { eof = false; } if (eof || (size === 0 && nbytes === 0)) return close(); bytesRead += nbytes; pos += nbytes; if (size !== 0) { if (pos === size) close(); else read(); } else { // Unknown size, just read until we don't get bytes. buffers.push(bufferSlice(buffer, 0, nbytes)); read(); } }; afterRead._wantEOFError = true; const close = () => { this.close(handle, (er) => { if (size === 0) { // Collect the data into the buffers list. buffer = Buffer.concat(buffers, pos); } else if (pos < size) { buffer = bufferSlice(buffer, 0, pos); } if (encoding) buffer = buffer.toString(encoding); return callback && callback(er, buffer); }); }; this.open(path, flag, 0o666, (er, handle_) => { if (er) return callback && callback(er); handle = handle_; const tryStat = (er, st) => { if (er) { // Try stat() for sftp servers that may not support fstat() for // whatever reason this.stat(path, (er_, st_) => { if (er_) { return this.close(handle, () => { callback && callback(er); }); } tryStat(null, st_); }); return; } size = st.size || 0; if (size === 0) { // The kernel lies about many files. // Go ahead and try to read some bytes. buffers = []; return read(); } buffer = Buffer.allocUnsafe(size); read(); }; this.fstat(handle, tryStat); }); } writeFile(path, data, options, callback_) { if (this.server) throw new Error('Client-only method called in server mode'); let callback; if (typeof callback_ === 'function') { callback = callback_; } else if (typeof options === 'function') { callback = options; options = undefined; } if (typeof options === 'string') options = { encoding: options, mode: 0o666, flag: 'w' }; else if (!options) options = { encoding: 'utf8', mode: 0o666, flag: 'w' }; else if (typeof options !== 'object') throw new TypeError('Bad arguments'); if (options.encoding && !Buffer.isEncoding(options.encoding)) throw new Error(`Unknown encoding: ${options.encoding}`); const flag = options.flag || 'w'; this.open(path, flag, options.mode, (openErr, handle) => { if (openErr) { callback && callback(openErr); } else { const buffer = (Buffer.isBuffer(data) ? data : Buffer.from('' + data, options.encoding || 'utf8')); const position = (/a/.test(flag) ? null : 0); // SFTPv3 does not support the notion of 'current position' // (null position), so we just attempt to append to the end of the file // instead if (position === null) { const tryStat = (er, st) => { if (er) { // Try stat() for sftp servers that may not support fstat() for // whatever reason this.stat(path, (er_, st_) => { if (er_) { return this.close(handle, () => { callback && callback(er); }); } tryStat(null, st_); }); return; } writeAll(this, handle, buffer, 0, buffer.length, st.size, callback); }; this.fstat(handle, tryStat); return; } writeAll(this, handle, buffer, 0, buffer.length, position, callback); } }); } appendFile(path, data, options, callback_) { if (this.server) throw new Error('Client-only method called in server mode'); let callback; if (typeof callback_ === 'function') { callback = callback_; } else if (typeof options === 'function') { callback = options; options = undefined; } if (typeof options === 'string') options = { encoding: options, mode: 0o666, flag: 'a' }; else if (!options) options = { encoding: 'utf8', mode: 0o666, flag: 'a' }; else if (typeof options !== 'object') throw new TypeError('Bad arguments'); if (!options.flag) options = Object.assign({ flag: 'a' }, options); this.writeFile(path, data, options, callback); } exists(path, cb) { if (this.server) throw new Error('Client-only method called in server mode'); this.stat(path, (err) => { cb && cb(err ? false : true); }); } unlink(filename, cb) { if (this.server) throw new Error('Client-only method called in server mode'); /* uint32 id string filename */ const fnameLen = Buffer.byteLength(filename); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + fnameLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.REMOVE; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, fnameLen, p); buf.utf8Write(filename, p += 4, fnameLen); this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REMOVE` ); } rename(oldPath, newPath, cb) { if (this.server) throw new Error('Client-only method called in server mode'); /* uint32 id string oldpath string newpath */ const oldLen = Buffer.byteLength(oldPath); const newLen = Buffer.byteLength(newPath); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + oldLen + 4 + newLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.RENAME; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, oldLen, p); buf.utf8Write(oldPath, p += 4, oldLen); writeUInt32BE(buf, newLen, p += oldLen); buf.utf8Write(newPath, p += 4, newLen); this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RENAME` ); } mkdir(path, attrs, cb) { if (this.server) throw new Error('Client-only method called in server mode'); let flags = 0; let attrsLen = 0; if (typeof attrs === 'function') { cb = attrs; attrs = undefined; } if (typeof attrs === 'object' && attrs !== null) { attrs = attrsToBytes(attrs); flags = attrs.flags; attrsLen = attrs.nb; } /* uint32 id string path ATTRS attrs */ const pathLen = Buffer.byteLength(path); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.MKDIR; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathLen, p); buf.utf8Write(path, p += 4, pathLen); writeUInt32BE(buf, flags, p += pathLen); if (attrsLen) { p += 4; if (attrsLen === ATTRS_BUF.length) buf.set(ATTRS_BUF, p); else bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); p += attrsLen; } this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} MKDIR` ); } rmdir(path, cb) { if (this.server) throw new Error('Client-only method called in server mode'); /* uint32 id string path */ const pathLen = Buffer.byteLength(path); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.RMDIR; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathLen, p); buf.utf8Write(path, p += 4, pathLen); this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RMDIR` ); } readdir(where, opts, cb) { if (this.server) throw new Error('Client-only method called in server mode'); if (typeof opts === 'function') { cb = opts; opts = {}; } if (typeof opts !== 'object' || opts === null) opts = {}; const doFilter = (opts && opts.full ? false : true); if (!Buffer.isBuffer(where) && typeof where !== 'string') throw new Error('missing directory handle or path'); if (typeof where === 'string') { const entries = []; let e = 0; const reread = (err, handle) => { if (err) return cb(err); this.readdir(handle, opts, (err, list) => { const eof = (err && err.code === STATUS_CODE.EOF); if (err && !eof) return this.close(handle, () => cb(err)); if (eof) { return this.close(handle, (err) => { if (err) return cb(err); cb(undefined, entries); }); } for (let i = 0; i < list.length; ++i, ++e) entries[e] = list[i]; reread(undefined, handle); }); }; return this.opendir(where, reread); } /* uint32 id string handle */ const handleLen = where.length; let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.READDIR; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, handleLen, p); buf.set(where, p += 4); this._requests[reqid] = { cb: (doFilter ? (err, list) => { if (typeof cb !== 'function') return; if (err) return cb(err); for (let i = list.length - 1; i >= 0; --i) { if (list[i].filename === '.' || list[i].filename === '..') list.splice(i, 1); } cb(undefined, list); } : cb) }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READDIR` ); } fstat(handle, cb) { if (this.server) throw new Error('Client-only method called in server mode'); if (!Buffer.isBuffer(handle)) throw new Error('handle is not a Buffer'); /* uint32 id string handle */ const handleLen = handle.length; let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.FSTAT; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, handleLen, p); buf.set(handle, p += 4); this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSTAT` ); } stat(path, cb) { if (this.server) throw new Error('Client-only method called in server mode'); /* uint32 id string path */ const pathLen = Buffer.byteLength(path); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.STAT; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathLen, p); buf.utf8Write(path, p += 4, pathLen); this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STAT` ); } lstat(path, cb) { if (this.server) throw new Error('Client-only method called in server mode'); /* uint32 id string path */ const pathLen = Buffer.byteLength(path); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.LSTAT; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathLen, p); buf.utf8Write(path, p += 4, pathLen); this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} LSTAT` ); } opendir(path, cb) { if (this.server) throw new Error('Client-only method called in server mode'); /* uint32 id string path */ const pathLen = Buffer.byteLength(path); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.OPENDIR; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathLen, p); buf.utf8Write(path, p += 4, pathLen); this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPENDIR` ); } setstat(path, attrs, cb) { if (this.server) throw new Error('Client-only method called in server mode'); let flags = 0; let attrsLen = 0; if (typeof attrs === 'object' && attrs !== null) { attrs = attrsToBytes(attrs); flags = attrs.flags; attrsLen = attrs.nb; } else if (typeof attrs === 'function') { cb = attrs; } /* uint32 id string path ATTRS attrs */ const pathLen = Buffer.byteLength(path); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.SETSTAT; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathLen, p); buf.utf8Write(path, p += 4, pathLen); writeUInt32BE(buf, flags, p += pathLen); if (attrsLen) { p += 4; if (attrsLen === ATTRS_BUF.length) buf.set(ATTRS_BUF, p); else bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); p += attrsLen; } this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SETSTAT` ); } fsetstat(handle, attrs, cb) { if (this.server) throw new Error('Client-only method called in server mode'); if (!Buffer.isBuffer(handle)) throw new Error('handle is not a Buffer'); let flags = 0; let attrsLen = 0; if (typeof attrs === 'object' && attrs !== null) { attrs = attrsToBytes(attrs); flags = attrs.flags; attrsLen = attrs.nb; } else if (typeof attrs === 'function') { cb = attrs; } /* uint32 id string handle ATTRS attrs */ const handleLen = handle.length; let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 4 + attrsLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.FSETSTAT; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, handleLen, p); buf.set(handle, p += 4); writeUInt32BE(buf, flags, p += handleLen); if (attrsLen) { p += 4; if (attrsLen === ATTRS_BUF.length) buf.set(ATTRS_BUF, p); else bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); p += attrsLen; } this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSETSTAT` ); } futimes(handle, atime, mtime, cb) { return this.fsetstat(handle, { atime: toUnixTimestamp(atime), mtime: toUnixTimestamp(mtime) }, cb); } utimes(path, atime, mtime, cb) { return this.setstat(path, { atime: toUnixTimestamp(atime), mtime: toUnixTimestamp(mtime) }, cb); } fchown(handle, uid, gid, cb) { return this.fsetstat(handle, { uid: uid, gid: gid }, cb); } chown(path, uid, gid, cb) { return this.setstat(path, { uid: uid, gid: gid }, cb); } fchmod(handle, mode, cb) { return this.fsetstat(handle, { mode: mode }, cb); } chmod(path, mode, cb) { return this.setstat(path, { mode: mode }, cb); } readlink(path, cb) { if (this.server) throw new Error('Client-only method called in server mode'); /* uint32 id string path */ const pathLen = Buffer.byteLength(path); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.READLINK; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathLen, p); buf.utf8Write(path, p += 4, pathLen); this._requests[reqid] = { cb: (err, names) => { if (typeof cb !== 'function') return; if (err) return cb(err); if (!names || !names.length) return cb(new Error('Response missing link info')); cb(undefined, names[0].filename); } }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READLINK` ); } symlink(targetPath, linkPath, cb) { if (this.server) throw new Error('Client-only method called in server mode'); /* uint32 id string linkpath string targetpath */ const linkLen = Buffer.byteLength(linkPath); const targetLen = Buffer.byteLength(targetPath); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + linkLen + 4 + targetLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.SYMLINK; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); if (this._isOpenSSH) { // OpenSSH has linkpath and targetpath positions switched writeUInt32BE(buf, targetLen, p); buf.utf8Write(targetPath, p += 4, targetLen); writeUInt32BE(buf, linkLen, p += targetLen); buf.utf8Write(linkPath, p += 4, linkLen); } else { writeUInt32BE(buf, linkLen, p); buf.utf8Write(linkPath, p += 4, linkLen); writeUInt32BE(buf, targetLen, p += linkLen); buf.utf8Write(targetPath, p += 4, targetLen); } this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SYMLINK` ); } realpath(path, cb) { if (this.server) throw new Error('Client-only method called in server mode'); /* uint32 id string path */ const pathLen = Buffer.byteLength(path); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.REALPATH; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathLen, p); buf.utf8Write(path, p += 4, pathLen); this._requests[reqid] = { cb: (err, names) => { if (typeof cb !== 'function') return; if (err) return cb(err); if (!names || !names.length) return cb(new Error('Response missing path info')); cb(undefined, names[0].filename); } }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REALPATH` ); } // extended requests ext_openssh_rename(oldPath, newPath, cb) { if (this.server) throw new Error('Client-only method called in server mode'); const ext = this._extensions['posix-rename@openssh.com']; if (!ext || ext !== '1') throw new Error('Server does not support this extended request'); /* uint32 id string "posix-rename@openssh.com" string oldpath string newpath */ const oldLen = Buffer.byteLength(oldPath); const newLen = Buffer.byteLength(newPath); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 24 + 4 + oldLen + 4 + newLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.EXTENDED; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, 24, p); buf.utf8Write('posix-rename@openssh.com', p += 4, 24); writeUInt32BE(buf, oldLen, p += 24); buf.utf8Write(oldPath, p += 4, oldLen); writeUInt32BE(buf, newLen, p += oldLen); buf.utf8Write(newPath, p += 4, newLen); this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); if (this._debug) { const which = (isBuffered ? 'Buffered' : 'Sending'); this._debug(`SFTP: Outbound: ${which} posix-rename@openssh.com`); } } ext_openssh_statvfs(path, cb) { if (this.server) throw new Error('Client-only method called in server mode'); const ext = this._extensions['statvfs@openssh.com']; if (!ext || ext !== '2') throw new Error('Server does not support this extended request'); /* uint32 id string "statvfs@openssh.com" string path */ const pathLen = Buffer.byteLength(path); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 19 + 4 + pathLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.EXTENDED; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, 19, p); buf.utf8Write('statvfs@openssh.com', p += 4, 19); writeUInt32BE(buf, pathLen, p += 19); buf.utf8Write(path, p += 4, pathLen); this._requests[reqid] = { extended: 'statvfs@openssh.com', cb }; const isBuffered = sendOrBuffer(this, buf); if (this._debug) { const which = (isBuffered ? 'Buffered' : 'Sending'); this._debug(`SFTP: Outbound: ${which} statvfs@openssh.com`); } } ext_openssh_fstatvfs(handle, cb) { if (this.server) throw new Error('Client-only method called in server mode'); const ext = this._extensions['fstatvfs@openssh.com']; if (!ext || ext !== '2') throw new Error('Server does not support this extended request'); if (!Buffer.isBuffer(handle)) throw new Error('handle is not a Buffer'); /* uint32 id string "fstatvfs@openssh.com" string handle */ const handleLen = handle.length; let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + handleLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.EXTENDED; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, 20, p); buf.utf8Write('fstatvfs@openssh.com', p += 4, 20); writeUInt32BE(buf, handleLen, p += 20); buf.set(handle, p += 4); this._requests[reqid] = { extended: 'fstatvfs@openssh.com', cb }; const isBuffered = sendOrBuffer(this, buf); if (this._debug) { const which = (isBuffered ? 'Buffered' : 'Sending'); this._debug(`SFTP: Outbound: ${which} fstatvfs@openssh.com`); } } ext_openssh_hardlink(oldPath, newPath, cb) { if (this.server) throw new Error('Client-only method called in server mode'); const ext = this._extensions['hardlink@openssh.com']; if (ext !== '1') throw new Error('Server does not support this extended request'); /* uint32 id string "hardlink@openssh.com" string oldpath string newpath */ const oldLen = Buffer.byteLength(oldPath); const newLen = Buffer.byteLength(newPath); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + oldLen + 4 + newLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.EXTENDED; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, 20, p); buf.utf8Write('hardlink@openssh.com', p += 4, 20); writeUInt32BE(buf, oldLen, p += 20); buf.utf8Write(oldPath, p += 4, oldLen); writeUInt32BE(buf, newLen, p += oldLen); buf.utf8Write(newPath, p += 4, newLen); this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); if (this._debug) { const which = (isBuffered ? 'Buffered' : 'Sending'); this._debug(`SFTP: Outbound: ${which} hardlink@openssh.com`); } } ext_openssh_fsync(handle, cb) { if (this.server) throw new Error('Client-only method called in server mode'); const ext = this._extensions['fsync@openssh.com']; if (ext !== '1') throw new Error('Server does not support this extended request'); if (!Buffer.isBuffer(handle)) throw new Error('handle is not a Buffer'); /* uint32 id string "fsync@openssh.com" string handle */ const handleLen = handle.length; let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 17 + 4 + handleLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.EXTENDED; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, 17, p); buf.utf8Write('fsync@openssh.com', p += 4, 17); writeUInt32BE(buf, handleLen, p += 17); buf.set(handle, p += 4); this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} fsync@openssh.com` ); } ext_openssh_lsetstat(path, attrs, cb) { if (this.server) throw new Error('Client-only method called in server mode'); const ext = this._extensions['lsetstat@openssh.com']; if (ext !== '1') throw new Error('Server does not support this extended request'); let flags = 0; let attrsLen = 0; if (typeof attrs === 'object' && attrs !== null) { attrs = attrsToBytes(attrs); flags = attrs.flags; attrsLen = attrs.nb; } else if (typeof attrs === 'function') { cb = attrs; } /* uint32 id string "lsetstat@openssh.com" string path ATTRS attrs */ const pathLen = Buffer.byteLength(path); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + pathLen + 4 + attrsLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.EXTENDED; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, 20, p); buf.utf8Write('lsetstat@openssh.com', p += 4, 20); writeUInt32BE(buf, pathLen, p += 20); buf.utf8Write(path, p += 4, pathLen); writeUInt32BE(buf, flags, p += pathLen); if (attrsLen) { p += 4; if (attrsLen === ATTRS_BUF.length) buf.set(ATTRS_BUF, p); else bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); p += attrsLen; } this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); if (this._debug) { const status = (isBuffered ? 'Buffered' : 'Sending'); this._debug(`SFTP: Outbound: ${status} lsetstat@openssh.com`); } } ext_openssh_expandPath(path, cb) { if (this.server) throw new Error('Client-only method called in server mode'); const ext = this._extensions['expand-path@openssh.com']; if (ext !== '1') throw new Error('Server does not support this extended request'); /* uint32 id string "expand-path@openssh.com" string path */ const pathLen = Buffer.byteLength(path); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 23 + 4 + pathLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.EXTENDED; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, 23, p); buf.utf8Write('expand-path@openssh.com', p += 4, 23); writeUInt32BE(buf, pathLen, p += 20); buf.utf8Write(path, p += 4, pathLen); this._requests[reqid] = { cb: (err, names) => { if (typeof cb !== 'function') return; if (err) return cb(err); if (!names || !names.length) return cb(new Error('Response missing expanded path')); cb(undefined, names[0].filename); } }; const isBuffered = sendOrBuffer(this, buf); if (this._debug) { const status = (isBuffered ? 'Buffered' : 'Sending'); this._debug(`SFTP: Outbound: ${status} expand-path@openssh.com`); } } ext_copy_data(srcHandle, srcOffset, len, dstHandle, dstOffset, cb) { if (this.server) throw new Error('Client-only method called in server mode'); const ext = this._extensions['copy-data']; if (ext !== '1') throw new Error('Server does not support this extended request'); if (!Buffer.isBuffer(srcHandle)) throw new Error('Source handle is not a Buffer'); if (!Buffer.isBuffer(dstHandle)) throw new Error('Destination handle is not a Buffer'); /* uint32 id string "copy-data" string read-from-handle uint64 read-from-offset uint64 read-data-length string write-to-handle uint64 write-to-offset */ let p = 0; const buf = Buffer.allocUnsafe( 4 + 1 + 4 + 4 + 9 + 4 + srcHandle.length + 8 + 8 + 4 + dstHandle.length + 8 ); writeUInt32BE(buf, buf.length - 4, p); p += 4; buf[p] = REQUEST.EXTENDED; ++p; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, p); p += 4; writeUInt32BE(buf, 9, p); p += 4; buf.utf8Write('copy-data', p, 9); p += 9; writeUInt32BE(buf, srcHandle.length, p); p += 4; buf.set(srcHandle, p); p += srcHandle.length; for (let i = 7; i >= 0; --i) { buf[p + i] = srcOffset & 0xFF; srcOffset /= 256; } p += 8; for (let i = 7; i >= 0; --i) { buf[p + i] = len & 0xFF; len /= 256; } p += 8; writeUInt32BE(buf, dstHandle.length, p); p += 4; buf.set(dstHandle, p); p += dstHandle.length; for (let i = 7; i >= 0; --i) { buf[p + i] = dstOffset & 0xFF; dstOffset /= 256; } this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); if (this._debug) { const status = (isBuffered ? 'Buffered' : 'Sending'); this._debug(`SFTP: Outbound: ${status} copy-data`); } } ext_home_dir(username, cb) { if (this.server) throw new Error('Client-only method called in server mode'); const ext = this._extensions['home-directory']; if (ext !== '1') throw new Error('Server does not support this extended request'); if (typeof username !== 'string') throw new TypeError('username is not a string'); /* uint32 id string "home-directory" string username */ let p = 0; const usernameLen = Buffer.byteLength(username); const buf = Buffer.allocUnsafe( 4 + 1 + 4 + 4 + 14 + 4 + usernameLen ); writeUInt32BE(buf, buf.length - 4, p); p += 4; buf[p] = REQUEST.EXTENDED; ++p; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, p); p += 4; writeUInt32BE(buf, 14, p); p += 4; buf.utf8Write('home-directory', p, 14); p += 14; writeUInt32BE(buf, usernameLen, p); p += 4; buf.utf8Write(username, p, usernameLen); p += usernameLen; this._requests[reqid] = { cb: (err, names) => { if (typeof cb !== 'function') return; if (err) return cb(err); if (!names || !names.length) return cb(new Error('Response missing home directory')); cb(undefined, names[0].filename); } }; const isBuffered = sendOrBuffer(this, buf); if (this._debug) { const status = (isBuffered ? 'Buffered' : 'Sending'); this._debug(`SFTP: Outbound: ${status} home-directory`); } } ext_users_groups(uids, gids, cb) { if (this.server) throw new Error('Client-only method called in server mode'); const ext = this._extensions['users-groups-by-id@openssh.com']; if (ext !== '1') throw new Error('Server does not support this extended request'); if (!Array.isArray(uids)) throw new TypeError('uids is not an array'); for (const val of uids) { if (!Number.isInteger(val) || val < 0 || val > (2 ** 32 - 1)) throw new Error('uid values must all be 32-bit unsigned integers'); } if (!Array.isArray(gids)) throw new TypeError('gids is not an array'); for (const val of gids) { if (!Number.isInteger(val) || val < 0 || val > (2 ** 32 - 1)) throw new Error('gid values must all be 32-bit unsigned integers'); } /* uint32 id string "users-groups-by-id@openssh.com" string uids uint32 uid1 ... string gids uint32 gid1 ... */ let p = 0; const buf = Buffer.allocUnsafe( 4 + 1 + 4 + 4 + 30 + 4 + (4 * uids.length) + 4 + (4 * gids.length) ); writeUInt32BE(buf, buf.length - 4, p); p += 4; buf[p] = REQUEST.EXTENDED; ++p; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, p); p += 4; writeUInt32BE(buf, 30, p); p += 4; buf.utf8Write('users-groups-by-id@openssh.com', p, 30); p += 30; writeUInt32BE(buf, 4 * uids.length, p); p += 4; for (const val of uids) { writeUInt32BE(buf, val, p); p += 4; } writeUInt32BE(buf, 4 * gids.length, p); p += 4; for (const val of gids) { writeUInt32BE(buf, val, p); p += 4; } this._requests[reqid] = { extended: 'users-groups-by-id@openssh.com', cb }; const isBuffered = sendOrBuffer(this, buf); if (this._debug) { const status = (isBuffered ? 'Buffered' : 'Sending'); this._debug(`SFTP: Outbound: ${status} users-groups-by-id@openssh.com`); } } // =========================================================================== // Server-specific =========================================================== // =========================================================================== handle(reqid, handle) { if (!this.server) throw new Error('Server-only method called in client mode'); if (!Buffer.isBuffer(handle)) throw new Error('handle is not a Buffer'); const handleLen = handle.length; if (handleLen > 256) throw new Error('handle too large (> 256 bytes)'); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = RESPONSE.HANDLE; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, handleLen, p); if (handleLen) buf.set(handle, p += 4); const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} HANDLE` ); } status(reqid, code, message) { if (!this.server) throw new Error('Server-only method called in client mode'); if (!VALID_STATUS_CODES.has(code)) throw new Error(`Bad status code: ${code}`); message || (message = ''); const msgLen = Buffer.byteLength(message); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 4 + msgLen + 4); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = RESPONSE.STATUS; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, code, p); writeUInt32BE(buf, msgLen, p += 4); p += 4; if (msgLen) { buf.utf8Write(message, p, msgLen); p += msgLen; } writeUInt32BE(buf, 0, p); // Empty language tag const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STATUS` ); } data(reqid, data, encoding) { if (!this.server) throw new Error('Server-only method called in client mode'); const isBuffer = Buffer.isBuffer(data); if (!isBuffer && typeof data !== 'string') throw new Error('data is not a Buffer or string'); let isUTF8; if (!isBuffer && !encoding) { encoding = undefined; isUTF8 = true; } const dataLen = ( isBuffer ? data.length : Buffer.byteLength(data, encoding) ); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + dataLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = RESPONSE.DATA; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, dataLen, p); if (dataLen) { if (isBuffer) buf.set(data, p += 4); else if (isUTF8) buf.utf8Write(data, p += 4, dataLen); else buf.write(data, p += 4, dataLen, encoding); } const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} DATA` ); } name(reqid, names) { if (!this.server) throw new Error('Server-only method called in client mode'); if (!Array.isArray(names)) { if (typeof names !== 'object' || names === null) throw new Error('names is not an object or array'); names = [ names ]; } const count = names.length; let namesLen = 0; let nameAttrs; const attrs = []; for (let i = 0; i < count; ++i) { const name = names[i]; const filename = ( !name || !name.filename || typeof name.filename !== 'string' ? '' : name.filename ); namesLen += 4 + Buffer.byteLength(filename); const longname = ( !name || !name.longname || typeof name.longname !== 'string' ? '' : name.longname ); namesLen += 4 + Buffer.byteLength(longname); if (typeof name.attrs === 'object' && name.attrs !== null) { nameAttrs = attrsToBytes(name.attrs); namesLen += 4 + nameAttrs.nb; if (nameAttrs.nb) { let bytes; if (nameAttrs.nb === ATTRS_BUF.length) { bytes = new Uint8Array(ATTRS_BUF); } else { bytes = new Uint8Array(nameAttrs.nb); bufferCopy(ATTRS_BUF, bytes, 0, nameAttrs.nb, 0); } nameAttrs.bytes = bytes; } attrs.push(nameAttrs); } else { namesLen += 4; attrs.push(null); } } let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + namesLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = RESPONSE.NAME; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, count, p); p += 4; for (let i = 0; i < count; ++i) { const name = names[i]; { const filename = ( !name || !name.filename || typeof name.filename !== 'string' ? '' : name.filename ); const len = Buffer.byteLength(filename); writeUInt32BE(buf, len, p); p += 4; if (len) { buf.utf8Write(filename, p, len); p += len; } } { const longname = ( !name || !name.longname || typeof name.longname !== 'string' ? '' : name.longname ); const len = Buffer.byteLength(longname); writeUInt32BE(buf, len, p); p += 4; if (len) { buf.utf8Write(longname, p, len); p += len; } } const attr = attrs[i]; if (attr) { writeUInt32BE(buf, attr.flags, p); p += 4; if (attr.flags && attr.bytes) { buf.set(attr.bytes, p); p += attr.nb; } } else { writeUInt32BE(buf, 0, p); p += 4; } } const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} NAME` ); } attrs(reqid, attrs) { if (!this.server) throw new Error('Server-only method called in client mode'); if (typeof attrs !== 'object' || attrs === null) throw new Error('attrs is not an object'); attrs = attrsToBytes(attrs); const flags = attrs.flags; const attrsLen = attrs.nb; let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + attrsLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = RESPONSE.ATTRS; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, flags, p); if (attrsLen) { p += 4; if (attrsLen === ATTRS_BUF.length) buf.set(ATTRS_BUF, p); else bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); p += attrsLen; } const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} ATTRS` ); } } function tryCreateBuffer(size) { try { return Buffer.allocUnsafe(size); } catch (ex) { return ex; } } function read_(self, handle, buf, off, len, position, cb, req_) { const maxDataLen = self._maxReadLen; const overflow = Math.max(len - maxDataLen, 0); if (overflow) len = maxDataLen; /* uint32 id string handle uint64 offset uint32 len */ const handleLen = handle.length; let p = 9; let pos = position; const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4); writeUInt32BE(out, out.length - 4, 0); out[4] = REQUEST.READ; const reqid = self._writeReqid = (self._writeReqid + 1) & MAX_REQID; writeUInt32BE(out, reqid, 5); writeUInt32BE(out, handleLen, p); out.set(handle, p += 4); p += handleLen; for (let i = 7; i >= 0; --i) { out[p + i] = pos & 0xFF; pos /= 256; } writeUInt32BE(out, len, p += 8); if (typeof cb !== 'function') cb = noop; const req = (req_ || { nb: 0, position, off, origOff: off, len: undefined, overflow: undefined, cb: (err, data, nb) => { const len = req.len; const overflow = req.overflow; if (err) { if (cb._wantEOFError || err.code !== STATUS_CODE.EOF) return cb(err); } else if (nb > len) { return cb(new Error('Received more data than requested')); } else if (nb === len && overflow) { req.nb += nb; req.position += nb; req.off += nb; read_(self, handle, buf, req.off, overflow, req.position, cb, req); return; } nb = (nb || 0); if (req.origOff === 0 && buf.length === req.nb) data = buf; else data = bufferSlice(buf, req.origOff, req.origOff + req.nb + nb); cb(undefined, req.nb + nb, data, req.position); }, buffer: undefined, }); req.len = len; req.overflow = overflow; // TODO: avoid creating multiple buffer slices when we need to re-call read_() // because of overflow req.buffer = bufferSlice(buf, off, off + len); self._requests[reqid] = req; const isBuffered = sendOrBuffer(self, out); self._debug && self._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READ` ); } function fastXfer(src, dst, srcPath, dstPath, opts, cb) { let concurrency = 64; let chunkSize = 32768; let onstep; let mode; let fileSize; if (typeof opts === 'function') { cb = opts; } else if (typeof opts === 'object' && opts !== null) { if (typeof opts.concurrency === 'number' && opts.concurrency > 0 && !isNaN(opts.concurrency)) { concurrency = opts.concurrency; } if (typeof opts.chunkSize === 'number' && opts.chunkSize > 0 && !isNaN(opts.chunkSize)) { chunkSize = opts.chunkSize; } if (typeof opts.fileSize === 'number' && opts.fileSize > 0 && !isNaN(opts.fileSize)) { fileSize = opts.fileSize; } if (typeof opts.step === 'function') onstep = opts.step; if (typeof opts.mode === 'string' || typeof opts.mode === 'number') mode = modeNum(opts.mode); } // Internal state variables let fsize; let pdst = 0; let total = 0; let hadError = false; let srcHandle; let dstHandle; let readbuf; let bufsize = chunkSize * concurrency; function onerror(err) { if (hadError) return; hadError = true; let left = 0; let cbfinal; if (srcHandle || dstHandle) { cbfinal = () => { if (--left === 0) cb(err); }; if (srcHandle && (src === fs || src.outgoing.state === 'open')) ++left; if (dstHandle && (dst === fs || dst.outgoing.state === 'open')) ++left; if (srcHandle && (src === fs || src.outgoing.state === 'open')) src.close(srcHandle, cbfinal); if (dstHandle && (dst === fs || dst.outgoing.state === 'open')) dst.close(dstHandle, cbfinal); } else { cb(err); } } src.open(srcPath, 'r', (err, sourceHandle) => { if (err) return onerror(err); srcHandle = sourceHandle; if (fileSize === undefined) src.fstat(srcHandle, tryStat); else tryStat(null, { size: fileSize }); function tryStat(err, attrs) { if (err) { if (src !== fs) { // Try stat() for sftp servers that may not support fstat() for // whatever reason src.stat(srcPath, (err_, attrs_) => { if (err_) return onerror(err); tryStat(null, attrs_); }); return; } return onerror(err); } fsize = attrs.size; dst.open(dstPath, 'w', (err, destHandle) => { if (err) return onerror(err); dstHandle = destHandle; if (fsize <= 0) return onerror(); // Use less memory where possible while (bufsize > fsize) { if (concurrency === 1) { bufsize = fsize; break; } bufsize -= chunkSize; --concurrency; } readbuf = tryCreateBuffer(bufsize); if (readbuf instanceof Error) return onerror(readbuf); if (mode !== undefined) { dst.fchmod(dstHandle, mode, function tryAgain(err) { if (err) { // Try chmod() for sftp servers that may not support fchmod() // for whatever reason dst.chmod(dstPath, mode, (err_) => tryAgain()); return; } startReads(); }); } else { startReads(); } function onread(err, nb, data, dstpos, datapos, origChunkLen) { if (err) return onerror(err); datapos = datapos || 0; dst.write(dstHandle, readbuf, datapos, nb, dstpos, writeCb); function writeCb(err) { if (err) return onerror(err); total += nb; onstep && onstep(total, nb, fsize); if (nb < origChunkLen) return singleRead(datapos, dstpos + nb, origChunkLen - nb); if (total === fsize) { dst.close(dstHandle, (err) => { dstHandle = undefined; if (err) return onerror(err); src.close(srcHandle, (err) => { srcHandle = undefined; if (err) return onerror(err); cb(); }); }); return; } if (pdst >= fsize) return; const chunk = (pdst + chunkSize > fsize ? fsize - pdst : chunkSize); singleRead(datapos, pdst, chunk); pdst += chunk; } } function makeCb(psrc, pdst, chunk) { return (err, nb, data) => { onread(err, nb, data, pdst, psrc, chunk); }; } function singleRead(psrc, pdst, chunk) { src.read(srcHandle, readbuf, psrc, chunk, pdst, makeCb(psrc, pdst, chunk)); } function startReads() { let reads = 0; let psrc = 0; while (pdst < fsize && reads < concurrency) { const chunk = (pdst + chunkSize > fsize ? fsize - pdst : chunkSize); singleRead(psrc, pdst, chunk); psrc += chunk; pdst += chunk; ++reads; } } }); } }); } function writeAll(sftp, handle, buffer, offset, length, position, callback_) { const callback = (typeof callback_ === 'function' ? callback_ : undefined); sftp.write(handle, buffer, offset, length, position, (writeErr, written) => { if (writeErr) { return sftp.close(handle, () => { callback && callback(writeErr); }); } if (written === length) { sftp.close(handle, callback); } else { offset += written; length -= written; position += written; writeAll(sftp, handle, buffer, offset, length, position, callback); } }); } class Stats { constructor(initial) { this.mode = (initial && initial.mode); this.uid = (initial && initial.uid); this.gid = (initial && initial.gid); this.size = (initial && initial.size); this.atime = (initial && initial.atime); this.mtime = (initial && initial.mtime); this.extended = (initial && initial.extended); } isDirectory() { return ((this.mode & constants.S_IFMT) === constants.S_IFDIR); } isFile() { return ((this.mode & constants.S_IFMT) === constants.S_IFREG); } isBlockDevice() { return ((this.mode & constants.S_IFMT) === constants.S_IFBLK); } isCharacterDevice() { return ((this.mode & constants.S_IFMT) === constants.S_IFCHR); } isSymbolicLink() { return ((this.mode & constants.S_IFMT) === constants.S_IFLNK); } isFIFO() { return ((this.mode & constants.S_IFMT) === constants.S_IFIFO); } isSocket() { return ((this.mode & constants.S_IFMT) === constants.S_IFSOCK); } } function attrsToBytes(attrs) { let flags = 0; let nb = 0; if (typeof attrs === 'object' && attrs !== null) { if (typeof attrs.size === 'number') { flags |= ATTR.SIZE; const val = attrs.size; // Big Endian ATTRS_BUF[nb++] = val / 72057594037927940; // 2**56 ATTRS_BUF[nb++] = val / 281474976710656; // 2**48 ATTRS_BUF[nb++] = val / 1099511627776; // 2**40 ATTRS_BUF[nb++] = val / 4294967296; // 2**32 ATTRS_BUF[nb++] = val / 16777216; // 2**24 ATTRS_BUF[nb++] = val / 65536; // 2**16 ATTRS_BUF[nb++] = val / 256; // 2**8 ATTRS_BUF[nb++] = val; } if (typeof attrs.uid === 'number' && typeof attrs.gid === 'number') { flags |= ATTR.UIDGID; const uid = attrs.uid; const gid = attrs.gid; // Big Endian ATTRS_BUF[nb++] = uid >>> 24; ATTRS_BUF[nb++] = uid >>> 16; ATTRS_BUF[nb++] = uid >>> 8; ATTRS_BUF[nb++] = uid; ATTRS_BUF[nb++] = gid >>> 24; ATTRS_BUF[nb++] = gid >>> 16; ATTRS_BUF[nb++] = gid >>> 8; ATTRS_BUF[nb++] = gid; } if (typeof attrs.mode === 'number' || typeof attrs.mode === 'string') { const mode = modeNum(attrs.mode); flags |= ATTR.PERMISSIONS; // Big Endian ATTRS_BUF[nb++] = mode >>> 24; ATTRS_BUF[nb++] = mode >>> 16; ATTRS_BUF[nb++] = mode >>> 8; ATTRS_BUF[nb++] = mode; } if ((typeof attrs.atime === 'number' || isDate(attrs.atime)) && (typeof attrs.mtime === 'number' || isDate(attrs.mtime))) { const atime = toUnixTimestamp(attrs.atime); const mtime = toUnixTimestamp(attrs.mtime); flags |= ATTR.ACMODTIME; // Big Endian ATTRS_BUF[nb++] = atime >>> 24; ATTRS_BUF[nb++] = atime >>> 16; ATTRS_BUF[nb++] = atime >>> 8; ATTRS_BUF[nb++] = atime; ATTRS_BUF[nb++] = mtime >>> 24; ATTRS_BUF[nb++] = mtime >>> 16; ATTRS_BUF[nb++] = mtime >>> 8; ATTRS_BUF[nb++] = mtime; } // TODO: extended attributes } return { flags, nb }; } function toUnixTimestamp(time) { // eslint-disable-next-line no-self-compare if (typeof time === 'number' && time === time) // Valid, non-NaN number return time; if (isDate(time)) return parseInt(time.getTime() / 1000, 10); throw new Error(`Cannot parse time: ${time}`); } function modeNum(mode) { // eslint-disable-next-line no-self-compare if (typeof mode === 'number' && mode === mode) // Valid, non-NaN number return mode; if (typeof mode === 'string') return modeNum(parseInt(mode, 8)); throw new Error(`Cannot parse mode: ${mode}`); } const stringFlagMap = { 'r': OPEN_MODE.READ, 'r+': OPEN_MODE.READ | OPEN_MODE.WRITE, 'w': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE, 'wx': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, 'xw': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, 'w+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, 'wx+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE | OPEN_MODE.EXCL, 'xw+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE | OPEN_MODE.EXCL, 'a': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE, 'ax': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, 'xa': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, 'a+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, 'ax+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE | OPEN_MODE.EXCL, 'xa+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE | OPEN_MODE.EXCL }; function stringToFlags(str) { const flags = stringFlagMap[str]; return (flags !== undefined ? flags : null); } const flagsToString = (() => { const stringFlagMapKeys = Object.keys(stringFlagMap); return (flags) => { for (let i = 0; i < stringFlagMapKeys.length; ++i) { const key = stringFlagMapKeys[i]; if (stringFlagMap[key] === flags) return key; } return null; }; })(); function readAttrs(biOpt) { /* uint32 flags uint64 size present only if flag SSH_FILEXFER_ATTR_SIZE uint32 uid present only if flag SSH_FILEXFER_ATTR_UIDGID uint32 gid present only if flag SSH_FILEXFER_ATTR_UIDGID uint32 permissions present only if flag SSH_FILEXFER_ATTR_PERMISSIONS uint32 atime present only if flag SSH_FILEXFER_ACMODTIME uint32 mtime present only if flag SSH_FILEXFER_ACMODTIME uint32 extended_count present only if flag SSH_FILEXFER_ATTR_EXTENDED string extended_type string extended_data ... more extended data (extended_type - extended_data pairs), so that number of pairs equals extended_count */ const flags = bufferParser.readUInt32BE(); if (flags === undefined) return; const attrs = new Stats(); if (flags & ATTR.SIZE) { const size = bufferParser.readUInt64BE(biOpt); if (size === undefined) return; attrs.size = size; } if (flags & ATTR.UIDGID) { const uid = bufferParser.readUInt32BE(); const gid = bufferParser.readUInt32BE(); if (gid === undefined) return; attrs.uid = uid; attrs.gid = gid; } if (flags & ATTR.PERMISSIONS) { const mode = bufferParser.readUInt32BE(); if (mode === undefined) return; attrs.mode = mode; } if (flags & ATTR.ACMODTIME) { const atime = bufferParser.readUInt32BE(); const mtime = bufferParser.readUInt32BE(); if (mtime === undefined) return; attrs.atime = atime; attrs.mtime = mtime; } if (flags & ATTR.EXTENDED) { const count = bufferParser.readUInt32BE(); if (count === undefined) return; const extended = {}; for (let i = 0; i < count; ++i) { const type = bufferParser.readString(true); const data = bufferParser.readString(); if (data === undefined) return; extended[type] = data; } attrs.extended = extended; } return attrs; } function sendOrBuffer(sftp, payload) { const ret = tryWritePayload(sftp, payload); if (ret !== undefined) { sftp._buffer.push(ret); return false; } return true; } function tryWritePayload(sftp, payload) { const outgoing = sftp.outgoing; if (outgoing.state !== 'open') return; if (outgoing.window === 0) { sftp._waitWindow = true; sftp._chunkcb = drainBuffer; return payload; } let ret; const len = payload.length; let p = 0; while (len - p > 0 && outgoing.window > 0) { const actualLen = Math.min(len - p, outgoing.window, outgoing.packetSize); outgoing.window -= actualLen; if (outgoing.window === 0) { sftp._waitWindow = true; sftp._chunkcb = drainBuffer; } if (p === 0 && actualLen === len) { sftp._protocol.channelData(sftp.outgoing.id, payload); } else { sftp._protocol.channelData(sftp.outgoing.id, bufferSlice(payload, p, p + actualLen)); } p += actualLen; } if (len - p > 0) { if (p > 0) ret = bufferSlice(payload, p, len); else ret = payload; // XXX: should never get here? } return ret; } function drainBuffer() { this._chunkcb = undefined; const buffer = this._buffer; let i = 0; while (i < buffer.length) { const payload = buffer[i]; const ret = tryWritePayload(this, payload); if (ret !== undefined) { if (ret !== payload) buffer[i] = ret; if (i > 0) this._buffer = buffer.slice(i); return; } ++i; } if (i > 0) this._buffer = []; } function doFatalSFTPError(sftp, msg, noDebug) { const err = new Error(msg); err.level = 'sftp-protocol'; if (!noDebug && sftp._debug) sftp._debug(`SFTP: Inbound: ${msg}`); sftp.emit('error', err); sftp.destroy(); cleanupRequests(sftp); return false; } function cleanupRequests(sftp) { const keys = Object.keys(sftp._requests); if (keys.length === 0) return; const reqs = sftp._requests; sftp._requests = {}; const err = new Error('No response from server'); for (let i = 0; i < keys.length; ++i) { const req = reqs[keys[i]]; if (typeof req.cb === 'function') req.cb(err); } } function requestLimits(sftp, cb) { /* uint32 id string "limits@openssh.com" */ let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 18); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.EXTENDED; const reqid = sftp._writeReqid = (sftp._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, 18, p); buf.utf8Write('limits@openssh.com', p += 4, 18); sftp._requests[reqid] = { extended: 'limits@openssh.com', cb }; const isBuffered = sendOrBuffer(sftp, buf); if (sftp._debug) { const which = (isBuffered ? 'Buffered' : 'Sending'); sftp._debug(`SFTP: Outbound: ${which} limits@openssh.com`); } } const CLIENT_HANDLERS = { [RESPONSE.VERSION]: (sftp, payload) => { if (sftp._version !== -1) return doFatalSFTPError(sftp, 'Duplicate VERSION packet'); const extensions = {}; /* uint32 version */ bufferParser.init(payload, 1); let version = bufferParser.readUInt32BE(); while (bufferParser.avail()) { const extName = bufferParser.readString(true); const extData = bufferParser.readString(true); if (extData === undefined) { version = undefined; break; } extensions[extName] = extData; } bufferParser.clear(); if (version === undefined) return doFatalSFTPError(sftp, 'Malformed VERSION packet'); if (sftp._debug) { const names = Object.keys(extensions); if (names.length) { sftp._debug( `SFTP: Inbound: Received VERSION (v${version}, exts:${names})` ); } else { sftp._debug(`SFTP: Inbound: Received VERSION (v${version})`); } } sftp._version = version; sftp._extensions = extensions; if (extensions['limits@openssh.com'] === '1') { return requestLimits(sftp, (err, limits) => { if (!err) { if (limits.maxPktLen > 0) sftp._maxOutPktLen = limits.maxPktLen; if (limits.maxReadLen > 0) sftp._maxReadLen = limits.maxReadLen; if (limits.maxWriteLen > 0) sftp._maxWriteLen = limits.maxWriteLen; sftp.maxOpenHandles = ( limits.maxOpenHandles > 0 ? limits.maxOpenHandles : Infinity ); } sftp.emit('ready'); }); } sftp.emit('ready'); }, [RESPONSE.STATUS]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* uint32 error/status code string error message (ISO-10646 UTF-8) string language tag */ const errorCode = bufferParser.readUInt32BE(); const errorMsg = bufferParser.readString(true); bufferParser.clear(); // Note: we avoid checking that the error message and language tag are in // the packet because there are some broken implementations that incorrectly // omit them. The language tag in general was never really used amongst ssh // implementations, so in the case of a missing error message we just // default to something sensible. if (sftp._debug) { const jsonMsg = JSON.stringify(errorMsg); sftp._debug( `SFTP: Inbound: Received STATUS (id:${reqID}, ${errorCode}, ${jsonMsg})` ); } const req = sftp._requests[reqID]; delete sftp._requests[reqID]; if (req && typeof req.cb === 'function') { if (errorCode === STATUS_CODE.OK) { req.cb(); return; } const err = new Error(errorMsg || STATUS_CODE_STR[errorCode] || 'Unknown status'); err.code = errorCode; req.cb(err); } }, [RESPONSE.HANDLE]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string handle */ const handle = bufferParser.readString(); bufferParser.clear(); if (handle === undefined) { if (reqID !== undefined) delete sftp._requests[reqID]; return doFatalSFTPError(sftp, 'Malformed HANDLE packet'); } sftp._debug && sftp._debug(`SFTP: Inbound: Received HANDLE (id:${reqID})`); const req = sftp._requests[reqID]; delete sftp._requests[reqID]; if (req && typeof req.cb === 'function') req.cb(undefined, handle); }, [RESPONSE.DATA]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); let req; if (reqID !== undefined) { req = sftp._requests[reqID]; delete sftp._requests[reqID]; } /* string data */ if (req && typeof req.cb === 'function') { if (req.buffer) { // We have already pre-allocated space to store the data const nb = bufferParser.readString(req.buffer); bufferParser.clear(); if (nb !== undefined) { sftp._debug && sftp._debug( `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})` ); req.cb(undefined, req.buffer, nb); return; } } else { const data = bufferParser.readString(); bufferParser.clear(); if (data !== undefined) { sftp._debug && sftp._debug( `SFTP: Inbound: Received DATA (id:${reqID}, ${data.length})` ); req.cb(undefined, data); return; } } } else { const nb = bufferParser.skipString(); bufferParser.clear(); if (nb !== undefined) { sftp._debug && sftp._debug( `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})` ); return; } } return doFatalSFTPError(sftp, 'Malformed DATA packet'); }, [RESPONSE.NAME]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); let req; if (reqID !== undefined) { req = sftp._requests[reqID]; delete sftp._requests[reqID]; } /* uint32 count repeats count times: string filename string longname ATTRS attrs */ const count = bufferParser.readUInt32BE(); if (count !== undefined) { let names = []; for (let i = 0; i < count; ++i) { // We are going to assume UTF-8 for filenames despite the SFTPv3 // spec not specifying an encoding because the specs for newer // versions of the protocol all explicitly specify UTF-8 for // filenames const filename = bufferParser.readString(true); // `longname` only exists in SFTPv3 and since it typically will // contain the filename, we assume it is also UTF-8 const longname = bufferParser.readString(true); const attrs = readAttrs(sftp._biOpt); if (attrs === undefined) { names = undefined; break; } names.push({ filename, longname, attrs }); } if (names !== undefined) { sftp._debug && sftp._debug( `SFTP: Inbound: Received NAME (id:${reqID}, ${names.length})` ); bufferParser.clear(); if (req && typeof req.cb === 'function') req.cb(undefined, names); return; } } bufferParser.clear(); return doFatalSFTPError(sftp, 'Malformed NAME packet'); }, [RESPONSE.ATTRS]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); let req; if (reqID !== undefined) { req = sftp._requests[reqID]; delete sftp._requests[reqID]; } /* ATTRS attrs */ const attrs = readAttrs(sftp._biOpt); bufferParser.clear(); if (attrs !== undefined) { sftp._debug && sftp._debug(`SFTP: Inbound: Received ATTRS (id:${reqID})`); if (req && typeof req.cb === 'function') req.cb(undefined, attrs); return; } return doFatalSFTPError(sftp, 'Malformed ATTRS packet'); }, [RESPONSE.EXTENDED]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); if (reqID !== undefined) { const req = sftp._requests[reqID]; if (req) { delete sftp._requests[reqID]; switch (req.extended) { case 'statvfs@openssh.com': case 'fstatvfs@openssh.com': { /* uint64 f_bsize // file system block size uint64 f_frsize // fundamental fs block size uint64 f_blocks // number of blocks (unit f_frsize) uint64 f_bfree // free blocks in file system uint64 f_bavail // free blocks for non-root uint64 f_files // total file inodes uint64 f_ffree // free file inodes uint64 f_favail // free file inodes for to non-root uint64 f_fsid // file system id uint64 f_flag // bit mask of f_flag values uint64 f_namemax // maximum filename length */ const biOpt = sftp._biOpt; const stats = { f_bsize: bufferParser.readUInt64BE(biOpt), f_frsize: bufferParser.readUInt64BE(biOpt), f_blocks: bufferParser.readUInt64BE(biOpt), f_bfree: bufferParser.readUInt64BE(biOpt), f_bavail: bufferParser.readUInt64BE(biOpt), f_files: bufferParser.readUInt64BE(biOpt), f_ffree: bufferParser.readUInt64BE(biOpt), f_favail: bufferParser.readUInt64BE(biOpt), f_sid: bufferParser.readUInt64BE(biOpt), f_flag: bufferParser.readUInt64BE(biOpt), f_namemax: bufferParser.readUInt64BE(biOpt), }; if (stats.f_namemax === undefined) break; if (sftp._debug) { sftp._debug( 'SFTP: Inbound: Received EXTENDED_REPLY ' + `(id:${reqID}, ${req.extended})` ); } bufferParser.clear(); if (typeof req.cb === 'function') req.cb(undefined, stats); return; } case 'limits@openssh.com': { /* uint64 max-packet-length uint64 max-read-length uint64 max-write-length uint64 max-open-handles */ const limits = { maxPktLen: bufferParser.readUInt64BE(), maxReadLen: bufferParser.readUInt64BE(), maxWriteLen: bufferParser.readUInt64BE(), maxOpenHandles: bufferParser.readUInt64BE(), }; if (limits.maxOpenHandles === undefined) break; if (sftp._debug) { sftp._debug( 'SFTP: Inbound: Received EXTENDED_REPLY ' + `(id:${reqID}, ${req.extended})` ); } bufferParser.clear(); if (typeof req.cb === 'function') req.cb(undefined, limits); return; } case 'users-groups-by-id@openssh.com': { /* string usernames string username1 ... string groupnames string groupname1 ... */ const usernameCount = bufferParser.readUInt32BE(); if (usernameCount === undefined) break; const usernames = new Array(usernameCount); for (let i = 0; i < usernames.length; ++i) usernames[i] = bufferParser.readString(true); const groupnameCount = bufferParser.readUInt32BE(); if (groupnameCount === undefined) break; const groupnames = new Array(groupnameCount); for (let i = 0; i < groupnames.length; ++i) groupnames[i] = bufferParser.readString(true); if (groupnames.length > 0 && groupnames[groupnames.length - 1] === undefined) { break; } if (sftp._debug) { sftp._debug( 'SFTP: Inbound: Received EXTENDED_REPLY ' + `(id:${reqID}, ${req.extended})` ); } bufferParser.clear(); if (typeof req.cb === 'function') req.cb(undefined, usernames, groupnames); return; } default: // Unknown extended request sftp._debug && sftp._debug( `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)` ); bufferParser.clear(); if (typeof req.cb === 'function') req.cb(); return; } } else { sftp._debug && sftp._debug( `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)` ); bufferParser.clear(); return; } } bufferParser.clear(); return doFatalSFTPError(sftp, 'Malformed EXTENDED_REPLY packet'); }, }; const SERVER_HANDLERS = { [REQUEST.INIT]: (sftp, payload) => { if (sftp._version !== -1) return doFatalSFTPError(sftp, 'Duplicate INIT packet'); const extensions = {}; /* uint32 version */ bufferParser.init(payload, 1); let version = bufferParser.readUInt32BE(); while (bufferParser.avail()) { const extName = bufferParser.readString(true); const extData = bufferParser.readString(true); if (extData === undefined) { version = undefined; break; } extensions[extName] = extData; } bufferParser.clear(); if (version === undefined) return doFatalSFTPError(sftp, 'Malformed INIT packet'); if (sftp._debug) { const names = Object.keys(extensions); if (names.length) { sftp._debug( `SFTP: Inbound: Received INIT (v${version}, exts:${names})` ); } else { sftp._debug(`SFTP: Inbound: Received INIT (v${version})`); } } sendOrBuffer(sftp, SERVER_VERSION_BUFFER); sftp._version = version; sftp._extensions = extensions; sftp.emit('ready'); }, [REQUEST.OPEN]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string filename uint32 pflags ATTRS attrs */ const filename = bufferParser.readString(true); const pflags = bufferParser.readUInt32BE(); const attrs = readAttrs(sftp._biOpt); bufferParser.clear(); if (attrs === undefined) return doFatalSFTPError(sftp, 'Malformed OPEN packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received OPEN (id:${reqID})`); if (!sftp.emit('OPEN', reqID, filename, pflags, attrs)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.CLOSE]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string handle */ const handle = bufferParser.readString(); bufferParser.clear(); if (handle === undefined || handle.length > 256) return doFatalSFTPError(sftp, 'Malformed CLOSE packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received CLOSE (id:${reqID})`); if (!sftp.emit('CLOSE', reqID, handle)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.READ]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string handle uint64 offset uint32 len */ const handle = bufferParser.readString(); const offset = bufferParser.readUInt64BE(sftp._biOpt); const len = bufferParser.readUInt32BE(); bufferParser.clear(); if (len === undefined || handle.length > 256) return doFatalSFTPError(sftp, 'Malformed READ packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received READ (id:${reqID})`); if (!sftp.emit('READ', reqID, handle, offset, len)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.WRITE]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string handle uint64 offset string data */ const handle = bufferParser.readString(); const offset = bufferParser.readUInt64BE(sftp._biOpt); const data = bufferParser.readString(); bufferParser.clear(); if (data === undefined || handle.length > 256) return doFatalSFTPError(sftp, 'Malformed WRITE packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received WRITE (id:${reqID})`); if (!sftp.emit('WRITE', reqID, handle, offset, data)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.LSTAT]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string path */ const path = bufferParser.readString(true); bufferParser.clear(); if (path === undefined) return doFatalSFTPError(sftp, 'Malformed LSTAT packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received LSTAT (id:${reqID})`); if (!sftp.emit('LSTAT', reqID, path)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.FSTAT]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string handle */ const handle = bufferParser.readString(); bufferParser.clear(); if (handle === undefined || handle.length > 256) return doFatalSFTPError(sftp, 'Malformed FSTAT packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received FSTAT (id:${reqID})`); if (!sftp.emit('FSTAT', reqID, handle)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.SETSTAT]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string path ATTRS attrs */ const path = bufferParser.readString(true); const attrs = readAttrs(sftp._biOpt); bufferParser.clear(); if (attrs === undefined) return doFatalSFTPError(sftp, 'Malformed SETSTAT packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received SETSTAT (id:${reqID})`); if (!sftp.emit('SETSTAT', reqID, path, attrs)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.FSETSTAT]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string handle ATTRS attrs */ const handle = bufferParser.readString(); const attrs = readAttrs(sftp._biOpt); bufferParser.clear(); if (attrs === undefined || handle.length > 256) return doFatalSFTPError(sftp, 'Malformed FSETSTAT packet'); sftp._debug && sftp._debug( `SFTP: Inbound: Received FSETSTAT (id:${reqID})` ); if (!sftp.emit('FSETSTAT', reqID, handle, attrs)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.OPENDIR]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string path */ const path = bufferParser.readString(true); bufferParser.clear(); if (path === undefined) return doFatalSFTPError(sftp, 'Malformed OPENDIR packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received OPENDIR (id:${reqID})`); if (!sftp.emit('OPENDIR', reqID, path)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.READDIR]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string handle */ const handle = bufferParser.readString(); bufferParser.clear(); if (handle === undefined || handle.length > 256) return doFatalSFTPError(sftp, 'Malformed READDIR packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received READDIR (id:${reqID})`); if (!sftp.emit('READDIR', reqID, handle)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.REMOVE]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string path */ const path = bufferParser.readString(true); bufferParser.clear(); if (path === undefined) return doFatalSFTPError(sftp, 'Malformed REMOVE packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received REMOVE (id:${reqID})`); if (!sftp.emit('REMOVE', reqID, path)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.MKDIR]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string path ATTRS attrs */ const path = bufferParser.readString(true); const attrs = readAttrs(sftp._biOpt); bufferParser.clear(); if (attrs === undefined) return doFatalSFTPError(sftp, 'Malformed MKDIR packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received MKDIR (id:${reqID})`); if (!sftp.emit('MKDIR', reqID, path, attrs)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.RMDIR]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string path */ const path = bufferParser.readString(true); bufferParser.clear(); if (path === undefined) return doFatalSFTPError(sftp, 'Malformed RMDIR packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received RMDIR (id:${reqID})`); if (!sftp.emit('RMDIR', reqID, path)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.REALPATH]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string path */ const path = bufferParser.readString(true); bufferParser.clear(); if (path === undefined) return doFatalSFTPError(sftp, 'Malformed REALPATH packet'); sftp._debug && sftp._debug( `SFTP: Inbound: Received REALPATH (id:${reqID})` ); if (!sftp.emit('REALPATH', reqID, path)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.STAT]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string path */ const path = bufferParser.readString(true); bufferParser.clear(); if (path === undefined) return doFatalSFTPError(sftp, 'Malformed STAT packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received STAT (id:${reqID})`); if (!sftp.emit('STAT', reqID, path)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.RENAME]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string oldpath string newpath */ const oldPath = bufferParser.readString(true); const newPath = bufferParser.readString(true); bufferParser.clear(); if (newPath === undefined) return doFatalSFTPError(sftp, 'Malformed RENAME packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received RENAME (id:${reqID})`); if (!sftp.emit('RENAME', reqID, oldPath, newPath)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.READLINK]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string path */ const path = bufferParser.readString(true); bufferParser.clear(); if (path === undefined) return doFatalSFTPError(sftp, 'Malformed READLINK packet'); sftp._debug && sftp._debug( `SFTP: Inbound: Received READLINK (id:${reqID})` ); if (!sftp.emit('READLINK', reqID, path)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.SYMLINK]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string linkpath string targetpath */ const linkPath = bufferParser.readString(true); const targetPath = bufferParser.readString(true); bufferParser.clear(); if (targetPath === undefined) return doFatalSFTPError(sftp, 'Malformed SYMLINK packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received SYMLINK (id:${reqID})`); let handled; if (sftp._isOpenSSH) { // OpenSSH has linkpath and targetpath positions switched handled = sftp.emit('SYMLINK', reqID, targetPath, linkPath); } else { handled = sftp.emit('SYMLINK', reqID, linkPath, targetPath); } if (!handled) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.EXTENDED]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string extended-request ... any request-specific data ... */ const extName = bufferParser.readString(true); if (extName === undefined) { bufferParser.clear(); return doFatalSFTPError(sftp, 'Malformed EXTENDED packet'); } let extData; if (bufferParser.avail()) extData = bufferParser.readRaw(); bufferParser.clear(); sftp._debug && sftp._debug( `SFTP: Inbound: Received EXTENDED (id:${reqID})` ); if (!sftp.emit('EXTENDED', reqID, extName, extData)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, }; // ============================================================================= // ReadStream/WriteStream-related ============================================== // ============================================================================= const { ERR_INVALID_ARG_TYPE, ERR_OUT_OF_RANGE, validateNumber } = __webpack_require__(85607); const kMinPoolSpace = 128; let pool; // It can happen that we expect to read a large chunk of data, and reserve // a large chunk of the pool accordingly, but the read() call only filled // a portion of it. If a concurrently executing read() then uses the same pool, // the "reserved" portion cannot be used, so we allow it to be re-used as a // new pool later. const poolFragments = []; function allocNewPool(poolSize) { if (poolFragments.length > 0) pool = poolFragments.pop(); else pool = Buffer.allocUnsafe(poolSize); pool.used = 0; } // Check the `this.start` and `this.end` of stream. function checkPosition(pos, name) { if (!Number.isSafeInteger(pos)) { validateNumber(pos, name); if (!Number.isInteger(pos)) throw new ERR_OUT_OF_RANGE(name, 'an integer', pos); throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos); } if (pos < 0) throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos); } function roundUpToMultipleOf8(n) { return (n + 7) & ~7; // Align to 8 byte boundary. } function ReadStream(sftp, path, options) { if (options === undefined) options = {}; else if (typeof options === 'string') options = { encoding: options }; else if (options === null || typeof options !== 'object') throw new TypeError('"options" argument must be a string or an object'); else options = Object.create(options); // A little bit bigger buffer and water marks by default if (options.highWaterMark === undefined) options.highWaterMark = 64 * 1024; // For backwards compat do not emit close on destroy. options.emitClose = false; options.autoDestroy = false; // Node 14 major change. ReadableStream.call(this, options); this.path = path; this.flags = options.flags === undefined ? 'r' : options.flags; this.mode = options.mode === undefined ? 0o666 : options.mode; this.start = options.start; this.end = options.end; this.autoClose = options.autoClose === undefined ? true : options.autoClose; this.pos = 0; this.bytesRead = 0; this.isClosed = false; this.handle = options.handle === undefined ? null : options.handle; this.sftp = sftp; this._opening = false; if (this.start !== undefined) { checkPosition(this.start, 'start'); this.pos = this.start; } if (this.end === undefined) { this.end = Infinity; } else if (this.end !== Infinity) { checkPosition(this.end, 'end'); if (this.start !== undefined && this.start > this.end) { throw new ERR_OUT_OF_RANGE( 'start', `<= "end" (here: ${this.end})`, this.start ); } } this.on('end', function() { if (this.autoClose) this.destroy(); }); if (!Buffer.isBuffer(this.handle)) this.open(); } inherits(ReadStream, ReadableStream); ReadStream.prototype.open = function() { if (this._opening) return; this._opening = true; this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { this._opening = false; if (er) { this.emit('error', er); if (this.autoClose) this.destroy(); return; } this.handle = handle; this.emit('open', handle); this.emit('ready'); // Start the flow of data. this.read(); }); }; ReadStream.prototype._read = function(n) { if (!Buffer.isBuffer(this.handle)) return this.once('open', () => this._read(n)); // XXX: safe to remove this? if (this.destroyed) return; if (!pool || pool.length - pool.used < kMinPoolSpace) { // Discard the old pool. allocNewPool(this.readableHighWaterMark || this._readableState.highWaterMark); } // Grab another reference to the pool in the case that while we're // in the thread pool another read() finishes up the pool, and // allocates a new one. const thisPool = pool; let toRead = Math.min(pool.length - pool.used, n); const start = pool.used; if (this.end !== undefined) toRead = Math.min(this.end - this.pos + 1, toRead); // Already read everything we were supposed to read! // treat as EOF. if (toRead <= 0) return this.push(null); // the actual read. this.sftp.read(this.handle, pool, pool.used, toRead, this.pos, (er, bytesRead) => { if (er) { this.emit('error', er); if (this.autoClose) this.destroy(); return; } let b = null; // Now that we know how much data we have actually read, re-wind the // 'used' field if we can, and otherwise allow the remainder of our // reservation to be used as a new pool later. if (start + toRead === thisPool.used && thisPool === pool) { thisPool.used = roundUpToMultipleOf8(thisPool.used + bytesRead - toRead); } else { // Round down to the next lowest multiple of 8 to ensure the new pool // fragment start and end positions are aligned to an 8 byte boundary. const alignedEnd = (start + toRead) & ~7; const alignedStart = roundUpToMultipleOf8(start + bytesRead); if (alignedEnd - alignedStart >= kMinPoolSpace) poolFragments.push(thisPool.slice(alignedStart, alignedEnd)); } if (bytesRead > 0) { this.bytesRead += bytesRead; b = thisPool.slice(start, start + bytesRead); } // Move the pool positions, and internal position for reading. this.pos += bytesRead; this.push(b); }); pool.used = roundUpToMultipleOf8(pool.used + toRead); }; ReadStream.prototype._destroy = function(err, cb) { if (this._opening && !Buffer.isBuffer(this.handle)) { this.once('open', closeStream.bind(null, this, cb, err)); return; } closeStream(this, cb, err); this.handle = null; this._opening = false; }; function closeStream(stream, cb, err) { if (!stream.handle) return onclose(); stream.sftp.close(stream.handle, onclose); function onclose(er) { er = er || err; cb(er); stream.isClosed = true; if (!er) stream.emit('close'); } } ReadStream.prototype.close = function(cb) { this.destroy(null, cb); }; Object.defineProperty(ReadStream.prototype, 'pending', { get() { return this.handle === null; }, configurable: true }); // TODO: add `concurrency` setting to allow more than one in-flight WRITE // request to server to improve throughput function WriteStream(sftp, path, options) { if (options === undefined) options = {}; else if (typeof options === 'string') options = { encoding: options }; else if (options === null || typeof options !== 'object') throw new TypeError('"options" argument must be a string or an object'); else options = Object.create(options); // For backwards compat do not emit close on destroy. options.emitClose = false; options.autoDestroy = false; // Node 14 major change. WritableStream.call(this, options); this.path = path; this.flags = options.flags === undefined ? 'w' : options.flags; this.mode = options.mode === undefined ? 0o666 : options.mode; this.start = options.start; this.autoClose = options.autoClose === undefined ? true : options.autoClose; this.pos = 0; this.bytesWritten = 0; this.isClosed = false; this.handle = options.handle === undefined ? null : options.handle; this.sftp = sftp; this._opening = false; if (this.start !== undefined) { checkPosition(this.start, 'start'); this.pos = this.start; } if (options.encoding) this.setDefaultEncoding(options.encoding); // Node v6.x only this.on('finish', function() { if (this._writableState.finalCalled) return; if (this.autoClose) this.destroy(); }); if (!Buffer.isBuffer(this.handle)) this.open(); } inherits(WriteStream, WritableStream); WriteStream.prototype._final = function(cb) { if (this.autoClose) this.destroy(); cb(); }; WriteStream.prototype.open = function() { if (this._opening) return; this._opening = true; this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { this._opening = false; if (er) { this.emit('error', er); if (this.autoClose) this.destroy(); return; } this.handle = handle; const tryAgain = (err) => { if (err) { // Try chmod() for sftp servers that may not support fchmod() for // whatever reason this.sftp.chmod(this.path, this.mode, (err_) => tryAgain()); return; } // SFTPv3 requires absolute offsets, no matter the open flag used if (this.flags[0] === 'a') { const tryStat = (err, st) => { if (err) { // Try stat() for sftp servers that may not support fstat() for // whatever reason this.sftp.stat(this.path, (err_, st_) => { if (err_) { this.destroy(); this.emit('error', err); return; } tryStat(null, st_); }); return; } this.pos = st.size; this.emit('open', handle); this.emit('ready'); }; this.sftp.fstat(handle, tryStat); return; } this.emit('open', handle); this.emit('ready'); }; this.sftp.fchmod(handle, this.mode, tryAgain); }); }; WriteStream.prototype._write = function(data, encoding, cb) { if (!Buffer.isBuffer(data)) { const err = new ERR_INVALID_ARG_TYPE('data', 'Buffer', data); return this.emit('error', err); } if (!Buffer.isBuffer(this.handle)) { return this.once('open', function() { this._write(data, encoding, cb); }); } this.sftp.write(this.handle, data, 0, data.length, this.pos, (er, bytes) => { if (er) { if (this.autoClose) this.destroy(); return cb(er); } this.bytesWritten += bytes; cb(); }); this.pos += data.length; }; WriteStream.prototype._writev = function(data, cb) { if (!Buffer.isBuffer(this.handle)) { return this.once('open', function() { this._writev(data, cb); }); } const sftp = this.sftp; const handle = this.handle; let writesLeft = data.length; const onwrite = (er, bytes) => { if (er) { this.destroy(); return cb(er); } this.bytesWritten += bytes; if (--writesLeft === 0) cb(); }; // TODO: try to combine chunks to reduce number of requests to the server? for (let i = 0; i < data.length; ++i) { const chunk = data[i].chunk; sftp.write(handle, chunk, 0, chunk.length, this.pos, onwrite); this.pos += chunk.length; } }; if (typeof WritableStream.prototype.destroy !== 'function') WriteStream.prototype.destroy = ReadStream.prototype.destroy; WriteStream.prototype._destroy = ReadStream.prototype._destroy; WriteStream.prototype.close = function(cb) { if (cb) { if (this.isClosed) { process.nextTick(cb); return; } this.on('close', cb); } // If we are not autoClosing, we should call // destroy on 'finish'. if (!this.autoClose) this.on('finish', this.destroy.bind(this)); this.end(); }; // There is no shutdown() for files. WriteStream.prototype.destroySoon = WriteStream.prototype.end; Object.defineProperty(WriteStream.prototype, 'pending', { get() { return this.handle === null; }, configurable: true }); // ============================================================================= module.exports = { flagsToString, OPEN_MODE, SFTP, Stats, STATUS_CODE, stringToFlags, }; /***/ }), /***/ 3190: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const crypto = __webpack_require__(6113); let cpuInfo; try { cpuInfo = __webpack_require__(75487)(); } catch {} const { bindingAvailable, CIPHER_INFO, MAC_INFO } = __webpack_require__(83877); const eddsaSupported = (() => { if (typeof crypto.sign === 'function' && typeof crypto.verify === 'function') { const key = '-----BEGIN PRIVATE KEY-----\r\nMC4CAQAwBQYDK2VwBCIEIHKj+sVa9WcD' + '/q2DJUJaf43Kptc8xYuUQA4bOFj9vC8T\r\n-----END PRIVATE KEY-----'; const data = Buffer.from('a'); let sig; let verified; try { sig = crypto.sign(null, data, key); verified = crypto.verify(null, data, key, sig); } catch {} return (Buffer.isBuffer(sig) && sig.length === 64 && verified === true); } return false; })(); const curve25519Supported = (typeof crypto.diffieHellman === 'function' && typeof crypto.generateKeyPairSync === 'function' && typeof crypto.createPublicKey === 'function'); const DEFAULT_KEX = [ // https://tools.ietf.org/html/rfc5656#section-10.1 'ecdh-sha2-nistp256', 'ecdh-sha2-nistp384', 'ecdh-sha2-nistp521', // https://tools.ietf.org/html/rfc4419#section-4 'diffie-hellman-group-exchange-sha256', // https://tools.ietf.org/html/rfc8268 'diffie-hellman-group14-sha256', 'diffie-hellman-group15-sha512', 'diffie-hellman-group16-sha512', 'diffie-hellman-group17-sha512', 'diffie-hellman-group18-sha512', ]; if (curve25519Supported) { DEFAULT_KEX.unshift('curve25519-sha256'); DEFAULT_KEX.unshift('curve25519-sha256@libssh.org'); } const SUPPORTED_KEX = DEFAULT_KEX.concat([ // https://tools.ietf.org/html/rfc4419#section-4 'diffie-hellman-group-exchange-sha1', 'diffie-hellman-group14-sha1', // REQUIRED 'diffie-hellman-group1-sha1', // REQUIRED ]); const DEFAULT_SERVER_HOST_KEY = [ 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', 'ecdsa-sha2-nistp521', 'rsa-sha2-512', // RFC 8332 'rsa-sha2-256', // RFC 8332 'ssh-rsa', ]; if (eddsaSupported) DEFAULT_SERVER_HOST_KEY.unshift('ssh-ed25519'); const SUPPORTED_SERVER_HOST_KEY = DEFAULT_SERVER_HOST_KEY.concat([ 'ssh-dss', ]); const canUseCipher = (() => { const ciphers = crypto.getCiphers(); return (name) => ciphers.includes(CIPHER_INFO[name].sslName); })(); let DEFAULT_CIPHER = [ // http://tools.ietf.org/html/rfc5647 'aes128-gcm@openssh.com', 'aes256-gcm@openssh.com', // http://tools.ietf.org/html/rfc4344#section-4 'aes128-ctr', 'aes192-ctr', 'aes256-ctr', ]; if (cpuInfo && cpuInfo.flags && !cpuInfo.flags.aes) { // We know for sure the CPU does not support AES acceleration if (bindingAvailable) DEFAULT_CIPHER.unshift('chacha20-poly1305@openssh.com'); else DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com'); } else if (bindingAvailable && cpuInfo && cpuInfo.arch === 'x86') { // Places chacha20-poly1305 immediately after GCM ciphers since GCM ciphers // seem to outperform it on x86, but it seems to be faster than CTR ciphers DEFAULT_CIPHER.splice(4, 0, 'chacha20-poly1305@openssh.com'); } else { DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com'); } DEFAULT_CIPHER = DEFAULT_CIPHER.filter(canUseCipher); const SUPPORTED_CIPHER = DEFAULT_CIPHER.concat([ 'aes256-cbc', 'aes192-cbc', 'aes128-cbc', 'blowfish-cbc', '3des-cbc', 'aes128-gcm', 'aes256-gcm', // http://tools.ietf.org/html/rfc4345#section-4: 'arcfour256', 'arcfour128', 'cast128-cbc', 'arcfour', ].filter(canUseCipher)); const canUseMAC = (() => { const hashes = crypto.getHashes(); return (name) => hashes.includes(MAC_INFO[name].sslName); })(); const DEFAULT_MAC = [ 'hmac-sha2-256-etm@openssh.com', 'hmac-sha2-512-etm@openssh.com', 'hmac-sha1-etm@openssh.com', 'hmac-sha2-256', 'hmac-sha2-512', 'hmac-sha1', ].filter(canUseMAC); const SUPPORTED_MAC = DEFAULT_MAC.concat([ 'hmac-md5', 'hmac-sha2-256-96', // first 96 bits of HMAC-SHA256 'hmac-sha2-512-96', // first 96 bits of HMAC-SHA512 'hmac-ripemd160', 'hmac-sha1-96', // first 96 bits of HMAC-SHA1 'hmac-md5-96', // first 96 bits of HMAC-MD5 ].filter(canUseMAC)); const DEFAULT_COMPRESSION = [ 'none', 'zlib@openssh.com', // ZLIB (LZ77) compression, except // compression/decompression does not start until after // successful user authentication 'zlib', // ZLIB (LZ77) compression ]; const SUPPORTED_COMPRESSION = DEFAULT_COMPRESSION.concat([ ]); const COMPAT = { BAD_DHGEX: 1 << 0, OLD_EXIT: 1 << 1, DYN_RPORT_BUG: 1 << 2, BUG_DHGEX_LARGE: 1 << 3, IMPLY_RSA_SHA2_SIGALGS: 1 << 4, }; module.exports = { MESSAGE: { // Transport layer protocol -- generic (1-19) DISCONNECT: 1, IGNORE: 2, UNIMPLEMENTED: 3, DEBUG: 4, SERVICE_REQUEST: 5, SERVICE_ACCEPT: 6, EXT_INFO: 7, // RFC 8308 // Transport layer protocol -- algorithm negotiation (20-29) KEXINIT: 20, NEWKEYS: 21, // Transport layer protocol -- key exchange method-specific (30-49) KEXDH_INIT: 30, KEXDH_REPLY: 31, KEXDH_GEX_GROUP: 31, KEXDH_GEX_INIT: 32, KEXDH_GEX_REPLY: 33, KEXDH_GEX_REQUEST: 34, KEXECDH_INIT: 30, KEXECDH_REPLY: 31, // User auth protocol -- generic (50-59) USERAUTH_REQUEST: 50, USERAUTH_FAILURE: 51, USERAUTH_SUCCESS: 52, USERAUTH_BANNER: 53, // User auth protocol -- user auth method-specific (60-79) USERAUTH_PASSWD_CHANGEREQ: 60, USERAUTH_PK_OK: 60, USERAUTH_INFO_REQUEST: 60, USERAUTH_INFO_RESPONSE: 61, // Connection protocol -- generic (80-89) GLOBAL_REQUEST: 80, REQUEST_SUCCESS: 81, REQUEST_FAILURE: 82, // Connection protocol -- channel-related (90-127) CHANNEL_OPEN: 90, CHANNEL_OPEN_CONFIRMATION: 91, CHANNEL_OPEN_FAILURE: 92, CHANNEL_WINDOW_ADJUST: 93, CHANNEL_DATA: 94, CHANNEL_EXTENDED_DATA: 95, CHANNEL_EOF: 96, CHANNEL_CLOSE: 97, CHANNEL_REQUEST: 98, CHANNEL_SUCCESS: 99, CHANNEL_FAILURE: 100 // Reserved for client protocols (128-191) // Local extensions (192-155) }, DISCONNECT_REASON: { HOST_NOT_ALLOWED_TO_CONNECT: 1, PROTOCOL_ERROR: 2, KEY_EXCHANGE_FAILED: 3, RESERVED: 4, MAC_ERROR: 5, COMPRESSION_ERROR: 6, SERVICE_NOT_AVAILABLE: 7, PROTOCOL_VERSION_NOT_SUPPORTED: 8, HOST_KEY_NOT_VERIFIABLE: 9, CONNECTION_LOST: 10, BY_APPLICATION: 11, TOO_MANY_CONNECTIONS: 12, AUTH_CANCELED_BY_USER: 13, NO_MORE_AUTH_METHODS_AVAILABLE: 14, ILLEGAL_USER_NAME: 15, }, DISCONNECT_REASON_STR: undefined, CHANNEL_OPEN_FAILURE: { ADMINISTRATIVELY_PROHIBITED: 1, CONNECT_FAILED: 2, UNKNOWN_CHANNEL_TYPE: 3, RESOURCE_SHORTAGE: 4 }, TERMINAL_MODE: { TTY_OP_END: 0, // Indicates end of options. VINTR: 1, // Interrupt character; 255 if none. Similarly for the // other characters. Not all of these characters are // supported on all systems. VQUIT: 2, // The quit character (sends SIGQUIT signal on POSIX // systems). VERASE: 3, // Erase the character to left of the cursor. VKILL: 4, // Kill the current input line. VEOF: 5, // End-of-file character (sends EOF from the // terminal). VEOL: 6, // End-of-line character in addition to carriage // return and/or linefeed. VEOL2: 7, // Additional end-of-line character. VSTART: 8, // Continues paused output (normally control-Q). VSTOP: 9, // Pauses output (normally control-S). VSUSP: 10, // Suspends the current program. VDSUSP: 11, // Another suspend character. VREPRINT: 12, // Reprints the current input line. VWERASE: 13, // Erases a word left of cursor. VLNEXT: 14, // Enter the next character typed literally, even if // it is a special character VFLUSH: 15, // Character to flush output. VSWTCH: 16, // Switch to a different shell layer. VSTATUS: 17, // Prints system status line (load, command, pid, // etc). VDISCARD: 18, // Toggles the flushing of terminal output. IGNPAR: 30, // The ignore parity flag. The parameter SHOULD be 0 // if this flag is FALSE, and 1 if it is TRUE. PARMRK: 31, // Mark parity and framing errors. INPCK: 32, // Enable checking of parity errors. ISTRIP: 33, // Strip 8th bit off characters. INLCR: 34, // Map NL into CR on input. IGNCR: 35, // Ignore CR on input. ICRNL: 36, // Map CR to NL on input. IUCLC: 37, // Translate uppercase characters to lowercase. IXON: 38, // Enable output flow control. IXANY: 39, // Any char will restart after stop. IXOFF: 40, // Enable input flow control. IMAXBEL: 41, // Ring bell on input queue full. ISIG: 50, // Enable signals INTR, QUIT, [D]SUSP. ICANON: 51, // Canonicalize input lines. XCASE: 52, // Enable input and output of uppercase characters by // preceding their lowercase equivalents with "\". ECHO: 53, // Enable echoing. ECHOE: 54, // Visually erase chars. ECHOK: 55, // Kill character discards current line. ECHONL: 56, // Echo NL even if ECHO is off. NOFLSH: 57, // Don't flush after interrupt. TOSTOP: 58, // Stop background jobs from output. IEXTEN: 59, // Enable extensions. ECHOCTL: 60, // Echo control characters as ^(Char). ECHOKE: 61, // Visual erase for line kill. PENDIN: 62, // Retype pending input. OPOST: 70, // Enable output processing. OLCUC: 71, // Convert lowercase to uppercase. ONLCR: 72, // Map NL to CR-NL. OCRNL: 73, // Translate carriage return to newline (output). ONOCR: 74, // Translate newline to carriage return-newline // (output). ONLRET: 75, // Newline performs a carriage return (output). CS7: 90, // 7 bit mode. CS8: 91, // 8 bit mode. PARENB: 92, // Parity enable. PARODD: 93, // Odd parity, else even. TTY_OP_ISPEED: 128, // Specifies the input baud rate in bits per second. TTY_OP_OSPEED: 129, // Specifies the output baud rate in bits per second. }, CHANNEL_EXTENDED_DATATYPE: { STDERR: 1, }, SIGNALS: [ 'ABRT', 'ALRM', 'FPE', 'HUP', 'ILL', 'INT', 'QUIT', 'SEGV', 'TERM', 'USR1', 'USR2', 'KILL', 'PIPE' ].reduce((cur, val) => ({ ...cur, [val]: 1 }), {}), COMPAT, COMPAT_CHECKS: [ [ 'Cisco-1.25', COMPAT.BAD_DHGEX ], [ /^Cisco-1[.]/, COMPAT.BUG_DHGEX_LARGE ], [ /^[0-9.]+$/, COMPAT.OLD_EXIT ], // old SSH.com implementations [ /^OpenSSH_5[.][0-9]+/, COMPAT.DYN_RPORT_BUG ], [ /^OpenSSH_7[.]4/, COMPAT.IMPLY_RSA_SHA2_SIGALGS ], ], // KEX proposal-related DEFAULT_KEX, SUPPORTED_KEX, DEFAULT_SERVER_HOST_KEY, SUPPORTED_SERVER_HOST_KEY, DEFAULT_CIPHER, SUPPORTED_CIPHER, DEFAULT_MAC, SUPPORTED_MAC, DEFAULT_COMPRESSION, SUPPORTED_COMPRESSION, curve25519Supported, eddsaSupported, }; module.exports.DISCONNECT_REASON_BY_VALUE = Array.from(Object.entries(module.exports.DISCONNECT_REASON)) .reduce((obj, [key, value]) => ({ ...obj, [value]: key }), {}); /***/ }), /***/ 83877: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // TODO: // * make max packet size configurable // * if decompression is enabled, use `._packet` in decipher instances as // input to (sync) zlib inflater with appropriate offset and length to // avoid an additional copy of payload data before inflation // * factor decompression status into packet length checks const { createCipheriv, createDecipheriv, createHmac, randomFillSync, timingSafeEqual } = __webpack_require__(6113); const { readUInt32BE, writeUInt32BE } = __webpack_require__(39205); const FastBuffer = Buffer[Symbol.species]; const MAX_SEQNO = 2 ** 32 - 1; const EMPTY_BUFFER = Buffer.alloc(0); const BUF_INT = Buffer.alloc(4); const DISCARD_CACHE = new Map(); const MAX_PACKET_SIZE = 35000; let binding; let AESGCMCipher; let ChaChaPolyCipher; let GenericCipher; let AESGCMDecipher; let ChaChaPolyDecipher; let GenericDecipher; try { binding = __webpack_require__(52765); ({ AESGCMCipher, ChaChaPolyCipher, GenericCipher, AESGCMDecipher, ChaChaPolyDecipher, GenericDecipher } = binding); } catch {} const CIPHER_STREAM = 1 << 0; const CIPHER_INFO = (() => { function info(sslName, blockLen, keyLen, ivLen, authLen, discardLen, flags) { return { sslName, blockLen, keyLen, ivLen: (ivLen !== 0 || (flags & CIPHER_STREAM) ? ivLen : blockLen), authLen, discardLen, stream: !!(flags & CIPHER_STREAM), }; } return { 'chacha20-poly1305@openssh.com': info('chacha20', 8, 64, 0, 16, 0, CIPHER_STREAM), 'aes128-gcm': info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM), 'aes256-gcm': info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM), 'aes128-gcm@openssh.com': info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM), 'aes256-gcm@openssh.com': info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM), 'aes128-cbc': info('aes-128-cbc', 16, 16, 0, 0, 0, 0), 'aes192-cbc': info('aes-192-cbc', 16, 24, 0, 0, 0, 0), 'aes256-cbc': info('aes-256-cbc', 16, 32, 0, 0, 0, 0), 'rijndael-cbc@lysator.liu.se': info('aes-256-cbc', 16, 32, 0, 0, 0, 0), '3des-cbc': info('des-ede3-cbc', 8, 24, 0, 0, 0, 0), 'blowfish-cbc': info('bf-cbc', 8, 16, 0, 0, 0, 0), 'idea-cbc': info('idea-cbc', 8, 16, 0, 0, 0, 0), 'cast128-cbc': info('cast-cbc', 8, 16, 0, 0, 0, 0), 'aes128-ctr': info('aes-128-ctr', 16, 16, 16, 0, 0, CIPHER_STREAM), 'aes192-ctr': info('aes-192-ctr', 16, 24, 16, 0, 0, CIPHER_STREAM), 'aes256-ctr': info('aes-256-ctr', 16, 32, 16, 0, 0, CIPHER_STREAM), '3des-ctr': info('des-ede3', 8, 24, 8, 0, 0, CIPHER_STREAM), 'blowfish-ctr': info('bf-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM), 'cast128-ctr': info('cast5-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM), /* The "arcfour128" algorithm is the RC4 cipher, as described in [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream generated by the cipher MUST be discarded, and the first byte of the first encrypted packet MUST be encrypted using the 1537th byte of keystream. -- http://tools.ietf.org/html/rfc4345#section-4 */ 'arcfour': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM), 'arcfour128': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM), 'arcfour256': info('rc4', 8, 32, 0, 0, 1536, CIPHER_STREAM), 'arcfour512': info('rc4', 8, 64, 0, 0, 1536, CIPHER_STREAM), }; })(); const MAC_INFO = (() => { function info(sslName, len, actualLen, isETM) { return { sslName, len, actualLen, isETM, }; } return { 'hmac-md5': info('md5', 16, 16, false), 'hmac-md5-96': info('md5', 16, 12, false), 'hmac-ripemd160': info('ripemd160', 20, 20, false), 'hmac-sha1': info('sha1', 20, 20, false), 'hmac-sha1-etm@openssh.com': info('sha1', 20, 20, true), 'hmac-sha1-96': info('sha1', 20, 12, false), 'hmac-sha2-256': info('sha256', 32, 32, false), 'hmac-sha2-256-etm@openssh.com': info('sha256', 32, 32, true), 'hmac-sha2-256-96': info('sha256', 32, 12, false), 'hmac-sha2-512': info('sha512', 64, 64, false), 'hmac-sha2-512-etm@openssh.com': info('sha512', 64, 64, true), 'hmac-sha2-512-96': info('sha512', 64, 12, false), }; })(); // Should only_be used during the initial handshake class NullCipher { constructor(seqno, onWrite) { this.outSeqno = seqno; this._onWrite = onWrite; this._dead = false; } free() { this._dead = true; } allocPacket(payloadLen) { let pktLen = 4 + 1 + payloadLen; let padLen = 8 - (pktLen & (8 - 1)); if (padLen < 4) padLen += 8; pktLen += padLen; const packet = Buffer.allocUnsafe(pktLen); writeUInt32BE(packet, pktLen - 4, 0); packet[4] = padLen; randomFillSync(packet, 5 + payloadLen, padLen); return packet; } encrypt(packet) { // `packet` === unencrypted packet if (this._dead) return; this._onWrite(packet); this.outSeqno = (this.outSeqno + 1) >>> 0; } } const POLY1305_ZEROS = Buffer.alloc(32); const POLY1305_OUT_COMPUTE = Buffer.alloc(16); let POLY1305_WASM_MODULE; let POLY1305_RESULT_MALLOC; let poly1305_auth; class ChaChaPolyCipherNative { constructor(config) { const enc = config.outbound; this.outSeqno = enc.seqno; this._onWrite = enc.onWrite; this._encKeyMain = enc.cipherKey.slice(0, 32); this._encKeyPktLen = enc.cipherKey.slice(32); this._dead = false; } free() { this._dead = true; } allocPacket(payloadLen) { let pktLen = 4 + 1 + payloadLen; let padLen = 8 - ((pktLen - 4) & (8 - 1)); if (padLen < 4) padLen += 8; pktLen += padLen; const packet = Buffer.allocUnsafe(pktLen); writeUInt32BE(packet, pktLen - 4, 0); packet[4] = padLen; randomFillSync(packet, 5 + payloadLen, padLen); return packet; } encrypt(packet) { // `packet` === unencrypted packet if (this._dead) return; // Generate Poly1305 key POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) writeUInt32BE(POLY1305_OUT_COMPUTE, this.outSeqno, 12); const polyKey = createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE) .update(POLY1305_ZEROS); // Encrypt packet length const pktLenEnc = createCipheriv('chacha20', this._encKeyPktLen, POLY1305_OUT_COMPUTE) .update(packet.slice(0, 4)); this._onWrite(pktLenEnc); // Encrypt rest of packet POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian) const payloadEnc = createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE) .update(packet.slice(4)); this._onWrite(payloadEnc); // Calculate Poly1305 MAC poly1305_auth(POLY1305_RESULT_MALLOC, pktLenEnc, pktLenEnc.length, payloadEnc, payloadEnc.length, polyKey); const mac = Buffer.allocUnsafe(16); mac.set( new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer, POLY1305_RESULT_MALLOC, 16), 0 ); this._onWrite(mac); this.outSeqno = (this.outSeqno + 1) >>> 0; } } class ChaChaPolyCipherBinding { constructor(config) { const enc = config.outbound; this.outSeqno = enc.seqno; this._onWrite = enc.onWrite; this._instance = new ChaChaPolyCipher(enc.cipherKey); this._dead = false; } free() { this._dead = true; this._instance.free(); } allocPacket(payloadLen) { let pktLen = 4 + 1 + payloadLen; let padLen = 8 - ((pktLen - 4) & (8 - 1)); if (padLen < 4) padLen += 8; pktLen += padLen; const packet = Buffer.allocUnsafe(pktLen + 16/* MAC */); writeUInt32BE(packet, pktLen - 4, 0); packet[4] = padLen; randomFillSync(packet, 5 + payloadLen, padLen); return packet; } encrypt(packet) { // `packet` === unencrypted packet if (this._dead) return; // Encrypts in-place this._instance.encrypt(packet, this.outSeqno); this._onWrite(packet); this.outSeqno = (this.outSeqno + 1) >>> 0; } } class AESGCMCipherNative { constructor(config) { const enc = config.outbound; this.outSeqno = enc.seqno; this._onWrite = enc.onWrite; this._encSSLName = enc.cipherInfo.sslName; this._encKey = enc.cipherKey; this._encIV = enc.cipherIV; this._dead = false; } free() { this._dead = true; } allocPacket(payloadLen) { let pktLen = 4 + 1 + payloadLen; let padLen = 16 - ((pktLen - 4) & (16 - 1)); if (padLen < 4) padLen += 16; pktLen += padLen; const packet = Buffer.allocUnsafe(pktLen); writeUInt32BE(packet, pktLen - 4, 0); packet[4] = padLen; randomFillSync(packet, 5 + payloadLen, padLen); return packet; } encrypt(packet) { // `packet` === unencrypted packet if (this._dead) return; const cipher = createCipheriv(this._encSSLName, this._encKey, this._encIV); cipher.setAutoPadding(false); const lenData = packet.slice(0, 4); cipher.setAAD(lenData); this._onWrite(lenData); // Encrypt pad length, payload, and padding const encrypted = cipher.update(packet.slice(4)); this._onWrite(encrypted); const final = cipher.final(); // XXX: final.length === 0 always? if (final.length) this._onWrite(final); // Generate MAC const tag = cipher.getAuthTag(); this._onWrite(tag); // Increment counter in IV by 1 for next packet ivIncrement(this._encIV); this.outSeqno = (this.outSeqno + 1) >>> 0; } } class AESGCMCipherBinding { constructor(config) { const enc = config.outbound; this.outSeqno = enc.seqno; this._onWrite = enc.onWrite; this._instance = new AESGCMCipher(enc.cipherInfo.sslName, enc.cipherKey, enc.cipherIV); this._dead = false; } free() { this._dead = true; this._instance.free(); } allocPacket(payloadLen) { let pktLen = 4 + 1 + payloadLen; let padLen = 16 - ((pktLen - 4) & (16 - 1)); if (padLen < 4) padLen += 16; pktLen += padLen; const packet = Buffer.allocUnsafe(pktLen + 16/* authTag */); writeUInt32BE(packet, pktLen - 4, 0); packet[4] = padLen; randomFillSync(packet, 5 + payloadLen, padLen); return packet; } encrypt(packet) { // `packet` === unencrypted packet if (this._dead) return; // Encrypts in-place this._instance.encrypt(packet); this._onWrite(packet); this.outSeqno = (this.outSeqno + 1) >>> 0; } } class GenericCipherNative { constructor(config) { const enc = config.outbound; this.outSeqno = enc.seqno; this._onWrite = enc.onWrite; this._encBlockLen = enc.cipherInfo.blockLen; this._cipherInstance = createCipheriv(enc.cipherInfo.sslName, enc.cipherKey, enc.cipherIV); this._macSSLName = enc.macInfo.sslName; this._macKey = enc.macKey; this._macActualLen = enc.macInfo.actualLen; this._macETM = enc.macInfo.isETM; this._aadLen = (this._macETM ? 4 : 0); this._dead = false; const discardLen = enc.cipherInfo.discardLen; if (discardLen) { let discard = DISCARD_CACHE.get(discardLen); if (discard === undefined) { discard = Buffer.alloc(discardLen); DISCARD_CACHE.set(discardLen, discard); } this._cipherInstance.update(discard); } } free() { this._dead = true; } allocPacket(payloadLen) { const blockLen = this._encBlockLen; let pktLen = 4 + 1 + payloadLen; let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1)); if (padLen < 4) padLen += blockLen; pktLen += padLen; const packet = Buffer.allocUnsafe(pktLen); writeUInt32BE(packet, pktLen - 4, 0); packet[4] = padLen; randomFillSync(packet, 5 + payloadLen, padLen); return packet; } encrypt(packet) { // `packet` === unencrypted packet if (this._dead) return; let mac; if (this._macETM) { // Encrypt pad length, payload, and padding const lenBytes = new Uint8Array(packet.buffer, packet.byteOffset, 4); const encrypted = this._cipherInstance.update( new Uint8Array(packet.buffer, packet.byteOffset + 4, packet.length - 4) ); this._onWrite(lenBytes); this._onWrite(encrypted); // TODO: look into storing seqno as 4-byte buffer and incrementing like we // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time mac = createHmac(this._macSSLName, this._macKey); writeUInt32BE(BUF_INT, this.outSeqno, 0); mac.update(BUF_INT); mac.update(lenBytes); mac.update(encrypted); } else { // Encrypt length field, pad length, payload, and padding const encrypted = this._cipherInstance.update(packet); this._onWrite(encrypted); // TODO: look into storing seqno as 4-byte buffer and incrementing like we // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time mac = createHmac(this._macSSLName, this._macKey); writeUInt32BE(BUF_INT, this.outSeqno, 0); mac.update(BUF_INT); mac.update(packet); } let digest = mac.digest(); if (digest.length > this._macActualLen) digest = digest.slice(0, this._macActualLen); this._onWrite(digest); this.outSeqno = (this.outSeqno + 1) >>> 0; } } class GenericCipherBinding { constructor(config) { const enc = config.outbound; this.outSeqno = enc.seqno; this._onWrite = enc.onWrite; this._encBlockLen = enc.cipherInfo.blockLen; this._macLen = enc.macInfo.len; this._macActualLen = enc.macInfo.actualLen; this._aadLen = (enc.macInfo.isETM ? 4 : 0); this._instance = new GenericCipher(enc.cipherInfo.sslName, enc.cipherKey, enc.cipherIV, enc.macInfo.sslName, enc.macKey, enc.macInfo.isETM); this._dead = false; } free() { this._dead = true; this._instance.free(); } allocPacket(payloadLen) { const blockLen = this._encBlockLen; let pktLen = 4 + 1 + payloadLen; let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1)); if (padLen < 4) padLen += blockLen; pktLen += padLen; const packet = Buffer.allocUnsafe(pktLen + this._macLen); writeUInt32BE(packet, pktLen - 4, 0); packet[4] = padLen; randomFillSync(packet, 5 + payloadLen, padLen); return packet; } encrypt(packet) { // `packet` === unencrypted packet if (this._dead) return; // Encrypts in-place this._instance.encrypt(packet, this.outSeqno); if (this._macActualLen < this._macLen) { packet = new FastBuffer(packet.buffer, packet.byteOffset, (packet.length - (this._macLen - this._macActualLen))); } this._onWrite(packet); this.outSeqno = (this.outSeqno + 1) >>> 0; } } class NullDecipher { constructor(seqno, onPayload) { this.inSeqno = seqno; this._onPayload = onPayload; this._len = 0; this._lenBytes = 0; this._packet = null; this._packetPos = 0; } free() {} decrypt(data, p, dataLen) { while (p < dataLen) { // Read packet length if (this._lenBytes < 4) { let nb = Math.min(4 - this._lenBytes, dataLen - p); this._lenBytes += nb; while (nb--) this._len = (this._len << 8) + data[p++]; if (this._lenBytes < 4) return; if (this._len > MAX_PACKET_SIZE || this._len < 8 || (4 + this._len & 7) !== 0) { throw new Error('Bad packet length'); } if (p >= dataLen) return; } // Read padding length, payload, and padding if (this._packetPos < this._len) { const nb = Math.min(this._len - this._packetPos, dataLen - p); let chunk; if (p !== 0 || nb !== dataLen) chunk = new Uint8Array(data.buffer, data.byteOffset + p, nb); else chunk = data; if (nb === this._len) { this._packet = chunk; } else { if (!this._packet) this._packet = Buffer.allocUnsafe(this._len); this._packet.set(chunk, this._packetPos); } p += nb; this._packetPos += nb; if (this._packetPos < this._len) return; } const payload = (!this._packet ? EMPTY_BUFFER : new FastBuffer(this._packet.buffer, this._packet.byteOffset + 1, this._packet.length - this._packet[0] - 1)); // Prepare for next packet this.inSeqno = (this.inSeqno + 1) >>> 0; this._len = 0; this._lenBytes = 0; this._packet = null; this._packetPos = 0; { const ret = this._onPayload(payload); if (ret !== undefined) return (ret === false ? p : ret); } } } } class ChaChaPolyDecipherNative { constructor(config) { const dec = config.inbound; this.inSeqno = dec.seqno; this._onPayload = dec.onPayload; this._decKeyMain = dec.decipherKey.slice(0, 32); this._decKeyPktLen = dec.decipherKey.slice(32); this._len = 0; this._lenBuf = Buffer.alloc(4); this._lenPos = 0; this._packet = null; this._pktLen = 0; this._mac = Buffer.allocUnsafe(16); this._calcMac = Buffer.allocUnsafe(16); this._macPos = 0; } free() {} decrypt(data, p, dataLen) { // `data` === encrypted data while (p < dataLen) { // Read packet length if (this._lenPos < 4) { let nb = Math.min(4 - this._lenPos, dataLen - p); while (nb--) this._lenBuf[this._lenPos++] = data[p++]; if (this._lenPos < 4) return; POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12); const decLenBytes = createDecipheriv('chacha20', this._decKeyPktLen, POLY1305_OUT_COMPUTE) .update(this._lenBuf); this._len = readUInt32BE(decLenBytes, 0); if (this._len > MAX_PACKET_SIZE || this._len < 8 || (this._len & 7) !== 0) { throw new Error('Bad packet length'); } } // Read padding length, payload, and padding if (this._pktLen < this._len) { if (p >= dataLen) return; const nb = Math.min(this._len - this._pktLen, dataLen - p); let encrypted; if (p !== 0 || nb !== dataLen) encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); else encrypted = data; if (nb === this._len) { this._packet = encrypted; } else { if (!this._packet) this._packet = Buffer.allocUnsafe(this._len); this._packet.set(encrypted, this._pktLen); } p += nb; this._pktLen += nb; if (this._pktLen < this._len || p >= dataLen) return; } // Read Poly1305 MAC { const nb = Math.min(16 - this._macPos, dataLen - p); // TODO: avoid copying if entire MAC is in current chunk if (p !== 0 || nb !== dataLen) { this._mac.set( new Uint8Array(data.buffer, data.byteOffset + p, nb), this._macPos ); } else { this._mac.set(data, this._macPos); } p += nb; this._macPos += nb; if (this._macPos < 16) return; } // Generate Poly1305 key POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12); const polyKey = createCipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE) .update(POLY1305_ZEROS); // Calculate and compare Poly1305 MACs poly1305_auth(POLY1305_RESULT_MALLOC, this._lenBuf, 4, this._packet, this._packet.length, polyKey); this._calcMac.set( new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer, POLY1305_RESULT_MALLOC, 16), 0 ); if (!timingSafeEqual(this._calcMac, this._mac)) throw new Error('Invalid MAC'); // Decrypt packet POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian) const packet = createDecipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE) .update(this._packet); const payload = new FastBuffer(packet.buffer, packet.byteOffset + 1, packet.length - packet[0] - 1); // Prepare for next packet this.inSeqno = (this.inSeqno + 1) >>> 0; this._len = 0; this._lenPos = 0; this._packet = null; this._pktLen = 0; this._macPos = 0; { const ret = this._onPayload(payload); if (ret !== undefined) return (ret === false ? p : ret); } } } } class ChaChaPolyDecipherBinding { constructor(config) { const dec = config.inbound; this.inSeqno = dec.seqno; this._onPayload = dec.onPayload; this._instance = new ChaChaPolyDecipher(dec.decipherKey); this._len = 0; this._lenBuf = Buffer.alloc(4); this._lenPos = 0; this._packet = null; this._pktLen = 0; this._mac = Buffer.allocUnsafe(16); this._macPos = 0; } free() { this._instance.free(); } decrypt(data, p, dataLen) { // `data` === encrypted data while (p < dataLen) { // Read packet length if (this._lenPos < 4) { let nb = Math.min(4 - this._lenPos, dataLen - p); while (nb--) this._lenBuf[this._lenPos++] = data[p++]; if (this._lenPos < 4) return; this._len = this._instance.decryptLen(this._lenBuf, this.inSeqno); if (this._len > MAX_PACKET_SIZE || this._len < 8 || (this._len & 7) !== 0) { throw new Error('Bad packet length'); } if (p >= dataLen) return; } // Read padding length, payload, and padding if (this._pktLen < this._len) { const nb = Math.min(this._len - this._pktLen, dataLen - p); let encrypted; if (p !== 0 || nb !== dataLen) encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); else encrypted = data; if (nb === this._len) { this._packet = encrypted; } else { if (!this._packet) this._packet = Buffer.allocUnsafe(this._len); this._packet.set(encrypted, this._pktLen); } p += nb; this._pktLen += nb; if (this._pktLen < this._len || p >= dataLen) return; } // Read Poly1305 MAC { const nb = Math.min(16 - this._macPos, dataLen - p); // TODO: avoid copying if entire MAC is in current chunk if (p !== 0 || nb !== dataLen) { this._mac.set( new Uint8Array(data.buffer, data.byteOffset + p, nb), this._macPos ); } else { this._mac.set(data, this._macPos); } p += nb; this._macPos += nb; if (this._macPos < 16) return; } this._instance.decrypt(this._packet, this._mac, this.inSeqno); const payload = new FastBuffer(this._packet.buffer, this._packet.byteOffset + 1, this._packet.length - this._packet[0] - 1); // Prepare for next packet this.inSeqno = (this.inSeqno + 1) >>> 0; this._len = 0; this._lenPos = 0; this._packet = null; this._pktLen = 0; this._macPos = 0; { const ret = this._onPayload(payload); if (ret !== undefined) return (ret === false ? p : ret); } } } } class AESGCMDecipherNative { constructor(config) { const dec = config.inbound; this.inSeqno = dec.seqno; this._onPayload = dec.onPayload; this._decipherInstance = null; this._decipherSSLName = dec.decipherInfo.sslName; this._decipherKey = dec.decipherKey; this._decipherIV = dec.decipherIV; this._len = 0; this._lenBytes = 0; this._packet = null; this._packetPos = 0; this._pktLen = 0; this._tag = Buffer.allocUnsafe(16); this._tagPos = 0; } free() {} decrypt(data, p, dataLen) { // `data` === encrypted data while (p < dataLen) { // Read packet length (unencrypted, but AAD) if (this._lenBytes < 4) { let nb = Math.min(4 - this._lenBytes, dataLen - p); this._lenBytes += nb; while (nb--) this._len = (this._len << 8) + data[p++]; if (this._lenBytes < 4) return; if ((this._len + 20) > MAX_PACKET_SIZE || this._len < 16 || (this._len & 15) !== 0) { throw new Error('Bad packet length'); } this._decipherInstance = createDecipheriv( this._decipherSSLName, this._decipherKey, this._decipherIV ); this._decipherInstance.setAutoPadding(false); this._decipherInstance.setAAD(intToBytes(this._len)); } // Read padding length, payload, and padding if (this._pktLen < this._len) { if (p >= dataLen) return; const nb = Math.min(this._len - this._pktLen, dataLen - p); let decrypted; if (p !== 0 || nb !== dataLen) { decrypted = this._decipherInstance.update( new Uint8Array(data.buffer, data.byteOffset + p, nb) ); } else { decrypted = this._decipherInstance.update(data); } if (decrypted.length) { if (nb === this._len) { this._packet = decrypted; } else { if (!this._packet) this._packet = Buffer.allocUnsafe(this._len); this._packet.set(decrypted, this._packetPos); } this._packetPos += decrypted.length; } p += nb; this._pktLen += nb; if (this._pktLen < this._len || p >= dataLen) return; } // Read authentication tag { const nb = Math.min(16 - this._tagPos, dataLen - p); if (p !== 0 || nb !== dataLen) { this._tag.set( new Uint8Array(data.buffer, data.byteOffset + p, nb), this._tagPos ); } else { this._tag.set(data, this._tagPos); } p += nb; this._tagPos += nb; if (this._tagPos < 16) return; } { // Verify authentication tag this._decipherInstance.setAuthTag(this._tag); const decrypted = this._decipherInstance.final(); // XXX: this should never output any data since stream ciphers always // return data from .update() and block ciphers must end on a multiple // of the block length, which would have caused an exception to be // thrown if the total input was not... if (decrypted.length) { if (this._packet) this._packet.set(decrypted, this._packetPos); else this._packet = decrypted; } } const payload = (!this._packet ? EMPTY_BUFFER : new FastBuffer(this._packet.buffer, this._packet.byteOffset + 1, this._packet.length - this._packet[0] - 1)); // Prepare for next packet this.inSeqno = (this.inSeqno + 1) >>> 0; ivIncrement(this._decipherIV); this._len = 0; this._lenBytes = 0; this._packet = null; this._packetPos = 0; this._pktLen = 0; this._tagPos = 0; { const ret = this._onPayload(payload); if (ret !== undefined) return (ret === false ? p : ret); } } } } class AESGCMDecipherBinding { constructor(config) { const dec = config.inbound; this.inSeqno = dec.seqno; this._onPayload = dec.onPayload; this._instance = new AESGCMDecipher(dec.decipherInfo.sslName, dec.decipherKey, dec.decipherIV); this._len = 0; this._lenBytes = 0; this._packet = null; this._pktLen = 0; this._tag = Buffer.allocUnsafe(16); this._tagPos = 0; } free() {} decrypt(data, p, dataLen) { // `data` === encrypted data while (p < dataLen) { // Read packet length (unencrypted, but AAD) if (this._lenBytes < 4) { let nb = Math.min(4 - this._lenBytes, dataLen - p); this._lenBytes += nb; while (nb--) this._len = (this._len << 8) + data[p++]; if (this._lenBytes < 4) return; if ((this._len + 20) > MAX_PACKET_SIZE || this._len < 16 || (this._len & 15) !== 0) { throw new Error(`Bad packet length: ${this._len}`); } } // Read padding length, payload, and padding if (this._pktLen < this._len) { if (p >= dataLen) return; const nb = Math.min(this._len - this._pktLen, dataLen - p); let encrypted; if (p !== 0 || nb !== dataLen) encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); else encrypted = data; if (nb === this._len) { this._packet = encrypted; } else { if (!this._packet) this._packet = Buffer.allocUnsafe(this._len); this._packet.set(encrypted, this._pktLen); } p += nb; this._pktLen += nb; if (this._pktLen < this._len || p >= dataLen) return; } // Read authentication tag { const nb = Math.min(16 - this._tagPos, dataLen - p); if (p !== 0 || nb !== dataLen) { this._tag.set( new Uint8Array(data.buffer, data.byteOffset + p, nb), this._tagPos ); } else { this._tag.set(data, this._tagPos); } p += nb; this._tagPos += nb; if (this._tagPos < 16) return; } this._instance.decrypt(this._packet, this._len, this._tag); const payload = new FastBuffer(this._packet.buffer, this._packet.byteOffset + 1, this._packet.length - this._packet[0] - 1); // Prepare for next packet this.inSeqno = (this.inSeqno + 1) >>> 0; this._len = 0; this._lenBytes = 0; this._packet = null; this._pktLen = 0; this._tagPos = 0; { const ret = this._onPayload(payload); if (ret !== undefined) return (ret === false ? p : ret); } } } } // TODO: test incremental .update()s vs. copying to _packet and doing a single // .update() after entire packet read -- a single .update() would allow // verifying MAC before decrypting for ETM MACs class GenericDecipherNative { constructor(config) { const dec = config.inbound; this.inSeqno = dec.seqno; this._onPayload = dec.onPayload; this._decipherInstance = createDecipheriv(dec.decipherInfo.sslName, dec.decipherKey, dec.decipherIV); this._decipherInstance.setAutoPadding(false); this._block = Buffer.allocUnsafe( dec.macInfo.isETM ? 4 : dec.decipherInfo.blockLen ); this._blockSize = dec.decipherInfo.blockLen; this._blockPos = 0; this._len = 0; this._packet = null; this._packetPos = 0; this._pktLen = 0; this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen); this._macPos = 0; this._macSSLName = dec.macInfo.sslName; this._macKey = dec.macKey; this._macActualLen = dec.macInfo.actualLen; this._macETM = dec.macInfo.isETM; this._macInstance = null; const discardLen = dec.decipherInfo.discardLen; if (discardLen) { let discard = DISCARD_CACHE.get(discardLen); if (discard === undefined) { discard = Buffer.alloc(discardLen); DISCARD_CACHE.set(discardLen, discard); } this._decipherInstance.update(discard); } } free() {} decrypt(data, p, dataLen) { // `data` === encrypted data while (p < dataLen) { // Read first encrypted block if (this._blockPos < this._block.length) { const nb = Math.min(this._block.length - this._blockPos, dataLen - p); if (p !== 0 || nb !== dataLen || nb < data.length) { this._block.set( new Uint8Array(data.buffer, data.byteOffset + p, nb), this._blockPos ); } else { this._block.set(data, this._blockPos); } p += nb; this._blockPos += nb; if (this._blockPos < this._block.length) return; let decrypted; let need; if (this._macETM) { this._len = need = readUInt32BE(this._block, 0); } else { // Decrypt first block to get packet length decrypted = this._decipherInstance.update(this._block); this._len = readUInt32BE(decrypted, 0); need = 4 + this._len - this._blockSize; } if (this._len > MAX_PACKET_SIZE || this._len < 5 || (need & (this._blockSize - 1)) !== 0) { throw new Error('Bad packet length'); } // Create MAC up front to calculate in parallel with decryption this._macInstance = createHmac(this._macSSLName, this._macKey); writeUInt32BE(BUF_INT, this.inSeqno, 0); this._macInstance.update(BUF_INT); if (this._macETM) { this._macInstance.update(this._block); } else { this._macInstance.update(new Uint8Array(decrypted.buffer, decrypted.byteOffset, 4)); this._pktLen = decrypted.length - 4; this._packetPos = this._pktLen; this._packet = Buffer.allocUnsafe(this._len); this._packet.set( new Uint8Array(decrypted.buffer, decrypted.byteOffset + 4, this._packetPos), 0 ); } if (p >= dataLen) return; } // Read padding length, payload, and padding if (this._pktLen < this._len) { const nb = Math.min(this._len - this._pktLen, dataLen - p); let encrypted; if (p !== 0 || nb !== dataLen) encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); else encrypted = data; if (this._macETM) this._macInstance.update(encrypted); const decrypted = this._decipherInstance.update(encrypted); if (decrypted.length) { if (nb === this._len) { this._packet = decrypted; } else { if (!this._packet) this._packet = Buffer.allocUnsafe(this._len); this._packet.set(decrypted, this._packetPos); } this._packetPos += decrypted.length; } p += nb; this._pktLen += nb; if (this._pktLen < this._len || p >= dataLen) return; } // Read MAC { const nb = Math.min(this._macActualLen - this._macPos, dataLen - p); if (p !== 0 || nb !== dataLen) { this._mac.set( new Uint8Array(data.buffer, data.byteOffset + p, nb), this._macPos ); } else { this._mac.set(data, this._macPos); } p += nb; this._macPos += nb; if (this._macPos < this._macActualLen) return; } // Verify MAC if (!this._macETM) this._macInstance.update(this._packet); let calculated = this._macInstance.digest(); if (this._macActualLen < calculated.length) { calculated = new Uint8Array(calculated.buffer, calculated.byteOffset, this._macActualLen); } if (!timingSafeEquals(calculated, this._mac)) throw new Error('Invalid MAC'); const payload = new FastBuffer(this._packet.buffer, this._packet.byteOffset + 1, this._packet.length - this._packet[0] - 1); // Prepare for next packet this.inSeqno = (this.inSeqno + 1) >>> 0; this._blockPos = 0; this._len = 0; this._packet = null; this._packetPos = 0; this._pktLen = 0; this._macPos = 0; this._macInstance = null; { const ret = this._onPayload(payload); if (ret !== undefined) return (ret === false ? p : ret); } } } } class GenericDecipherBinding { constructor(config) { const dec = config.inbound; this.inSeqno = dec.seqno; this._onPayload = dec.onPayload; this._instance = new GenericDecipher(dec.decipherInfo.sslName, dec.decipherKey, dec.decipherIV, dec.macInfo.sslName, dec.macKey, dec.macInfo.isETM, dec.macInfo.actualLen); this._block = Buffer.allocUnsafe( dec.macInfo.isETM || dec.decipherInfo.stream ? 4 : dec.decipherInfo.blockLen ); this._blockPos = 0; this._len = 0; this._packet = null; this._pktLen = 0; this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen); this._macPos = 0; this._macActualLen = dec.macInfo.actualLen; this._macETM = dec.macInfo.isETM; } free() { this._instance.free(); } decrypt(data, p, dataLen) { // `data` === encrypted data while (p < dataLen) { // Read first encrypted block if (this._blockPos < this._block.length) { const nb = Math.min(this._block.length - this._blockPos, dataLen - p); if (p !== 0 || nb !== dataLen || nb < data.length) { this._block.set( new Uint8Array(data.buffer, data.byteOffset + p, nb), this._blockPos ); } else { this._block.set(data, this._blockPos); } p += nb; this._blockPos += nb; if (this._blockPos < this._block.length) return; let need; if (this._macETM) { this._len = need = readUInt32BE(this._block, 0); } else { // Decrypt first block to get packet length this._instance.decryptBlock(this._block); this._len = readUInt32BE(this._block, 0); need = 4 + this._len - this._block.length; } if (this._len > MAX_PACKET_SIZE || this._len < 5 || (need & (this._block.length - 1)) !== 0) { throw new Error('Bad packet length'); } if (!this._macETM) { this._pktLen = (this._block.length - 4); if (this._pktLen) { this._packet = Buffer.allocUnsafe(this._len); this._packet.set( new Uint8Array(this._block.buffer, this._block.byteOffset + 4, this._pktLen), 0 ); } } if (p >= dataLen) return; } // Read padding length, payload, and padding if (this._pktLen < this._len) { const nb = Math.min(this._len - this._pktLen, dataLen - p); let encrypted; if (p !== 0 || nb !== dataLen) encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); else encrypted = data; if (nb === this._len) { this._packet = encrypted; } else { if (!this._packet) this._packet = Buffer.allocUnsafe(this._len); this._packet.set(encrypted, this._pktLen); } p += nb; this._pktLen += nb; if (this._pktLen < this._len || p >= dataLen) return; } // Read MAC { const nb = Math.min(this._macActualLen - this._macPos, dataLen - p); if (p !== 0 || nb !== dataLen) { this._mac.set( new Uint8Array(data.buffer, data.byteOffset + p, nb), this._macPos ); } else { this._mac.set(data, this._macPos); } p += nb; this._macPos += nb; if (this._macPos < this._macActualLen) return; } // Decrypt and verify MAC this._instance.decrypt(this._packet, this.inSeqno, this._block, this._mac); const payload = new FastBuffer(this._packet.buffer, this._packet.byteOffset + 1, this._packet.length - this._packet[0] - 1); // Prepare for next packet this.inSeqno = (this.inSeqno + 1) >>> 0; this._blockPos = 0; this._len = 0; this._packet = null; this._pktLen = 0; this._macPos = 0; this._macInstance = null; { const ret = this._onPayload(payload); if (ret !== undefined) return (ret === false ? p : ret); } } } } // Increments unsigned, big endian counter (last 8 bytes) of AES-GCM IV function ivIncrement(iv) { // eslint-disable-next-line no-unused-expressions ++iv[11] >>> 8 && ++iv[10] >>> 8 && ++iv[9] >>> 8 && ++iv[8] >>> 8 && ++iv[7] >>> 8 && ++iv[6] >>> 8 && ++iv[5] >>> 8 && ++iv[4] >>> 8; } const intToBytes = (() => { const ret = Buffer.alloc(4); return (n) => { ret[0] = (n >>> 24); ret[1] = (n >>> 16); ret[2] = (n >>> 8); ret[3] = n; return ret; }; })(); function timingSafeEquals(a, b) { if (a.length !== b.length) { timingSafeEqual(a, a); return false; } return timingSafeEqual(a, b); } function createCipher(config) { if (typeof config !== 'object' || config === null) throw new Error('Invalid config'); if (typeof config.outbound !== 'object' || config.outbound === null) throw new Error('Invalid outbound'); const outbound = config.outbound; if (typeof outbound.onWrite !== 'function') throw new Error('Invalid outbound.onWrite'); if (typeof outbound.cipherInfo !== 'object' || outbound.cipherInfo === null) throw new Error('Invalid outbound.cipherInfo'); if (!Buffer.isBuffer(outbound.cipherKey) || outbound.cipherKey.length !== outbound.cipherInfo.keyLen) { throw new Error('Invalid outbound.cipherKey'); } if (outbound.cipherInfo.ivLen && (!Buffer.isBuffer(outbound.cipherIV) || outbound.cipherIV.length !== outbound.cipherInfo.ivLen)) { throw new Error('Invalid outbound.cipherIV'); } if (typeof outbound.seqno !== 'number' || outbound.seqno < 0 || outbound.seqno > MAX_SEQNO) { throw new Error('Invalid outbound.seqno'); } const forceNative = !!outbound.forceNative; switch (outbound.cipherInfo.sslName) { case 'aes-128-gcm': case 'aes-256-gcm': return (AESGCMCipher && !forceNative ? new AESGCMCipherBinding(config) : new AESGCMCipherNative(config)); case 'chacha20': return (ChaChaPolyCipher && !forceNative ? new ChaChaPolyCipherBinding(config) : new ChaChaPolyCipherNative(config)); default: { if (typeof outbound.macInfo !== 'object' || outbound.macInfo === null) throw new Error('Invalid outbound.macInfo'); if (!Buffer.isBuffer(outbound.macKey) || outbound.macKey.length !== outbound.macInfo.len) { throw new Error('Invalid outbound.macKey'); } return (GenericCipher && !forceNative ? new GenericCipherBinding(config) : new GenericCipherNative(config)); } } } function createDecipher(config) { if (typeof config !== 'object' || config === null) throw new Error('Invalid config'); if (typeof config.inbound !== 'object' || config.inbound === null) throw new Error('Invalid inbound'); const inbound = config.inbound; if (typeof inbound.onPayload !== 'function') throw new Error('Invalid inbound.onPayload'); if (typeof inbound.decipherInfo !== 'object' || inbound.decipherInfo === null) { throw new Error('Invalid inbound.decipherInfo'); } if (!Buffer.isBuffer(inbound.decipherKey) || inbound.decipherKey.length !== inbound.decipherInfo.keyLen) { throw new Error('Invalid inbound.decipherKey'); } if (inbound.decipherInfo.ivLen && (!Buffer.isBuffer(inbound.decipherIV) || inbound.decipherIV.length !== inbound.decipherInfo.ivLen)) { throw new Error('Invalid inbound.decipherIV'); } if (typeof inbound.seqno !== 'number' || inbound.seqno < 0 || inbound.seqno > MAX_SEQNO) { throw new Error('Invalid inbound.seqno'); } const forceNative = !!inbound.forceNative; switch (inbound.decipherInfo.sslName) { case 'aes-128-gcm': case 'aes-256-gcm': return (AESGCMDecipher && !forceNative ? new AESGCMDecipherBinding(config) : new AESGCMDecipherNative(config)); case 'chacha20': return (ChaChaPolyDecipher && !forceNative ? new ChaChaPolyDecipherBinding(config) : new ChaChaPolyDecipherNative(config)); default: { if (typeof inbound.macInfo !== 'object' || inbound.macInfo === null) throw new Error('Invalid inbound.macInfo'); if (!Buffer.isBuffer(inbound.macKey) || inbound.macKey.length !== inbound.macInfo.len) { throw new Error('Invalid inbound.macKey'); } return (GenericDecipher && !forceNative ? new GenericDecipherBinding(config) : new GenericDecipherNative(config)); } } } module.exports = { CIPHER_INFO, MAC_INFO, bindingAvailable: !!binding, init: (() => { // eslint-disable-next-line no-async-promise-executor return new Promise(async (resolve, reject) => { try { POLY1305_WASM_MODULE = await __webpack_require__(69449)(); POLY1305_RESULT_MALLOC = POLY1305_WASM_MODULE._malloc(16); poly1305_auth = POLY1305_WASM_MODULE.cwrap( 'poly1305_auth', null, ['number', 'array', 'number', 'array', 'number', 'array'] ); } catch (ex) { return reject(ex); } resolve(); }); })(), NullCipher, createCipher, NullDecipher, createDecipher, }; /***/ }), /***/ 69449: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var createPoly1305 = (function() { var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename; return ( function(createPoly1305) { createPoly1305 = createPoly1305 || {}; var b;b||(b=typeof createPoly1305 !== 'undefined' ? createPoly1305 : {});var q,r;b.ready=new Promise(function(a,c){q=a;r=c});var u={},w;for(w in b)b.hasOwnProperty(w)&&(u[w]=b[w]);var x="object"===typeof window,y="function"===typeof importScripts,z="object"===typeof process&&"object"===typeof process.versions&&"string"===typeof process.versions.node,B="",C,D,E,F,G; if(z)B=y?__webpack_require__(71017).dirname(B)+"/":__dirname+"/",C=function(a,c){var d=H(a);if(d)return c?d:d.toString();F||(F=__webpack_require__(57147));G||(G=__webpack_require__(71017));a=G.normalize(a);return F.readFileSync(a,c?null:"utf8")},E=function(a){a=C(a,!0);a.buffer||(a=new Uint8Array(a));assert(a.buffer);return a},D=function(a,c,d){var e=H(a);e&&c(e);F||(F=__webpack_require__(57147));G||(G=__webpack_require__(71017));a=G.normalize(a);F.readFile(a,function(f,l){f?d(f):c(l.buffer)})},1=m){var oa=g.charCodeAt(++v);m=65536+((m&1023)<<10)|oa&1023}if(127>=m){if(k>=n)break;h[k++]=m}else{if(2047>=m){if(k+1>=n)break;h[k++]=192|m>>6}else{if(65535>=m){if(k+2>=n)break;h[k++]=224|m>>12}else{if(k+3>=n)break;h[k++]=240|m>>18;h[k++]=128|m>>12&63}h[k++]=128|m>>6&63}h[k++]=128|m&63}}h[k]= 0}}return p},array:function(g){var p=O(g.length);Q.set(g,p);return p}},l=N(a),A=[];a=0;if(e)for(var t=0;t=n);)++k;if(16h?n+=String.fromCharCode(h):(h-=65536,n+=String.fromCharCode(55296|h>>10,56320|h&1023))}}else n+=String.fromCharCode(h)}g=n}}else g="";else g="boolean"===c?!!g:g;return g}(d);0!==a&&fa(a);return d}var ea="undefined"!==typeof TextDecoder?new TextDecoder("utf8"):void 0,ha,Q,P; function ia(){var a=L.buffer;ha=a;b.HEAP8=Q=new Int8Array(a);b.HEAP16=new Int16Array(a);b.HEAP32=new Int32Array(a);b.HEAPU8=P=new Uint8Array(a);b.HEAPU16=new Uint16Array(a);b.HEAPU32=new Uint32Array(a);b.HEAPF32=new Float32Array(a);b.HEAPF64=new Float64Array(a)}var R,ja=[],ka=[],la=[];function ma(){var a=b.preRun.shift();ja.unshift(a)}var S=0,T=null,U=null;b.preloadedImages={};b.preloadedAudios={}; function K(a){if(b.onAbort)b.onAbort(a);I(a);M=!0;a=new WebAssembly.RuntimeError("abort("+a+"). Build with -s ASSERTIONS=1 for more info.");r(a);throw a;}var V="data:application/octet-stream;base64,",W;W="data:application/octet-stream;base64,AGFzbQEAAAABIAZgAX8Bf2ADf39/AGABfwBgAABgAAF/YAZ/f39/f38AAgcBAWEBYQAAAwsKAAEDAQAAAgQFAgQFAXABAQEFBwEBgAKAgAIGCQF/AUGAjMACCwclCQFiAgABYwADAWQACQFlAAgBZgAHAWcABgFoAAUBaQAKAWoBAAqGTQpPAQJ/QYAIKAIAIgEgAEEDakF8cSICaiEAAkAgAkEAIAAgAU0bDQAgAD8AQRB0SwRAIAAQAEUNAQtBgAggADYCACABDwtBhAhBMDYCAEF/C4wFAg5+Cn8gACgCJCEUIAAoAiAhFSAAKAIcIREgACgCGCESIAAoAhQhEyACQRBPBEAgAC0ATEVBGHQhFyAAKAIEIhZBBWytIQ8gACgCCCIYQQVsrSENIAAoAgwiGUEFbK0hCyAAKAIQIhpBBWytIQkgADUCACEIIBqtIRAgGa0hDiAYrSEMIBatIQoDQCASIAEtAAMiEiABLQAEQQh0ciABLQAFQRB0ciABLQAGIhZBGHRyQQJ2Qf///x9xaq0iAyAOfiABLwAAIAEtAAJBEHRyIBNqIBJBGHRBgICAGHFqrSIEIBB+fCARIAEtAAdBCHQgFnIgAS0ACEEQdHIgAS0ACSIRQRh0ckEEdkH///8fcWqtIgUgDH58IAEtAApBCHQgEXIgAS0AC0EQdHIgAS0ADEEYdHJBBnYgFWqtIgYgCn58IBQgF2ogAS8ADSABLQAPQRB0cmqtIgcgCH58IAMgDH4gBCAOfnwgBSAKfnwgBiAIfnwgByAJfnwgAyAKfiAEIAx+fCAFIAh+fCAGIAl+fCAHIAt+fCADIAh+IAQgCn58IAUgCX58IAYgC358IAcgDX58IAMgCX4gBCAIfnwgBSALfnwgBiANfnwgByAPfnwiA0IaiEL/////D4N8IgRCGohC/////w+DfCIFQhqIQv////8Pg3wiBkIaiEL/////D4N8IgdCGoinQQVsIAOnQf///x9xaiITQRp2IASnQf///x9xaiESIAWnQf///x9xIREgBqdB////H3EhFSAHp0H///8fcSEUIBNB////H3EhEyABQRBqIQEgAkEQayICQQ9LDQALCyAAIBQ2AiQgACAVNgIgIAAgETYCHCAAIBI2AhggACATNgIUCwMAAQu2BAEGfwJAIAAoAjgiBARAIABBPGohBQJAIAJBECAEayIDIAIgA0kbIgZFDQAgBkEDcSEHAkAgBkEBa0EDSQRAQQAhAwwBCyAGQXxxIQhBACEDA0AgBSADIARqaiABIANqLQAAOgAAIAUgA0EBciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0ECciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0EDciIEIAAoAjhqaiABIARqLQAAOgAAIANBBGohAyAAKAI4IQQgCEEEayIIDQALCyAHRQ0AA0AgBSADIARqaiABIANqLQAAOgAAIANBAWohAyAAKAI4IQQgB0EBayIHDQALCyAAIAQgBmoiAzYCOCADQRBJDQEgACAFQRAQAiAAQQA2AjggAiAGayECIAEgBmohAQsgAkEQTwRAIAAgASACQXBxIgMQAiACQQ9xIQIgASADaiEBCyACRQ0AIAJBA3EhBCAAQTxqIQVBACEDIAJBAWtBA08EQCACQXxxIQcDQCAFIAAoAjggA2pqIAEgA2otAAA6AAAgBSADQQFyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQJyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQNyIgYgACgCOGpqIAEgBmotAAA6AAAgA0EEaiEDIAdBBGsiBw0ACwsgBARAA0AgBSAAKAI4IANqaiABIANqLQAAOgAAIANBAWohAyAEQQFrIgQNAAsLIAAgACgCOCACajYCOAsLoS0BDH8jAEEQayIMJAACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEH0AU0EQEGICCgCACIFQRAgAEELakF4cSAAQQtJGyIIQQN2IgJ2IgFBA3EEQCABQX9zQQFxIAJqIgNBA3QiAUG4CGooAgAiBEEIaiEAAkAgBCgCCCICIAFBsAhqIgFGBEBBiAggBUF+IAN3cTYCAAwBCyACIAE2AgwgASACNgIICyAEIANBA3QiAUEDcjYCBCABIARqIgEgASgCBEEBcjYCBAwNCyAIQZAIKAIAIgpNDQEgAQRAAkBBAiACdCIAQQAgAGtyIAEgAnRxIgBBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2aiIDQQN0IgBBuAhqKAIAIgQoAggiASAAQbAIaiIARgRAQYgIIAVBfiADd3EiBTYCAAwBCyABIAA2AgwgACABNgIICyAEQQhqIQAgBCAIQQNyNgIEIAQgCGoiAiADQQN0IgEgCGsiA0EBcjYCBCABIARqIAM2AgAgCgRAIApBA3YiAUEDdEGwCGohB0GcCCgCACEEAn8gBUEBIAF0IgFxRQRAQYgIIAEgBXI2AgAgBwwBCyAHKAIICyEBIAcgBDYCCCABIAQ2AgwgBCAHNgIMIAQgATYCCAtBnAggAjYCAEGQCCADNgIADA0LQYwIKAIAIgZFDQEgBkEAIAZrcUEBayIAIABBDHZBEHEiAnYiAUEFdkEIcSIAIAJyIAEgAHYiAUECdkEEcSIAciABIAB2IgFBAXZBAnEiAHIgASAAdiIBQQF2QQFxIgByIAEgAHZqQQJ0QbgKaigCACIBKAIEQXhxIAhrIQMgASECA0ACQCACKAIQIgBFBEAgAigCFCIARQ0BCyAAKAIEQXhxIAhrIgIgAyACIANJIgIbIQMgACABIAIbIQEgACECDAELCyABIAhqIgkgAU0NAiABKAIYIQsgASABKAIMIgRHBEAgASgCCCIAQZgIKAIASRogACAENgIMIAQgADYCCAwMCyABQRRqIgIoAgAiAEUEQCABKAIQIgBFDQQgAUEQaiECCwNAIAIhByAAIgRBFGoiAigCACIADQAgBEEQaiECIAQoAhAiAA0ACyAHQQA2AgAMCwtBfyEIIABBv39LDQAgAEELaiIAQXhxIQhBjAgoAgAiCUUNAEEAIAhrIQMCQAJAAkACf0EAIAhBgAJJDQAaQR8gCEH///8HSw0AGiAAQQh2IgAgAEGA/j9qQRB2QQhxIgJ0IgAgAEGA4B9qQRB2QQRxIgF0IgAgAEGAgA9qQRB2QQJxIgB0QQ92IAEgAnIgAHJrIgBBAXQgCCAAQRVqdkEBcXJBHGoLIgVBAnRBuApqKAIAIgJFBEBBACEADAELQQAhACAIQQBBGSAFQQF2ayAFQR9GG3QhAQNAAkAgAigCBEF4cSAIayIHIANPDQAgAiEEIAciAw0AQQAhAyACIQAMAwsgACACKAIUIgcgByACIAFBHXZBBHFqKAIQIgJGGyAAIAcbIQAgAUEBdCEBIAINAAsLIAAgBHJFBEBBACEEQQIgBXQiAEEAIABrciAJcSIARQ0DIABBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2akECdEG4CmooAgAhAAsgAEUNAQsDQCAAKAIEQXhxIAhrIgEgA0khAiABIAMgAhshAyAAIAQgAhshBCAAKAIQIgEEfyABBSAAKAIUCyIADQALCyAERQ0AIANBkAgoAgAgCGtPDQAgBCAIaiIGIARNDQEgBCgCGCEFIAQgBCgCDCIBRwRAIAQoAggiAEGYCCgCAEkaIAAgATYCDCABIAA2AggMCgsgBEEUaiICKAIAIgBFBEAgBCgCECIARQ0EIARBEGohAgsDQCACIQcgACIBQRRqIgIoAgAiAA0AIAFBEGohAiABKAIQIgANAAsgB0EANgIADAkLIAhBkAgoAgAiAk0EQEGcCCgCACEDAkAgAiAIayIBQRBPBEBBkAggATYCAEGcCCADIAhqIgA2AgAgACABQQFyNgIEIAIgA2ogATYCACADIAhBA3I2AgQMAQtBnAhBADYCAEGQCEEANgIAIAMgAkEDcjYCBCACIANqIgAgACgCBEEBcjYCBAsgA0EIaiEADAsLIAhBlAgoAgAiBkkEQEGUCCAGIAhrIgE2AgBBoAhBoAgoAgAiAiAIaiIANgIAIAAgAUEBcjYCBCACIAhBA3I2AgQgAkEIaiEADAsLQQAhACAIQS9qIgkCf0HgCygCAARAQegLKAIADAELQewLQn83AgBB5AtCgKCAgICABDcCAEHgCyAMQQxqQXBxQdiq1aoFczYCAEH0C0EANgIAQcQLQQA2AgBBgCALIgFqIgVBACABayIHcSICIAhNDQpBwAsoAgAiBARAQbgLKAIAIgMgAmoiASADTQ0LIAEgBEsNCwtBxAstAABBBHENBQJAAkBBoAgoAgAiAwRAQcgLIQADQCADIAAoAgAiAU8EQCABIAAoAgRqIANLDQMLIAAoAggiAA0ACwtBABABIgFBf0YNBiACIQVB5AsoAgAiA0EBayIAIAFxBEAgAiABayAAIAFqQQAgA2txaiEFCyAFIAhNDQYgBUH+////B0sNBkHACygCACIEBEBBuAsoAgAiAyAFaiIAIANNDQcgACAESw0HCyAFEAEiACABRw0BDAgLIAUgBmsgB3EiBUH+////B0sNBSAFEAEiASAAKAIAIAAoAgRqRg0EIAEhAAsCQCAAQX9GDQAgCEEwaiAFTQ0AQegLKAIAIgEgCSAFa2pBACABa3EiAUH+////B0sEQCAAIQEMCAsgARABQX9HBEAgASAFaiEFIAAhAQwIC0EAIAVrEAEaDAULIAAiAUF/Rw0GDAQLAAtBACEEDAcLQQAhAQwFCyABQX9HDQILQcQLQcQLKAIAQQRyNgIACyACQf7///8HSw0BIAIQASEBQQAQASEAIAFBf0YNASAAQX9GDQEgACABTQ0BIAAgAWsiBSAIQShqTQ0BC0G4C0G4CygCACAFaiIANgIAQbwLKAIAIABJBEBBvAsgADYCAAsCQAJAAkBBoAgoAgAiBwRAQcgLIQADQCABIAAoAgAiAyAAKAIEIgJqRg0CIAAoAggiAA0ACwwCC0GYCCgCACIAQQAgACABTRtFBEBBmAggATYCAAtBACEAQcwLIAU2AgBByAsgATYCAEGoCEF/NgIAQawIQeALKAIANgIAQdQLQQA2AgADQCAAQQN0IgNBuAhqIANBsAhqIgI2AgAgA0G8CGogAjYCACAAQQFqIgBBIEcNAAtBlAggBUEoayIDQXggAWtBB3FBACABQQhqQQdxGyIAayICNgIAQaAIIAAgAWoiADYCACAAIAJBAXI2AgQgASADakEoNgIEQaQIQfALKAIANgIADAILIAAtAAxBCHENACADIAdLDQAgASAHTQ0AIAAgAiAFajYCBEGgCCAHQXggB2tBB3FBACAHQQhqQQdxGyIAaiICNgIAQZQIQZQIKAIAIAVqIgEgAGsiADYCACACIABBAXI2AgQgASAHakEoNgIEQaQIQfALKAIANgIADAELQZgIKAIAIAFLBEBBmAggATYCAAsgASAFaiECQcgLIQACQAJAAkACQAJAAkADQCACIAAoAgBHBEAgACgCCCIADQEMAgsLIAAtAAxBCHFFDQELQcgLIQADQCAHIAAoAgAiAk8EQCACIAAoAgRqIgQgB0sNAwsgACgCCCEADAALAAsgACABNgIAIAAgACgCBCAFajYCBCABQXggAWtBB3FBACABQQhqQQdxG2oiCSAIQQNyNgIEIAJBeCACa0EHcUEAIAJBCGpBB3EbaiIFIAggCWoiBmshAiAFIAdGBEBBoAggBjYCAEGUCEGUCCgCACACaiIANgIAIAYgAEEBcjYCBAwDCyAFQZwIKAIARgRAQZwIIAY2AgBBkAhBkAgoAgAgAmoiADYCACAGIABBAXI2AgQgACAGaiAANgIADAMLIAUoAgQiAEEDcUEBRgRAIABBeHEhBwJAIABB/wFNBEAgBSgCCCIDIABBA3YiAEEDdEGwCGpGGiADIAUoAgwiAUYEQEGICEGICCgCAEF+IAB3cTYCAAwCCyADIAE2AgwgASADNgIIDAELIAUoAhghCAJAIAUgBSgCDCIBRwRAIAUoAggiACABNgIMIAEgADYCCAwBCwJAIAVBFGoiACgCACIDDQAgBUEQaiIAKAIAIgMNAEEAIQEMAQsDQCAAIQQgAyIBQRRqIgAoAgAiAw0AIAFBEGohACABKAIQIgMNAAsgBEEANgIACyAIRQ0AAkAgBSAFKAIcIgNBAnRBuApqIgAoAgBGBEAgACABNgIAIAENAUGMCEGMCCgCAEF+IAN3cTYCAAwCCyAIQRBBFCAIKAIQIAVGG2ogATYCACABRQ0BCyABIAg2AhggBSgCECIABEAgASAANgIQIAAgATYCGAsgBSgCFCIARQ0AIAEgADYCFCAAIAE2AhgLIAUgB2ohBSACIAdqIQILIAUgBSgCBEF+cTYCBCAGIAJBAXI2AgQgAiAGaiACNgIAIAJB/wFNBEAgAkEDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwDC0EfIQAgAkH///8HTQRAIAJBCHYiACAAQYD+P2pBEHZBCHEiA3QiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASADciAAcmsiAEEBdCACIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQQCQEGMCCgCACIDQQEgAHQiAXFFBEBBjAggASADcjYCACAEIAY2AgAgBiAENgIYDAELIAJBAEEZIABBAXZrIABBH0YbdCEAIAQoAgAhAQNAIAEiAygCBEF4cSACRg0DIABBHXYhASAAQQF0IQAgAyABQQRxaiIEKAIQIgENAAsgBCAGNgIQIAYgAzYCGAsgBiAGNgIMIAYgBjYCCAwCC0GUCCAFQShrIgNBeCABa0EHcUEAIAFBCGpBB3EbIgBrIgI2AgBBoAggACABaiIANgIAIAAgAkEBcjYCBCABIANqQSg2AgRBpAhB8AsoAgA2AgAgByAEQScgBGtBB3FBACAEQSdrQQdxG2pBL2siACAAIAdBEGpJGyICQRs2AgQgAkHQCykCADcCECACQcgLKQIANwIIQdALIAJBCGo2AgBBzAsgBTYCAEHICyABNgIAQdQLQQA2AgAgAkEYaiEAA0AgAEEHNgIEIABBCGohASAAQQRqIQAgASAESQ0ACyACIAdGDQMgAiACKAIEQX5xNgIEIAcgAiAHayIEQQFyNgIEIAIgBDYCACAEQf8BTQRAIARBA3YiAEEDdEGwCGohAgJ/QYgIKAIAIgFBASAAdCIAcUUEQEGICCAAIAFyNgIAIAIMAQsgAigCCAshACACIAc2AgggACAHNgIMIAcgAjYCDCAHIAA2AggMBAtBHyEAIAdCADcCECAEQf///wdNBEAgBEEIdiIAIABBgP4/akEQdkEIcSICdCIAIABBgOAfakEQdkEEcSIBdCIAIABBgIAPakEQdkECcSIAdEEPdiABIAJyIAByayIAQQF0IAQgAEEVanZBAXFyQRxqIQALIAcgADYCHCAAQQJ0QbgKaiEDAkBBjAgoAgAiAkEBIAB0IgFxRQRAQYwIIAEgAnI2AgAgAyAHNgIAIAcgAzYCGAwBCyAEQQBBGSAAQQF2ayAAQR9GG3QhACADKAIAIQEDQCABIgIoAgRBeHEgBEYNBCAAQR12IQEgAEEBdCEAIAIgAUEEcWoiAygCECIBDQALIAMgBzYCECAHIAI2AhgLIAcgBzYCDCAHIAc2AggMAwsgAygCCCIAIAY2AgwgAyAGNgIIIAZBADYCGCAGIAM2AgwgBiAANgIICyAJQQhqIQAMBQsgAigCCCIAIAc2AgwgAiAHNgIIIAdBADYCGCAHIAI2AgwgByAANgIIC0GUCCgCACIAIAhNDQBBlAggACAIayIBNgIAQaAIQaAIKAIAIgIgCGoiADYCACAAIAFBAXI2AgQgAiAIQQNyNgIEIAJBCGohAAwDC0GECEEwNgIAQQAhAAwCCwJAIAVFDQACQCAEKAIcIgJBAnRBuApqIgAoAgAgBEYEQCAAIAE2AgAgAQ0BQYwIIAlBfiACd3EiCTYCAAwCCyAFQRBBFCAFKAIQIARGG2ogATYCACABRQ0BCyABIAU2AhggBCgCECIABEAgASAANgIQIAAgATYCGAsgBCgCFCIARQ0AIAEgADYCFCAAIAE2AhgLAkAgA0EPTQRAIAQgAyAIaiIAQQNyNgIEIAAgBGoiACAAKAIEQQFyNgIEDAELIAQgCEEDcjYCBCAGIANBAXI2AgQgAyAGaiADNgIAIANB/wFNBEAgA0EDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwBC0EfIQAgA0H///8HTQRAIANBCHYiACAAQYD+P2pBEHZBCHEiAnQiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASACciAAcmsiAEEBdCADIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQICQAJAIAlBASAAdCIBcUUEQEGMCCABIAlyNgIAIAIgBjYCACAGIAI2AhgMAQsgA0EAQRkgAEEBdmsgAEEfRht0IQAgAigCACEIA0AgCCIBKAIEQXhxIANGDQIgAEEddiECIABBAXQhACABIAJBBHFqIgIoAhAiCA0ACyACIAY2AhAgBiABNgIYCyAGIAY2AgwgBiAGNgIIDAELIAEoAggiACAGNgIMIAEgBjYCCCAGQQA2AhggBiABNgIMIAYgADYCCAsgBEEIaiEADAELAkAgC0UNAAJAIAEoAhwiAkECdEG4CmoiACgCACABRgRAIAAgBDYCACAEDQFBjAggBkF+IAJ3cTYCAAwCCyALQRBBFCALKAIQIAFGG2ogBDYCACAERQ0BCyAEIAs2AhggASgCECIABEAgBCAANgIQIAAgBDYCGAsgASgCFCIARQ0AIAQgADYCFCAAIAQ2AhgLAkAgA0EPTQRAIAEgAyAIaiIAQQNyNgIEIAAgAWoiACAAKAIEQQFyNgIEDAELIAEgCEEDcjYCBCAJIANBAXI2AgQgAyAJaiADNgIAIAoEQCAKQQN2IgBBA3RBsAhqIQRBnAgoAgAhAgJ/QQEgAHQiACAFcUUEQEGICCAAIAVyNgIAIAQMAQsgBCgCCAshACAEIAI2AgggACACNgIMIAIgBDYCDCACIAA2AggLQZwIIAk2AgBBkAggAzYCAAsgAUEIaiEACyAMQRBqJAAgAAsQACMAIABrQXBxIgAkACAACwYAIAAkAAsEACMAC4AJAgh/BH4jAEGQAWsiBiQAIAYgBS0AA0EYdEGAgIAYcSAFLwAAIAUtAAJBEHRycjYCACAGIAUoAANBAnZBg/7/H3E2AgQgBiAFKAAGQQR2Qf+B/x9xNgIIIAYgBSgACUEGdkH//8AfcTYCDCAFLwANIQggBS0ADyEJIAZCADcCFCAGQgA3AhwgBkEANgIkIAYgCCAJQRB0QYCAPHFyNgIQIAYgBSgAEDYCKCAGIAUoABQ2AiwgBiAFKAAYNgIwIAUoABwhBSAGQQA6AEwgBkEANgI4IAYgBTYCNCAGIAEgAhAEIAQEQCAGIAMgBBAECyAGKAI4IgEEQCAGQTxqIgIgAWpBAToAACABQQFqQQ9NBEAgASAGakE9aiEEAkBBDyABayIDRQ0AIAMgBGoiAUEBa0EAOgAAIARBADoAACADQQNJDQAgAUECa0EAOgAAIARBADoAASABQQNrQQA6AAAgBEEAOgACIANBB0kNACABQQRrQQA6AAAgBEEAOgADIANBCUkNACAEQQAgBGtBA3EiAWoiBEEANgIAIAQgAyABa0F8cSIBaiIDQQRrQQA2AgAgAUEJSQ0AIARBADYCCCAEQQA2AgQgA0EIa0EANgIAIANBDGtBADYCACABQRlJDQAgBEEANgIYIARBADYCFCAEQQA2AhAgBEEANgIMIANBEGtBADYCACADQRRrQQA2AgAgA0EYa0EANgIAIANBHGtBADYCACABIARBBHFBGHIiAWsiA0EgSQ0AIAEgBGohAQNAIAFCADcDGCABQgA3AxAgAUIANwMIIAFCADcDACABQSBqIQEgA0EgayIDQR9LDQALCwsgBkEBOgBMIAYgAkEQEAILIAY1AjQhECAGNQIwIREgBjUCLCEOIAAgBjUCKCAGKAIkIAYoAiAgBigCHCAGKAIYIgNBGnZqIgJBGnZqIgFBGnZqIgtBgICAYHIgAUH///8fcSINIAJB////H3EiCCAGKAIUIAtBGnZBBWxqIgFB////H3EiCUEFaiIFQRp2IANB////H3EgAUEadmoiA2oiAUEadmoiAkEadmoiBEEadmoiDEEfdSIHIANxIAEgDEEfdkEBayIDQf///x9xIgpxciIBQRp0IAUgCnEgByAJcXJyrXwiDzwAACAAIA9CGIg8AAMgACAPQhCIPAACIAAgD0IIiDwAASAAIA4gByAIcSACIApxciICQRR0IAFBBnZyrXwgD0IgiHwiDjwABCAAIA5CGIg8AAcgACAOQhCIPAAGIAAgDkIIiDwABSAAIBEgByANcSAEIApxciIBQQ50IAJBDHZyrXwgDkIgiHwiDjwACCAAIA5CGIg8AAsgACAOQhCIPAAKIAAgDkIIiDwACSAAIBAgAyAMcSAHIAtxckEIdCABQRJ2cq18IA5CIIh8Ig48AAwgACAOQhiIPAAPIAAgDkIQiDwADiAAIA5CCIg8AA0gBkIANwIwIAZCADcCKCAGQgA3AiAgBkIANwIYIAZCADcCECAGQgA3AgggBkIANwIAIAZBkAFqJAALpwwBB38CQCAARQ0AIABBCGsiAyAAQQRrKAIAIgFBeHEiAGohBQJAIAFBAXENACABQQNxRQ0BIAMgAygCACIBayIDQZgIKAIASQ0BIAAgAWohACADQZwIKAIARwRAIAFB/wFNBEAgAygCCCICIAFBA3YiBEEDdEGwCGpGGiACIAMoAgwiAUYEQEGICEGICCgCAEF+IAR3cTYCAAwDCyACIAE2AgwgASACNgIIDAILIAMoAhghBgJAIAMgAygCDCIBRwRAIAMoAggiAiABNgIMIAEgAjYCCAwBCwJAIANBFGoiAigCACIEDQAgA0EQaiICKAIAIgQNAEEAIQEMAQsDQCACIQcgBCIBQRRqIgIoAgAiBA0AIAFBEGohAiABKAIQIgQNAAsgB0EANgIACyAGRQ0BAkAgAyADKAIcIgJBAnRBuApqIgQoAgBGBEAgBCABNgIAIAENAUGMCEGMCCgCAEF+IAJ3cTYCAAwDCyAGQRBBFCAGKAIQIANGG2ogATYCACABRQ0CCyABIAY2AhggAygCECICBEAgASACNgIQIAIgATYCGAsgAygCFCICRQ0BIAEgAjYCFCACIAE2AhgMAQsgBSgCBCIBQQNxQQNHDQBBkAggADYCACAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAA8LIAMgBU8NACAFKAIEIgFBAXFFDQACQCABQQJxRQRAIAVBoAgoAgBGBEBBoAggAzYCAEGUCEGUCCgCACAAaiIANgIAIAMgAEEBcjYCBCADQZwIKAIARw0DQZAIQQA2AgBBnAhBADYCAA8LIAVBnAgoAgBGBEBBnAggAzYCAEGQCEGQCCgCACAAaiIANgIAIAMgAEEBcjYCBCAAIANqIAA2AgAPCyABQXhxIABqIQACQCABQf8BTQRAIAUoAggiAiABQQN2IgRBA3RBsAhqRhogAiAFKAIMIgFGBEBBiAhBiAgoAgBBfiAEd3E2AgAMAgsgAiABNgIMIAEgAjYCCAwBCyAFKAIYIQYCQCAFIAUoAgwiAUcEQCAFKAIIIgJBmAgoAgBJGiACIAE2AgwgASACNgIIDAELAkAgBUEUaiICKAIAIgQNACAFQRBqIgIoAgAiBA0AQQAhAQwBCwNAIAIhByAEIgFBFGoiAigCACIEDQAgAUEQaiECIAEoAhAiBA0ACyAHQQA2AgALIAZFDQACQCAFIAUoAhwiAkECdEG4CmoiBCgCAEYEQCAEIAE2AgAgAQ0BQYwIQYwIKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgBUYbaiABNgIAIAFFDQELIAEgBjYCGCAFKAIQIgIEQCABIAI2AhAgAiABNgIYCyAFKAIUIgJFDQAgASACNgIUIAIgATYCGAsgAyAAQQFyNgIEIAAgA2ogADYCACADQZwIKAIARw0BQZAIIAA2AgAPCyAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAAsgAEH/AU0EQCAAQQN2IgFBA3RBsAhqIQACf0GICCgCACICQQEgAXQiAXFFBEBBiAggASACcjYCACAADAELIAAoAggLIQIgACADNgIIIAIgAzYCDCADIAA2AgwgAyACNgIIDwtBHyECIANCADcCECAAQf///wdNBEAgAEEIdiIBIAFBgP4/akEQdkEIcSIBdCICIAJBgOAfakEQdkEEcSICdCIEIARBgIAPakEQdkECcSIEdEEPdiABIAJyIARyayIBQQF0IAAgAUEVanZBAXFyQRxqIQILIAMgAjYCHCACQQJ0QbgKaiEBAkACQAJAQYwIKAIAIgRBASACdCIHcUUEQEGMCCAEIAdyNgIAIAEgAzYCACADIAE2AhgMAQsgAEEAQRkgAkEBdmsgAkEfRht0IQIgASgCACEBA0AgASIEKAIEQXhxIABGDQIgAkEddiEBIAJBAXQhAiAEIAFBBHFqIgdBEGooAgAiAQ0ACyAHIAM2AhAgAyAENgIYCyADIAM2AgwgAyADNgIIDAELIAQoAggiACADNgIMIAQgAzYCCCADQQA2AhggAyAENgIMIAMgADYCCAtBqAhBqAgoAgBBAWsiAEF/IAAbNgIACwsLCQEAQYEICwIGUA==";if(!W.startsWith(V)){var na=W;W=b.locateFile?b.locateFile(na,B):B+na}function pa(){var a=W;try{if(a==W&&J)return new Uint8Array(J);var c=H(a);if(c)return c;if(E)return E(a);throw"both async and sync fetching of the wasm failed";}catch(d){K(d)}} function qa(){if(!J&&(x||y)){if("function"===typeof fetch&&!W.startsWith("file://"))return fetch(W,{credentials:"same-origin"}).then(function(a){if(!a.ok)throw"failed to load wasm binary file at '"+W+"'";return a.arrayBuffer()}).catch(function(){return pa()});if(D)return new Promise(function(a,c){D(W,function(d){a(new Uint8Array(d))},c)})}return Promise.resolve().then(function(){return pa()})} function X(a){for(;0>4;f=(f&15)<<4|l>>2;var t=(l&3)<<6|A;c+=String.fromCharCode(e);64!==l&&(c+=String.fromCharCode(f));64!==A&&(c+=String.fromCharCode(t))}while(d>>=0;if(2147483648=d;d*=2){var e=c*(1+.2/d);e=Math.min(e,a+100663296);e=Math.max(a,e);0>>16);ia();var f=1;break a}catch(l){}f=void 0}if(f)return!0}return!1}}; (function(){function a(f){b.asm=f.exports;L=b.asm.b;ia();R=b.asm.j;ka.unshift(b.asm.c);S--;b.monitorRunDependencies&&b.monitorRunDependencies(S);0==S&&(null!==T&&(clearInterval(T),T=null),U&&(f=U,U=null,f()))}function c(f){a(f.instance)}function d(f){return qa().then(function(l){return WebAssembly.instantiate(l,e)}).then(f,function(l){I("failed to asynchronously prepare wasm: "+l);K(l)})}var e={a:sa};S++;b.monitorRunDependencies&&b.monitorRunDependencies(S);if(b.instantiateWasm)try{return b.instantiateWasm(e, a)}catch(f){return I("Module.instantiateWasm callback failed with error: "+f),!1}(function(){return J||"function"!==typeof WebAssembly.instantiateStreaming||W.startsWith(V)||W.startsWith("file://")||"function"!==typeof fetch?d(c):fetch(W,{credentials:"same-origin"}).then(function(f){return WebAssembly.instantiateStreaming(f,e).then(c,function(l){I("wasm streaming compile failed: "+l);I("falling back to ArrayBuffer instantiation");return d(c)})})})().catch(r);return{}})(); b.___wasm_call_ctors=function(){return(b.___wasm_call_ctors=b.asm.c).apply(null,arguments)};b._poly1305_auth=function(){return(b._poly1305_auth=b.asm.d).apply(null,arguments)};var da=b.stackSave=function(){return(da=b.stackSave=b.asm.e).apply(null,arguments)},fa=b.stackRestore=function(){return(fa=b.stackRestore=b.asm.f).apply(null,arguments)},O=b.stackAlloc=function(){return(O=b.stackAlloc=b.asm.g).apply(null,arguments)};b._malloc=function(){return(b._malloc=b.asm.h).apply(null,arguments)}; b._free=function(){return(b._free=b.asm.i).apply(null,arguments)};b.cwrap=function(a,c,d,e){d=d||[];var f=d.every(function(l){return"number"===l});return"string"!==c&&f&&!e?N(a):function(){return ca(a,c,d,arguments)}};var Y;U=function ta(){Y||Z();Y||(U=ta)}; function Z(){function a(){if(!Y&&(Y=!0,b.calledRun=!0,!M)){X(ka);q(b);if(b.onRuntimeInitialized)b.onRuntimeInitialized();if(b.postRun)for("function"==typeof b.postRun&&(b.postRun=[b.postRun]);b.postRun.length;){var c=b.postRun.shift();la.unshift(c)}X(la)}}if(!(0 { "use strict"; const MESSAGE_HANDLERS = new Array(256); [ __webpack_require__(65260).HANDLERS, __webpack_require__(56728), ].forEach((handlers) => { // eslint-disable-next-line prefer-const for (let [type, handler] of Object.entries(handlers)) { type = +type; if (isFinite(type) && type >= 0 && type < MESSAGE_HANDLERS.length) MESSAGE_HANDLERS[type] = handler; } }); module.exports = MESSAGE_HANDLERS; /***/ }), /***/ 56728: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const { bufferSlice, bufferParser, doFatalError, sigSSHToASN1, writeUInt32BE, } = __webpack_require__(39205); const { CHANNEL_OPEN_FAILURE, COMPAT, MESSAGE, TERMINAL_MODE, } = __webpack_require__(3190); const { parseKey, } = __webpack_require__(13781); const TERMINAL_MODE_BY_VALUE = Array.from(Object.entries(TERMINAL_MODE)) .reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {}); module.exports = { // Transport layer protocol ================================================== [MESSAGE.DISCONNECT]: (self, payload) => { /* byte SSH_MSG_DISCONNECT uint32 reason code string description in ISO-10646 UTF-8 encoding string language tag */ bufferParser.init(payload, 1); const reason = bufferParser.readUInt32BE(); const desc = bufferParser.readString(true); const lang = bufferParser.readString(); bufferParser.clear(); if (lang === undefined) { return doFatalError( self, 'Inbound: Malformed DISCONNECT packet' ); } self._debug && self._debug( `Inbound: Received DISCONNECT (${reason}, "${desc}")` ); const handler = self._handlers.DISCONNECT; handler && handler(self, reason, desc); }, [MESSAGE.IGNORE]: (self, payload) => { /* byte SSH_MSG_IGNORE string data */ self._debug && self._debug('Inbound: Received IGNORE'); }, [MESSAGE.UNIMPLEMENTED]: (self, payload) => { /* byte SSH_MSG_UNIMPLEMENTED uint32 packet sequence number of rejected message */ bufferParser.init(payload, 1); const seqno = bufferParser.readUInt32BE(); bufferParser.clear(); if (seqno === undefined) { return doFatalError( self, 'Inbound: Malformed UNIMPLEMENTED packet' ); } self._debug && self._debug(`Inbound: Received UNIMPLEMENTED (seqno ${seqno})`); }, [MESSAGE.DEBUG]: (self, payload) => { /* byte SSH_MSG_DEBUG boolean always_display string message in ISO-10646 UTF-8 encoding [RFC3629] string language tag [RFC3066] */ bufferParser.init(payload, 1); const display = bufferParser.readBool(); const msg = bufferParser.readString(true); const lang = bufferParser.readString(); bufferParser.clear(); if (lang === undefined) { return doFatalError( self, 'Inbound: Malformed DEBUG packet' ); } self._debug && self._debug('Inbound: Received DEBUG'); const handler = self._handlers.DEBUG; handler && handler(self, display, msg); }, [MESSAGE.SERVICE_REQUEST]: (self, payload) => { /* byte SSH_MSG_SERVICE_REQUEST string service name */ bufferParser.init(payload, 1); const name = bufferParser.readString(true); bufferParser.clear(); if (name === undefined) { return doFatalError( self, 'Inbound: Malformed SERVICE_REQUEST packet' ); } self._debug && self._debug(`Inbound: Received SERVICE_REQUEST (${name})`); const handler = self._handlers.SERVICE_REQUEST; handler && handler(self, name); }, [MESSAGE.SERVICE_ACCEPT]: (self, payload) => { // S->C /* byte SSH_MSG_SERVICE_ACCEPT string service name */ bufferParser.init(payload, 1); const name = bufferParser.readString(true); bufferParser.clear(); if (name === undefined) { return doFatalError( self, 'Inbound: Malformed SERVICE_ACCEPT packet' ); } self._debug && self._debug(`Inbound: Received SERVICE_ACCEPT (${name})`); const handler = self._handlers.SERVICE_ACCEPT; handler && handler(self, name); }, [MESSAGE.EXT_INFO]: (self, payload) => { /* byte SSH_MSG_EXT_INFO uint32 nr-extensions repeat the following 2 fields "nr-extensions" times: string extension-name string extension-value (binary) */ bufferParser.init(payload, 1); const numExts = bufferParser.readUInt32BE(); let exts; if (numExts !== undefined) { exts = []; for (let i = 0; i < numExts; ++i) { const name = bufferParser.readString(true); const data = bufferParser.readString(); if (data !== undefined) { switch (name) { case 'server-sig-algs': { const algs = data.latin1Slice(0, data.length).split(','); exts.push({ name, algs }); continue; } default: continue; } } // Malformed exts = undefined; break; } } bufferParser.clear(); if (exts === undefined) return doFatalError(self, 'Inbound: Malformed EXT_INFO packet'); self._debug && self._debug('Inbound: Received EXT_INFO'); const handler = self._handlers.EXT_INFO; handler && handler(self, exts); }, // User auth protocol -- generic ============================================= [MESSAGE.USERAUTH_REQUEST]: (self, payload) => { /* byte SSH_MSG_USERAUTH_REQUEST string user name in ISO-10646 UTF-8 encoding [RFC3629] string service name in US-ASCII string method name in US-ASCII .... method specific fields */ bufferParser.init(payload, 1); const user = bufferParser.readString(true); const service = bufferParser.readString(true); const method = bufferParser.readString(true); let methodData; let methodDesc; switch (method) { case 'none': methodData = null; break; case 'password': { /* boolean string plaintext password in ISO-10646 UTF-8 encoding [RFC3629] [string new password] */ const isChange = bufferParser.readBool(); if (isChange !== undefined) { methodData = bufferParser.readString(true); if (methodData !== undefined && isChange) { const newPassword = bufferParser.readString(true); if (newPassword !== undefined) methodData = { oldPassword: methodData, newPassword }; else methodData = undefined; } } break; } case 'publickey': { /* boolean string public key algorithm name string public key blob [string signature] */ const hasSig = bufferParser.readBool(); if (hasSig !== undefined) { const keyAlgo = bufferParser.readString(true); let realKeyAlgo = keyAlgo; const key = bufferParser.readString(); let hashAlgo; switch (keyAlgo) { case 'rsa-sha2-256': realKeyAlgo = 'ssh-rsa'; hashAlgo = 'sha256'; break; case 'rsa-sha2-512': realKeyAlgo = 'ssh-rsa'; hashAlgo = 'sha512'; break; } if (hasSig) { const blobEnd = bufferParser.pos(); let signature = bufferParser.readString(); if (signature !== undefined) { if (signature.length > (4 + keyAlgo.length + 4) && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) { // Skip algoLen + algo + sigLen signature = bufferSlice(signature, 4 + keyAlgo.length + 4); } signature = sigSSHToASN1(signature, realKeyAlgo); if (signature) { const sessionID = self._kex.sessionID; const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd); writeUInt32BE(blob, sessionID.length, 0); blob.set(sessionID, 4); blob.set( new Uint8Array(payload.buffer, payload.byteOffset, blobEnd), 4 + sessionID.length ); methodData = { keyAlgo: realKeyAlgo, key, signature, blob, hashAlgo, }; } } } else { methodData = { keyAlgo: realKeyAlgo, key, hashAlgo }; methodDesc = 'publickey -- check'; } } break; } case 'hostbased': { /* string public key algorithm for host key string public host key and certificates for client host string client host name expressed as the FQDN in US-ASCII string user name on the client host in ISO-10646 UTF-8 encoding [RFC3629] string signature */ const keyAlgo = bufferParser.readString(true); let realKeyAlgo = keyAlgo; const key = bufferParser.readString(); const localHostname = bufferParser.readString(true); const localUsername = bufferParser.readString(true); let hashAlgo; switch (keyAlgo) { case 'rsa-sha2-256': realKeyAlgo = 'ssh-rsa'; hashAlgo = 'sha256'; break; case 'rsa-sha2-512': realKeyAlgo = 'ssh-rsa'; hashAlgo = 'sha512'; break; } const blobEnd = bufferParser.pos(); let signature = bufferParser.readString(); if (signature !== undefined) { if (signature.length > (4 + keyAlgo.length + 4) && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) { // Skip algoLen + algo + sigLen signature = bufferSlice(signature, 4 + keyAlgo.length + 4); } signature = sigSSHToASN1(signature, realKeyAlgo); if (signature !== undefined) { const sessionID = self._kex.sessionID; const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd); writeUInt32BE(blob, sessionID.length, 0); blob.set(sessionID, 4); blob.set( new Uint8Array(payload.buffer, payload.byteOffset, blobEnd), 4 + sessionID.length ); methodData = { keyAlgo: realKeyAlgo, key, signature, blob, localHostname, localUsername, hashAlgo }; } } break; } case 'keyboard-interactive': /* string language tag (as defined in [RFC-3066]) string submethods (ISO-10646 UTF-8) */ // Skip/ignore language field -- it's deprecated in RFC 4256 bufferParser.skipString(); methodData = bufferParser.readList(); break; default: if (method !== undefined) methodData = bufferParser.readRaw(); } bufferParser.clear(); if (methodData === undefined) { return doFatalError( self, 'Inbound: Malformed USERAUTH_REQUEST packet' ); } if (methodDesc === undefined) methodDesc = method; self._authsQueue.push(method); self._debug && self._debug(`Inbound: Received USERAUTH_REQUEST (${methodDesc})`); const handler = self._handlers.USERAUTH_REQUEST; handler && handler(self, user, service, method, methodData); }, [MESSAGE.USERAUTH_FAILURE]: (self, payload) => { // S->C /* byte SSH_MSG_USERAUTH_FAILURE name-list authentications that can continue boolean partial success */ bufferParser.init(payload, 1); const authMethods = bufferParser.readList(); const partialSuccess = bufferParser.readBool(); bufferParser.clear(); if (partialSuccess === undefined) { return doFatalError( self, 'Inbound: Malformed USERAUTH_FAILURE packet' ); } self._debug && self._debug(`Inbound: Received USERAUTH_FAILURE (${authMethods})`); self._authsQueue.shift(); const handler = self._handlers.USERAUTH_FAILURE; handler && handler(self, authMethods, partialSuccess); }, [MESSAGE.USERAUTH_SUCCESS]: (self, payload) => { // S->C /* byte SSH_MSG_USERAUTH_SUCCESS */ self._debug && self._debug('Inbound: Received USERAUTH_SUCCESS'); self._authsQueue.shift(); const handler = self._handlers.USERAUTH_SUCCESS; handler && handler(self); }, [MESSAGE.USERAUTH_BANNER]: (self, payload) => { // S->C /* byte SSH_MSG_USERAUTH_BANNER string message in ISO-10646 UTF-8 encoding [RFC3629] string language tag [RFC3066] */ bufferParser.init(payload, 1); const msg = bufferParser.readString(true); const lang = bufferParser.readString(); bufferParser.clear(); if (lang === undefined) { return doFatalError( self, 'Inbound: Malformed USERAUTH_BANNER packet' ); } self._debug && self._debug('Inbound: Received USERAUTH_BANNER'); const handler = self._handlers.USERAUTH_BANNER; handler && handler(self, msg); }, // User auth protocol -- method-specific ===================================== 60: (self, payload) => { if (!self._authsQueue.length) { self._debug && self._debug('Inbound: Received payload type 60 without auth'); return; } switch (self._authsQueue[0]) { case 'password': { // S->C /* byte SSH_MSG_USERAUTH_PASSWD_CHANGEREQ string prompt in ISO-10646 UTF-8 encoding [RFC3629] string language tag [RFC3066] */ bufferParser.init(payload, 1); const prompt = bufferParser.readString(true); const lang = bufferParser.readString(); bufferParser.clear(); if (lang === undefined) { return doFatalError( self, 'Inbound: Malformed USERAUTH_PASSWD_CHANGEREQ packet' ); } self._debug && self._debug('Inbound: Received USERAUTH_PASSWD_CHANGEREQ'); const handler = self._handlers.USERAUTH_PASSWD_CHANGEREQ; handler && handler(self, prompt); break; } case 'publickey': { // S->C /* byte SSH_MSG_USERAUTH_PK_OK string public key algorithm name from the request string public key blob from the request */ bufferParser.init(payload, 1); const keyAlgo = bufferParser.readString(true); const key = bufferParser.readString(); bufferParser.clear(); if (key === undefined) { return doFatalError( self, 'Inbound: Malformed USERAUTH_PK_OK packet' ); } self._debug && self._debug('Inbound: Received USERAUTH_PK_OK'); self._authsQueue.shift(); const handler = self._handlers.USERAUTH_PK_OK; handler && handler(self, keyAlgo, key); break; } case 'keyboard-interactive': { // S->C /* byte SSH_MSG_USERAUTH_INFO_REQUEST string name (ISO-10646 UTF-8) string instruction (ISO-10646 UTF-8) string language tag (as defined in [RFC-3066]) int num-prompts string prompt[1] (ISO-10646 UTF-8) boolean echo[1] ... string prompt[num-prompts] (ISO-10646 UTF-8) boolean echo[num-prompts] */ bufferParser.init(payload, 1); const name = bufferParser.readString(true); const instructions = bufferParser.readString(true); bufferParser.readString(); // skip lang const numPrompts = bufferParser.readUInt32BE(); let prompts; if (numPrompts !== undefined) { prompts = new Array(numPrompts); let i; for (i = 0; i < numPrompts; ++i) { const prompt = bufferParser.readString(true); const echo = bufferParser.readBool(); if (echo === undefined) break; prompts[i] = { prompt, echo }; } if (i !== numPrompts) prompts = undefined; } bufferParser.clear(); if (prompts === undefined) { return doFatalError( self, 'Inbound: Malformed USERAUTH_INFO_REQUEST packet' ); } self._debug && self._debug('Inbound: Received USERAUTH_INFO_REQUEST'); const handler = self._handlers.USERAUTH_INFO_REQUEST; handler && handler(self, name, instructions, prompts); break; } default: self._debug && self._debug('Inbound: Received unexpected payload type 60'); } }, 61: (self, payload) => { if (!self._authsQueue.length) { self._debug && self._debug('Inbound: Received payload type 61 without auth'); return; } /* byte SSH_MSG_USERAUTH_INFO_RESPONSE int num-responses string response[1] (ISO-10646 UTF-8) ... string response[num-responses] (ISO-10646 UTF-8) */ if (self._authsQueue[0] !== 'keyboard-interactive') { return doFatalError( self, 'Inbound: Received unexpected payload type 61' ); } bufferParser.init(payload, 1); const numResponses = bufferParser.readUInt32BE(); let responses; if (numResponses !== undefined) { responses = new Array(numResponses); let i; for (i = 0; i < numResponses; ++i) { const response = bufferParser.readString(true); if (response === undefined) break; responses[i] = response; } if (i !== numResponses) responses = undefined; } bufferParser.clear(); if (responses === undefined) { return doFatalError( self, 'Inbound: Malformed USERAUTH_INFO_RESPONSE packet' ); } self._debug && self._debug('Inbound: Received USERAUTH_INFO_RESPONSE'); const handler = self._handlers.USERAUTH_INFO_RESPONSE; handler && handler(self, responses); }, // Connection protocol -- generic ============================================ [MESSAGE.GLOBAL_REQUEST]: (self, payload) => { /* byte SSH_MSG_GLOBAL_REQUEST string request name in US-ASCII only boolean want reply .... request-specific data follows */ bufferParser.init(payload, 1); const name = bufferParser.readString(true); const wantReply = bufferParser.readBool(); let data; if (wantReply !== undefined) { switch (name) { case 'tcpip-forward': case 'cancel-tcpip-forward': { /* string address to bind (e.g., "0.0.0.0") uint32 port number to bind */ const bindAddr = bufferParser.readString(true); const bindPort = bufferParser.readUInt32BE(); if (bindPort !== undefined) data = { bindAddr, bindPort }; break; } case 'streamlocal-forward@openssh.com': case 'cancel-streamlocal-forward@openssh.com': { /* string socket path */ const socketPath = bufferParser.readString(true); if (socketPath !== undefined) data = { socketPath }; break; } case 'no-more-sessions@openssh.com': data = null; break; case 'hostkeys-00@openssh.com': { data = []; while (bufferParser.avail() > 0) { const keyRaw = bufferParser.readString(); if (keyRaw === undefined) { data = undefined; break; } const key = parseKey(keyRaw); if (!(key instanceof Error)) data.push(key); } break; } default: data = bufferParser.readRaw(); } } bufferParser.clear(); if (data === undefined) { return doFatalError( self, 'Inbound: Malformed GLOBAL_REQUEST packet' ); } self._debug && self._debug(`Inbound: GLOBAL_REQUEST (${name})`); const handler = self._handlers.GLOBAL_REQUEST; if (handler) handler(self, name, wantReply, data); else self.requestFailure(); // Auto reject }, [MESSAGE.REQUEST_SUCCESS]: (self, payload) => { /* byte SSH_MSG_REQUEST_SUCCESS .... response specific data */ const data = (payload.length > 1 ? bufferSlice(payload, 1) : null); self._debug && self._debug('Inbound: REQUEST_SUCCESS'); const handler = self._handlers.REQUEST_SUCCESS; handler && handler(self, data); }, [MESSAGE.REQUEST_FAILURE]: (self, payload) => { /* byte SSH_MSG_REQUEST_FAILURE */ self._debug && self._debug('Inbound: Received REQUEST_FAILURE'); const handler = self._handlers.REQUEST_FAILURE; handler && handler(self); }, // Connection protocol -- channel-related ==================================== [MESSAGE.CHANNEL_OPEN]: (self, payload) => { /* byte SSH_MSG_CHANNEL_OPEN string channel type in US-ASCII only uint32 sender channel uint32 initial window size uint32 maximum packet size .... channel type specific data follows */ bufferParser.init(payload, 1); const type = bufferParser.readString(true); const sender = bufferParser.readUInt32BE(); const window = bufferParser.readUInt32BE(); const packetSize = bufferParser.readUInt32BE(); let channelInfo; switch (type) { case 'forwarded-tcpip': // S->C case 'direct-tcpip': { // C->S /* string address that was connected / host to connect uint32 port that was connected / port to connect string originator IP address uint32 originator port */ const destIP = bufferParser.readString(true); const destPort = bufferParser.readUInt32BE(); const srcIP = bufferParser.readString(true); const srcPort = bufferParser.readUInt32BE(); if (srcPort !== undefined) { channelInfo = { type, sender, window, packetSize, data: { destIP, destPort, srcIP, srcPort } }; } break; } case 'forwarded-streamlocal@openssh.com': // S->C case 'direct-streamlocal@openssh.com': { // C->S /* string socket path string reserved for future use (direct-streamlocal@openssh.com additionally has:) uint32 reserved */ const socketPath = bufferParser.readString(true); if (socketPath !== undefined) { channelInfo = { type, sender, window, packetSize, data: { socketPath } }; } break; } case 'x11': { // S->C /* string originator address (e.g., "192.168.7.38") uint32 originator port */ const srcIP = bufferParser.readString(true); const srcPort = bufferParser.readUInt32BE(); if (srcPort !== undefined) { channelInfo = { type, sender, window, packetSize, data: { srcIP, srcPort } }; } break; } default: // Includes: // 'session' (C->S) // 'auth-agent@openssh.com' (S->C) channelInfo = { type, sender, window, packetSize, data: {} }; } bufferParser.clear(); if (channelInfo === undefined) { return doFatalError( self, 'Inbound: Malformed CHANNEL_OPEN packet' ); } self._debug && self._debug(`Inbound: CHANNEL_OPEN (s:${sender}, ${type})`); const handler = self._handlers.CHANNEL_OPEN; if (handler) { handler(self, channelInfo); } else { self.channelOpenFail( channelInfo.sender, CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED, '', '' ); } }, [MESSAGE.CHANNEL_OPEN_CONFIRMATION]: (self, payload) => { /* byte SSH_MSG_CHANNEL_OPEN_CONFIRMATION uint32 recipient channel uint32 sender channel uint32 initial window size uint32 maximum packet size .... channel type specific data follows */ // "The 'recipient channel' is the channel number given in the // original open request, and 'sender channel' is the channel number // allocated by the other side." bufferParser.init(payload, 1); const recipient = bufferParser.readUInt32BE(); const sender = bufferParser.readUInt32BE(); const window = bufferParser.readUInt32BE(); const packetSize = bufferParser.readUInt32BE(); const data = (bufferParser.avail() ? bufferParser.readRaw() : undefined); bufferParser.clear(); if (packetSize === undefined) { return doFatalError( self, 'Inbound: Malformed CHANNEL_OPEN_CONFIRMATION packet' ); } self._debug && self._debug( `Inbound: CHANNEL_OPEN_CONFIRMATION (r:${recipient}, s:${sender})` ); const handler = self._handlers.CHANNEL_OPEN_CONFIRMATION; if (handler) handler(self, { recipient, sender, window, packetSize, data }); }, [MESSAGE.CHANNEL_OPEN_FAILURE]: (self, payload) => { /* byte SSH_MSG_CHANNEL_OPEN_FAILURE uint32 recipient channel uint32 reason code string description in ISO-10646 UTF-8 encoding [RFC3629] string language tag [RFC3066] */ bufferParser.init(payload, 1); const recipient = bufferParser.readUInt32BE(); const reason = bufferParser.readUInt32BE(); const description = bufferParser.readString(true); const lang = bufferParser.readString(); bufferParser.clear(); if (lang === undefined) { return doFatalError( self, 'Inbound: Malformed CHANNEL_OPEN_FAILURE packet' ); } self._debug && self._debug(`Inbound: CHANNEL_OPEN_FAILURE (r:${recipient})`); const handler = self._handlers.CHANNEL_OPEN_FAILURE; handler && handler(self, recipient, reason, description); }, [MESSAGE.CHANNEL_WINDOW_ADJUST]: (self, payload) => { /* byte SSH_MSG_CHANNEL_WINDOW_ADJUST uint32 recipient channel uint32 bytes to add */ bufferParser.init(payload, 1); const recipient = bufferParser.readUInt32BE(); const bytesToAdd = bufferParser.readUInt32BE(); bufferParser.clear(); if (bytesToAdd === undefined) { return doFatalError( self, 'Inbound: Malformed CHANNEL_WINDOW_ADJUST packet' ); } self._debug && self._debug( `Inbound: CHANNEL_WINDOW_ADJUST (r:${recipient}, ${bytesToAdd})` ); const handler = self._handlers.CHANNEL_WINDOW_ADJUST; handler && handler(self, recipient, bytesToAdd); }, [MESSAGE.CHANNEL_DATA]: (self, payload) => { /* byte SSH_MSG_CHANNEL_DATA uint32 recipient channel string data */ bufferParser.init(payload, 1); const recipient = bufferParser.readUInt32BE(); const data = bufferParser.readString(); bufferParser.clear(); if (data === undefined) { return doFatalError( self, 'Inbound: Malformed CHANNEL_DATA packet' ); } self._debug && self._debug(`Inbound: CHANNEL_DATA (r:${recipient}, ${data.length})`); const handler = self._handlers.CHANNEL_DATA; handler && handler(self, recipient, data); }, [MESSAGE.CHANNEL_EXTENDED_DATA]: (self, payload) => { /* byte SSH_MSG_CHANNEL_EXTENDED_DATA uint32 recipient channel uint32 data_type_code string data */ bufferParser.init(payload, 1); const recipient = bufferParser.readUInt32BE(); const type = bufferParser.readUInt32BE(); const data = bufferParser.readString(); bufferParser.clear(); if (data === undefined) { return doFatalError( self, 'Inbound: Malformed CHANNEL_EXTENDED_DATA packet' ); } self._debug && self._debug( `Inbound: CHANNEL_EXTENDED_DATA (r:${recipient}, ${data.length})` ); const handler = self._handlers.CHANNEL_EXTENDED_DATA; handler && handler(self, recipient, data, type); }, [MESSAGE.CHANNEL_EOF]: (self, payload) => { /* byte SSH_MSG_CHANNEL_EOF uint32 recipient channel */ bufferParser.init(payload, 1); const recipient = bufferParser.readUInt32BE(); bufferParser.clear(); if (recipient === undefined) { return doFatalError( self, 'Inbound: Malformed CHANNEL_EOF packet' ); } self._debug && self._debug(`Inbound: CHANNEL_EOF (r:${recipient})`); const handler = self._handlers.CHANNEL_EOF; handler && handler(self, recipient); }, [MESSAGE.CHANNEL_CLOSE]: (self, payload) => { /* byte SSH_MSG_CHANNEL_CLOSE uint32 recipient channel */ bufferParser.init(payload, 1); const recipient = bufferParser.readUInt32BE(); bufferParser.clear(); if (recipient === undefined) { return doFatalError( self, 'Inbound: Malformed CHANNEL_CLOSE packet' ); } self._debug && self._debug(`Inbound: CHANNEL_CLOSE (r:${recipient})`); const handler = self._handlers.CHANNEL_CLOSE; handler && handler(self, recipient); }, [MESSAGE.CHANNEL_REQUEST]: (self, payload) => { /* byte SSH_MSG_CHANNEL_REQUEST uint32 recipient channel string request type in US-ASCII characters only boolean want reply .... type-specific data follows */ bufferParser.init(payload, 1); const recipient = bufferParser.readUInt32BE(); const type = bufferParser.readString(true); const wantReply = bufferParser.readBool(); let data; if (wantReply !== undefined) { switch (type) { case 'exit-status': // S->C /* uint32 exit_status */ data = bufferParser.readUInt32BE(); self._debug && self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` ); break; case 'exit-signal': { // S->C /* string signal name (without the "SIG" prefix) boolean core dumped string error message in ISO-10646 UTF-8 encoding string language tag */ let signal; let coreDumped; if (self._compatFlags & COMPAT.OLD_EXIT) { /* Instead of `signal name` and `core dumped`, we have just: uint32 signal number */ const num = bufferParser.readUInt32BE(); switch (num) { case 1: signal = 'HUP'; break; case 2: signal = 'INT'; break; case 3: signal = 'QUIT'; break; case 6: signal = 'ABRT'; break; case 9: signal = 'KILL'; break; case 14: signal = 'ALRM'; break; case 15: signal = 'TERM'; break; default: if (num !== undefined) { // Unknown or OS-specific signal = `UNKNOWN (${num})`; } } coreDumped = false; } else { signal = bufferParser.readString(true); coreDumped = bufferParser.readBool(); if (coreDumped === undefined) signal = undefined; } const errorMessage = bufferParser.readString(true); if (bufferParser.skipString() !== undefined) data = { signal, coreDumped, errorMessage }; self._debug && self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${signal})` ); break; } case 'pty-req': { // C->S /* string TERM environment variable value (e.g., vt100) uint32 terminal width, characters (e.g., 80) uint32 terminal height, rows (e.g., 24) uint32 terminal width, pixels (e.g., 640) uint32 terminal height, pixels (e.g., 480) string encoded terminal modes */ const term = bufferParser.readString(true); const cols = bufferParser.readUInt32BE(); const rows = bufferParser.readUInt32BE(); const width = bufferParser.readUInt32BE(); const height = bufferParser.readUInt32BE(); const modesBinary = bufferParser.readString(); if (modesBinary !== undefined) { bufferParser.init(modesBinary, 1); let modes = {}; while (bufferParser.avail()) { const opcode = bufferParser.readByte(); if (opcode === TERMINAL_MODE.TTY_OP_END) break; const name = TERMINAL_MODE_BY_VALUE[opcode]; const value = bufferParser.readUInt32BE(); if (opcode === undefined || name === undefined || value === undefined) { modes = undefined; break; } modes[name] = value; } if (modes !== undefined) data = { term, cols, rows, width, height, modes }; } self._debug && self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` ); break; } case 'window-change': { // C->S /* uint32 terminal width, columns uint32 terminal height, rows uint32 terminal width, pixels uint32 terminal height, pixels */ const cols = bufferParser.readUInt32BE(); const rows = bufferParser.readUInt32BE(); const width = bufferParser.readUInt32BE(); const height = bufferParser.readUInt32BE(); if (height !== undefined) data = { cols, rows, width, height }; self._debug && self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` ); break; } case 'x11-req': { // C->S /* boolean single connection string x11 authentication protocol string x11 authentication cookie uint32 x11 screen number */ const single = bufferParser.readBool(); const protocol = bufferParser.readString(true); const cookie = bufferParser.readString(); const screen = bufferParser.readUInt32BE(); if (screen !== undefined) data = { single, protocol, cookie, screen }; self._debug && self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` ); break; } case 'env': { // C->S /* string variable name string variable value */ const name = bufferParser.readString(true); const value = bufferParser.readString(true); if (value !== undefined) data = { name, value }; if (self._debug) { self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ` + `${name}=${value})` ); } break; } case 'shell': // C->S data = null; // No extra data self._debug && self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` ); break; case 'exec': // C->S /* string command */ data = bufferParser.readString(true); self._debug && self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` ); break; case 'subsystem': // C->S /* string subsystem name */ data = bufferParser.readString(true); self._debug && self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` ); break; case 'signal': // C->S /* string signal name (without the "SIG" prefix) */ data = bufferParser.readString(true); self._debug && self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` ); break; case 'xon-xoff': // C->S /* boolean client can do */ data = bufferParser.readBool(); self._debug && self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` ); break; case 'auth-agent-req@openssh.com': // C-S data = null; // No extra data self._debug && self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` ); break; default: data = (bufferParser.avail() ? bufferParser.readRaw() : null); self._debug && self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` ); } } bufferParser.clear(); if (data === undefined) { return doFatalError( self, 'Inbound: Malformed CHANNEL_REQUEST packet' ); } const handler = self._handlers.CHANNEL_REQUEST; handler && handler(self, recipient, type, wantReply, data); }, [MESSAGE.CHANNEL_SUCCESS]: (self, payload) => { /* byte SSH_MSG_CHANNEL_SUCCESS uint32 recipient channel */ bufferParser.init(payload, 1); const recipient = bufferParser.readUInt32BE(); bufferParser.clear(); if (recipient === undefined) { return doFatalError( self, 'Inbound: Malformed CHANNEL_SUCCESS packet' ); } self._debug && self._debug(`Inbound: CHANNEL_SUCCESS (r:${recipient})`); const handler = self._handlers.CHANNEL_SUCCESS; handler && handler(self, recipient); }, [MESSAGE.CHANNEL_FAILURE]: (self, payload) => { /* byte SSH_MSG_CHANNEL_FAILURE uint32 recipient channel */ bufferParser.init(payload, 1); const recipient = bufferParser.readUInt32BE(); bufferParser.clear(); if (recipient === undefined) { return doFatalError( self, 'Inbound: Malformed CHANNEL_FAILURE packet' ); } self._debug && self._debug(`Inbound: CHANNEL_FAILURE (r:${recipient})`); const handler = self._handlers.CHANNEL_FAILURE; handler && handler(self, recipient); }, }; /***/ }), /***/ 65260: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const { createDiffieHellman, createDiffieHellmanGroup, createECDH, createHash, createPublicKey, diffieHellman, generateKeyPairSync, randomFillSync, } = __webpack_require__(6113); const { Ber } = __webpack_require__(90476); const { COMPAT, curve25519Supported, DEFAULT_KEX, DEFAULT_SERVER_HOST_KEY, DEFAULT_CIPHER, DEFAULT_MAC, DEFAULT_COMPRESSION, DISCONNECT_REASON, MESSAGE, } = __webpack_require__(3190); const { CIPHER_INFO, createCipher, createDecipher, MAC_INFO, } = __webpack_require__(83877); const { parseDERKey } = __webpack_require__(13781); const { bufferFill, bufferParser, convertSignature, doFatalError, FastBuffer, sigSSHToASN1, writeUInt32BE, } = __webpack_require__(39205); const { PacketReader, PacketWriter, ZlibPacketReader, ZlibPacketWriter, } = __webpack_require__(36993); let MESSAGE_HANDLERS; const GEX_MIN_BITS = 2048; // RFC 8270 const GEX_MAX_BITS = 8192; // RFC 8270 const EMPTY_BUFFER = Buffer.alloc(0); // Client/Server function kexinit(self) { /* byte SSH_MSG_KEXINIT byte[16] cookie (random bytes) name-list kex_algorithms name-list server_host_key_algorithms name-list encryption_algorithms_client_to_server name-list encryption_algorithms_server_to_client name-list mac_algorithms_client_to_server name-list mac_algorithms_server_to_client name-list compression_algorithms_client_to_server name-list compression_algorithms_server_to_client name-list languages_client_to_server name-list languages_server_to_client boolean first_kex_packet_follows uint32 0 (reserved for future extension) */ let payload; if (self._compatFlags & COMPAT.BAD_DHGEX) { const entry = self._offer.lists.kex; let kex = entry.array; let found = false; for (let i = 0; i < kex.length; ++i) { if (kex[i].includes('group-exchange')) { if (!found) { found = true; // Copy array lazily kex = kex.slice(); } kex.splice(i--, 1); } } if (found) { let len = 1 + 16 + self._offer.totalSize + 1 + 4; const newKexBuf = Buffer.from(kex.join(',')); len -= (entry.buffer.length - newKexBuf.length); const all = self._offer.lists.all; const rest = new Uint8Array( all.buffer, all.byteOffset + 4 + entry.buffer.length, all.length - (4 + entry.buffer.length) ); payload = Buffer.allocUnsafe(len); writeUInt32BE(payload, newKexBuf.length, 17); payload.set(newKexBuf, 17 + 4); payload.set(rest, 17 + 4 + newKexBuf.length); } } if (payload === undefined) { payload = Buffer.allocUnsafe(1 + 16 + self._offer.totalSize + 1 + 4); self._offer.copyAllTo(payload, 17); } self._debug && self._debug('Outbound: Sending KEXINIT'); payload[0] = MESSAGE.KEXINIT; randomFillSync(payload, 1, 16); // Zero-fill first_kex_packet_follows and reserved bytes bufferFill(payload, 0, payload.length - 5); self._kexinit = payload; // Needed to correct the starting position in allocated "packets" when packets // will be buffered due to active key exchange self._packetRW.write.allocStart = 0; // TODO: only create single buffer and set _kexinit as slice of packet instead { const p = self._packetRW.write.allocStartKEX; const packet = self._packetRW.write.alloc(payload.length, true); packet.set(payload, p); self._cipher.encrypt(self._packetRW.write.finalize(packet, true)); } } function handleKexInit(self, payload) { /* byte SSH_MSG_KEXINIT byte[16] cookie (random bytes) name-list kex_algorithms name-list server_host_key_algorithms name-list encryption_algorithms_client_to_server name-list encryption_algorithms_server_to_client name-list mac_algorithms_client_to_server name-list mac_algorithms_server_to_client name-list compression_algorithms_client_to_server name-list compression_algorithms_server_to_client name-list languages_client_to_server name-list languages_server_to_client boolean first_kex_packet_follows uint32 0 (reserved for future extension) */ const init = { kex: undefined, serverHostKey: undefined, cs: { cipher: undefined, mac: undefined, compress: undefined, lang: undefined, }, sc: { cipher: undefined, mac: undefined, compress: undefined, lang: undefined, }, }; bufferParser.init(payload, 17); if ((init.kex = bufferParser.readList()) === undefined || (init.serverHostKey = bufferParser.readList()) === undefined || (init.cs.cipher = bufferParser.readList()) === undefined || (init.sc.cipher = bufferParser.readList()) === undefined || (init.cs.mac = bufferParser.readList()) === undefined || (init.sc.mac = bufferParser.readList()) === undefined || (init.cs.compress = bufferParser.readList()) === undefined || (init.sc.compress = bufferParser.readList()) === undefined || (init.cs.lang = bufferParser.readList()) === undefined || (init.sc.lang = bufferParser.readList()) === undefined) { bufferParser.clear(); return doFatalError( self, 'Received malformed KEXINIT', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } const pos = bufferParser.pos(); const firstFollows = (pos < payload.length && payload[pos] === 1); bufferParser.clear(); const local = self._offer; const remote = init; let localKex = local.lists.kex.array; if (self._compatFlags & COMPAT.BAD_DHGEX) { let found = false; for (let i = 0; i < localKex.length; ++i) { if (localKex[i].indexOf('group-exchange') !== -1) { if (!found) { found = true; // Copy array lazily localKex = localKex.slice(); } localKex.splice(i--, 1); } } } let clientList; let serverList; let i; const debug = self._debug; debug && debug('Inbound: Handshake in progress'); // Key exchange method ======================================================= debug && debug(`Handshake: (local) KEX method: ${localKex}`); debug && debug(`Handshake: (remote) KEX method: ${remote.kex}`); let remoteExtInfoEnabled; if (self._server) { serverList = localKex; clientList = remote.kex; remoteExtInfoEnabled = (clientList.indexOf('ext-info-c') !== -1); } else { serverList = remote.kex; clientList = localKex; remoteExtInfoEnabled = (serverList.indexOf('ext-info-s') !== -1); } // Check for agreeable key exchange algorithm for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i); if (i === clientList.length) { // No suitable match found! debug && debug('Handshake: No matching key exchange algorithm'); return doFatalError( self, 'Handshake failed: no matching key exchange algorithm', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } init.kex = clientList[i]; debug && debug(`Handshake: KEX algorithm: ${clientList[i]}`); if (firstFollows && (!remote.kex.length || clientList[i] !== remote.kex[0])) { // Ignore next inbound packet, it was a wrong first guess at KEX algorithm self._skipNextInboundPacket = true; } // Server host key format ==================================================== const localSrvHostKey = local.lists.serverHostKey.array; debug && debug(`Handshake: (local) Host key format: ${localSrvHostKey}`); debug && debug( `Handshake: (remote) Host key format: ${remote.serverHostKey}` ); if (self._server) { serverList = localSrvHostKey; clientList = remote.serverHostKey; } else { serverList = remote.serverHostKey; clientList = localSrvHostKey; } // Check for agreeable server host key format for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i); if (i === clientList.length) { // No suitable match found! debug && debug('Handshake: No matching host key format'); return doFatalError( self, 'Handshake failed: no matching host key format', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } init.serverHostKey = clientList[i]; debug && debug(`Handshake: Host key format: ${clientList[i]}`); // Client->Server cipher ===================================================== const localCSCipher = local.lists.cs.cipher.array; debug && debug(`Handshake: (local) C->S cipher: ${localCSCipher}`); debug && debug(`Handshake: (remote) C->S cipher: ${remote.cs.cipher}`); if (self._server) { serverList = localCSCipher; clientList = remote.cs.cipher; } else { serverList = remote.cs.cipher; clientList = localCSCipher; } // Check for agreeable client->server cipher for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i); if (i === clientList.length) { // No suitable match found! debug && debug('Handshake: No matching C->S cipher'); return doFatalError( self, 'Handshake failed: no matching C->S cipher', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } init.cs.cipher = clientList[i]; debug && debug(`Handshake: C->S Cipher: ${clientList[i]}`); // Server->Client cipher ===================================================== const localSCCipher = local.lists.sc.cipher.array; debug && debug(`Handshake: (local) S->C cipher: ${localSCCipher}`); debug && debug(`Handshake: (remote) S->C cipher: ${remote.sc.cipher}`); if (self._server) { serverList = localSCCipher; clientList = remote.sc.cipher; } else { serverList = remote.sc.cipher; clientList = localSCCipher; } // Check for agreeable server->client cipher for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i); if (i === clientList.length) { // No suitable match found! debug && debug('Handshake: No matching S->C cipher'); return doFatalError( self, 'Handshake failed: no matching S->C cipher', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } init.sc.cipher = clientList[i]; debug && debug(`Handshake: S->C cipher: ${clientList[i]}`); // Client->Server MAC ======================================================== const localCSMAC = local.lists.cs.mac.array; debug && debug(`Handshake: (local) C->S MAC: ${localCSMAC}`); debug && debug(`Handshake: (remote) C->S MAC: ${remote.cs.mac}`); if (CIPHER_INFO[init.cs.cipher].authLen > 0) { init.cs.mac = ''; debug && debug('Handshake: C->S MAC: '); } else { if (self._server) { serverList = localCSMAC; clientList = remote.cs.mac; } else { serverList = remote.cs.mac; clientList = localCSMAC; } // Check for agreeable client->server hmac algorithm for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i); if (i === clientList.length) { // No suitable match found! debug && debug('Handshake: No matching C->S MAC'); return doFatalError( self, 'Handshake failed: no matching C->S MAC', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } init.cs.mac = clientList[i]; debug && debug(`Handshake: C->S MAC: ${clientList[i]}`); } // Server->Client MAC ======================================================== const localSCMAC = local.lists.sc.mac.array; debug && debug(`Handshake: (local) S->C MAC: ${localSCMAC}`); debug && debug(`Handshake: (remote) S->C MAC: ${remote.sc.mac}`); if (CIPHER_INFO[init.sc.cipher].authLen > 0) { init.sc.mac = ''; debug && debug('Handshake: S->C MAC: '); } else { if (self._server) { serverList = localSCMAC; clientList = remote.sc.mac; } else { serverList = remote.sc.mac; clientList = localSCMAC; } // Check for agreeable server->client hmac algorithm for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i); if (i === clientList.length) { // No suitable match found! debug && debug('Handshake: No matching S->C MAC'); return doFatalError( self, 'Handshake failed: no matching S->C MAC', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } init.sc.mac = clientList[i]; debug && debug(`Handshake: S->C MAC: ${clientList[i]}`); } // Client->Server compression ================================================ const localCSCompress = local.lists.cs.compress.array; debug && debug(`Handshake: (local) C->S compression: ${localCSCompress}`); debug && debug(`Handshake: (remote) C->S compression: ${remote.cs.compress}`); if (self._server) { serverList = localCSCompress; clientList = remote.cs.compress; } else { serverList = remote.cs.compress; clientList = localCSCompress; } // Check for agreeable client->server compression algorithm for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i); if (i === clientList.length) { // No suitable match found! debug && debug('Handshake: No matching C->S compression'); return doFatalError( self, 'Handshake failed: no matching C->S compression', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } init.cs.compress = clientList[i]; debug && debug(`Handshake: C->S compression: ${clientList[i]}`); // Server->Client compression ================================================ const localSCCompress = local.lists.sc.compress.array; debug && debug(`Handshake: (local) S->C compression: ${localSCCompress}`); debug && debug(`Handshake: (remote) S->C compression: ${remote.sc.compress}`); if (self._server) { serverList = localSCCompress; clientList = remote.sc.compress; } else { serverList = remote.sc.compress; clientList = localSCCompress; } // Check for agreeable server->client compression algorithm for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i); if (i === clientList.length) { // No suitable match found! debug && debug('Handshake: No matching S->C compression'); return doFatalError( self, 'Handshake failed: no matching S->C compression', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } init.sc.compress = clientList[i]; debug && debug(`Handshake: S->C compression: ${clientList[i]}`); init.cs.lang = ''; init.sc.lang = ''; // XXX: hack -- find a better way to do this if (self._kex) { if (!self._kexinit) { // We received a rekey request, but we haven't sent a KEXINIT in response // yet kexinit(self); } self._decipher._onPayload = onKEXPayload.bind(self, { firstPacket: false }); } self._kex = createKeyExchange(init, self, payload); self._kex.remoteExtInfoEnabled = remoteExtInfoEnabled; self._kex.start(); } const createKeyExchange = (() => { function convertToMpint(buf) { let idx = 0; let length = buf.length; while (buf[idx] === 0x00) { ++idx; --length; } let newBuf; if (buf[idx] & 0x80) { newBuf = Buffer.allocUnsafe(1 + length); newBuf[0] = 0; buf.copy(newBuf, 1, idx); buf = newBuf; } else if (length !== buf.length) { newBuf = Buffer.allocUnsafe(length); buf.copy(newBuf, 0, idx); buf = newBuf; } return buf; } class KeyExchange { constructor(negotiated, protocol, remoteKexinit) { this._protocol = protocol; this.sessionID = (protocol._kex ? protocol._kex.sessionID : undefined); this.negotiated = negotiated; this.remoteExtInfoEnabled = false; this._step = 1; this._public = null; this._dh = null; this._sentNEWKEYS = false; this._receivedNEWKEYS = false; this._finished = false; this._hostVerified = false; // Data needed for initializing cipher/decipher/etc. this._kexinit = protocol._kexinit; this._remoteKexinit = remoteKexinit; this._identRaw = protocol._identRaw; this._remoteIdentRaw = protocol._remoteIdentRaw; this._hostKey = undefined; this._dhData = undefined; this._sig = undefined; } finish(scOnly) { if (this._finished) return false; this._finished = true; const isServer = this._protocol._server; const negotiated = this.negotiated; const pubKey = this.convertPublicKey(this._dhData); let secret = this.computeSecret(this._dhData); if (secret instanceof Error) { secret.message = `Error while computing DH secret (${this.type}): ${secret.message}`; secret.level = 'handshake'; return doFatalError( this._protocol, secret, DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } const hash = createHash(this.hashName); // V_C hashString(hash, (isServer ? this._remoteIdentRaw : this._identRaw)); // "V_S" hashString(hash, (isServer ? this._identRaw : this._remoteIdentRaw)); // "I_C" hashString(hash, (isServer ? this._remoteKexinit : this._kexinit)); // "I_S" hashString(hash, (isServer ? this._kexinit : this._remoteKexinit)); // "K_S" const serverPublicHostKey = (isServer ? this._hostKey.getPublicSSH() : this._hostKey); hashString(hash, serverPublicHostKey); if (this.type === 'groupex') { // Group exchange-specific const params = this.getDHParams(); const num = Buffer.allocUnsafe(4); // min (uint32) writeUInt32BE(num, this._minBits, 0); hash.update(num); // preferred (uint32) writeUInt32BE(num, this._prefBits, 0); hash.update(num); // max (uint32) writeUInt32BE(num, this._maxBits, 0); hash.update(num); // prime hashString(hash, params.prime); // generator hashString(hash, params.generator); } // method-specific data sent by client hashString(hash, (isServer ? pubKey : this.getPublicKey())); // method-specific data sent by server const serverPublicKey = (isServer ? this.getPublicKey() : pubKey); hashString(hash, serverPublicKey); // shared secret ("K") hashString(hash, secret); // "H" const exchangeHash = hash.digest(); if (!isServer) { bufferParser.init(this._sig, 0); const sigType = bufferParser.readString(true); if (!sigType) { return doFatalError( this._protocol, 'Malformed packet while reading signature', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } if (sigType !== negotiated.serverHostKey) { return doFatalError( this._protocol, `Wrong signature type: ${sigType}, ` + `expected: ${negotiated.serverHostKey}`, 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } // "s" let sigValue = bufferParser.readString(); bufferParser.clear(); if (sigValue === undefined) { return doFatalError( this._protocol, 'Malformed packet while reading signature', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } if (!(sigValue = sigSSHToASN1(sigValue, sigType))) { return doFatalError( this._protocol, 'Malformed signature', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } let parsedHostKey; { bufferParser.init(this._hostKey, 0); const name = bufferParser.readString(true); const hostKey = this._hostKey.slice(bufferParser.pos()); bufferParser.clear(); parsedHostKey = parseDERKey(hostKey, name); if (parsedHostKey instanceof Error) { parsedHostKey.level = 'handshake'; return doFatalError( this._protocol, parsedHostKey, DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } } let hashAlgo; // Check if we need to override the default hash algorithm switch (this.negotiated.serverHostKey) { case 'rsa-sha2-256': hashAlgo = 'sha256'; break; case 'rsa-sha2-512': hashAlgo = 'sha512'; break; } this._protocol._debug && this._protocol._debug('Verifying signature ...'); const verified = parsedHostKey.verify(exchangeHash, sigValue, hashAlgo); if (verified !== true) { if (verified instanceof Error) { this._protocol._debug && this._protocol._debug( `Signature verification failed: ${verified.stack}` ); } else { this._protocol._debug && this._protocol._debug( 'Signature verification failed' ); } return doFatalError( this._protocol, 'Handshake failed: signature verification failed', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } this._protocol._debug && this._protocol._debug('Verified signature'); } else { // Server let hashAlgo; // Check if we need to override the default hash algorithm switch (this.negotiated.serverHostKey) { case 'rsa-sha2-256': hashAlgo = 'sha256'; break; case 'rsa-sha2-512': hashAlgo = 'sha512'; break; } this._protocol._debug && this._protocol._debug( 'Generating signature ...' ); let signature = this._hostKey.sign(exchangeHash, hashAlgo); if (signature instanceof Error) { return doFatalError( this._protocol, 'Handshake failed: signature generation failed for ' + `${this._hostKey.type} host key: ${signature.message}`, 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } signature = convertSignature(signature, this._hostKey.type); if (signature === false) { return doFatalError( this._protocol, 'Handshake failed: signature conversion failed for ' + `${this._hostKey.type} host key`, 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } // Send KEX reply /* byte SSH_MSG_KEXDH_REPLY / SSH_MSG_KEX_DH_GEX_REPLY / SSH_MSG_KEX_ECDH_REPLY string server public host key and certificates (K_S) string string signature of H */ const sigType = this.negotiated.serverHostKey; const sigTypeLen = Buffer.byteLength(sigType); const sigLen = 4 + sigTypeLen + 4 + signature.length; let p = this._protocol._packetRW.write.allocStartKEX; const packet = this._protocol._packetRW.write.alloc( 1 + 4 + serverPublicHostKey.length + 4 + serverPublicKey.length + 4 + sigLen, true ); packet[p] = MESSAGE.KEXDH_REPLY; writeUInt32BE(packet, serverPublicHostKey.length, ++p); packet.set(serverPublicHostKey, p += 4); writeUInt32BE(packet, serverPublicKey.length, p += serverPublicHostKey.length); packet.set(serverPublicKey, p += 4); writeUInt32BE(packet, sigLen, p += serverPublicKey.length); writeUInt32BE(packet, sigTypeLen, p += 4); packet.utf8Write(sigType, p += 4, sigTypeLen); writeUInt32BE(packet, signature.length, p += sigTypeLen); packet.set(signature, p += 4); if (this._protocol._debug) { let type; switch (this.type) { case 'group': type = 'KEXDH_REPLY'; break; case 'groupex': type = 'KEXDH_GEX_REPLY'; break; default: type = 'KEXECDH_REPLY'; } this._protocol._debug(`Outbound: Sending ${type}`); } this._protocol._cipher.encrypt( this._protocol._packetRW.write.finalize(packet, true) ); } if (isServer || !scOnly) trySendNEWKEYS(this); let hsCipherConfig; let hsWrite; const completeHandshake = (partial) => { if (hsCipherConfig) { trySendNEWKEYS(this); hsCipherConfig.outbound.seqno = this._protocol._cipher.outSeqno; this._protocol._cipher.free(); this._protocol._cipher = createCipher(hsCipherConfig); this._protocol._packetRW.write = hsWrite; hsCipherConfig = undefined; hsWrite = undefined; this._protocol._onHandshakeComplete(negotiated); return false; } if (!this.sessionID) this.sessionID = exchangeHash; { const newSecret = Buffer.allocUnsafe(4 + secret.length); writeUInt32BE(newSecret, secret.length, 0); newSecret.set(secret, 4); secret = newSecret; } // Initialize new ciphers, deciphers, etc. const csCipherInfo = CIPHER_INFO[negotiated.cs.cipher]; const scCipherInfo = CIPHER_INFO[negotiated.sc.cipher]; const csIV = generateKEXVal(csCipherInfo.ivLen, this.hashName, secret, exchangeHash, this.sessionID, 'A'); const scIV = generateKEXVal(scCipherInfo.ivLen, this.hashName, secret, exchangeHash, this.sessionID, 'B'); const csKey = generateKEXVal(csCipherInfo.keyLen, this.hashName, secret, exchangeHash, this.sessionID, 'C'); const scKey = generateKEXVal(scCipherInfo.keyLen, this.hashName, secret, exchangeHash, this.sessionID, 'D'); let csMacInfo; let csMacKey; if (!csCipherInfo.authLen) { csMacInfo = MAC_INFO[negotiated.cs.mac]; csMacKey = generateKEXVal(csMacInfo.len, this.hashName, secret, exchangeHash, this.sessionID, 'E'); } let scMacInfo; let scMacKey; if (!scCipherInfo.authLen) { scMacInfo = MAC_INFO[negotiated.sc.mac]; scMacKey = generateKEXVal(scMacInfo.len, this.hashName, secret, exchangeHash, this.sessionID, 'F'); } const config = { inbound: { onPayload: this._protocol._onPayload, seqno: this._protocol._decipher.inSeqno, decipherInfo: (!isServer ? scCipherInfo : csCipherInfo), decipherIV: (!isServer ? scIV : csIV), decipherKey: (!isServer ? scKey : csKey), macInfo: (!isServer ? scMacInfo : csMacInfo), macKey: (!isServer ? scMacKey : csMacKey), }, outbound: { onWrite: this._protocol._onWrite, seqno: this._protocol._cipher.outSeqno, cipherInfo: (isServer ? scCipherInfo : csCipherInfo), cipherIV: (isServer ? scIV : csIV), cipherKey: (isServer ? scKey : csKey), macInfo: (isServer ? scMacInfo : csMacInfo), macKey: (isServer ? scMacKey : csMacKey), }, }; this._protocol._decipher.free(); hsCipherConfig = config; this._protocol._decipher = createDecipher(config); const rw = { read: undefined, write: undefined, }; switch (negotiated.cs.compress) { case 'zlib': // starts immediately if (isServer) rw.read = new ZlibPacketReader(); else rw.write = new ZlibPacketWriter(this._protocol); break; case 'zlib@openssh.com': // Starts after successful user authentication if (this._protocol._authenticated) { // If a rekey happens and this compression method is selected and // we already authenticated successfully, we need to start // immediately instead if (isServer) rw.read = new ZlibPacketReader(); else rw.write = new ZlibPacketWriter(this._protocol); break; } // FALLTHROUGH default: // none -- never any compression/decompression if (isServer) rw.read = new PacketReader(); else rw.write = new PacketWriter(this._protocol); } switch (negotiated.sc.compress) { case 'zlib': // starts immediately if (isServer) rw.write = new ZlibPacketWriter(this._protocol); else rw.read = new ZlibPacketReader(); break; case 'zlib@openssh.com': // Starts after successful user authentication if (this._protocol._authenticated) { // If a rekey happens and this compression method is selected and // we already authenticated successfully, we need to start // immediately instead if (isServer) rw.write = new ZlibPacketWriter(this._protocol); else rw.read = new ZlibPacketReader(); break; } // FALLTHROUGH default: // none -- never any compression/decompression if (isServer) rw.write = new PacketWriter(this._protocol); else rw.read = new PacketReader(); } this._protocol._packetRW.read.cleanup(); this._protocol._packetRW.write.cleanup(); this._protocol._packetRW.read = rw.read; hsWrite = rw.write; // Cleanup/reset various state this._public = null; this._dh = null; this._kexinit = this._protocol._kexinit = undefined; this._remoteKexinit = undefined; this._identRaw = undefined; this._remoteIdentRaw = undefined; this._hostKey = undefined; this._dhData = undefined; this._sig = undefined; if (!partial) return completeHandshake(); return false; }; if (isServer || scOnly) this.finish = completeHandshake; if (!isServer) return completeHandshake(scOnly); } start() { if (!this._protocol._server) { if (this._protocol._debug) { let type; switch (this.type) { case 'group': type = 'KEXDH_INIT'; break; default: type = 'KEXECDH_INIT'; } this._protocol._debug(`Outbound: Sending ${type}`); } const pubKey = this.getPublicKey(); let p = this._protocol._packetRW.write.allocStartKEX; const packet = this._protocol._packetRW.write.alloc( 1 + 4 + pubKey.length, true ); packet[p] = MESSAGE.KEXDH_INIT; writeUInt32BE(packet, pubKey.length, ++p); packet.set(pubKey, p += 4); this._protocol._cipher.encrypt( this._protocol._packetRW.write.finalize(packet, true) ); } } getPublicKey() { this.generateKeys(); const key = this._public; if (key) return this.convertPublicKey(key); } convertPublicKey(key) { let newKey; let idx = 0; let len = key.length; while (key[idx] === 0x00) { ++idx; --len; } if (key[idx] & 0x80) { newKey = Buffer.allocUnsafe(1 + len); newKey[0] = 0; key.copy(newKey, 1, idx); return newKey; } if (len !== key.length) { newKey = Buffer.allocUnsafe(len); key.copy(newKey, 0, idx); key = newKey; } return key; } computeSecret(otherPublicKey) { this.generateKeys(); try { return convertToMpint(this._dh.computeSecret(otherPublicKey)); } catch (ex) { return ex; } } parse(payload) { const type = payload[0]; switch (this._step) { case 1: if (this._protocol._server) { // Server if (type !== MESSAGE.KEXDH_INIT) { return doFatalError( this._protocol, `Received packet ${type} instead of ${MESSAGE.KEXDH_INIT}`, 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } this._protocol._debug && this._protocol._debug( 'Received DH Init' ); /* byte SSH_MSG_KEXDH_INIT / SSH_MSG_KEX_ECDH_INIT string */ bufferParser.init(payload, 1); const dhData = bufferParser.readString(); bufferParser.clear(); if (dhData === undefined) { return doFatalError( this._protocol, 'Received malformed KEX*_INIT', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } // Client public key this._dhData = dhData; let hostKey = this._protocol._hostKeys[this.negotiated.serverHostKey]; if (Array.isArray(hostKey)) hostKey = hostKey[0]; this._hostKey = hostKey; this.finish(); } else { // Client if (type !== MESSAGE.KEXDH_REPLY) { return doFatalError( this._protocol, `Received packet ${type} instead of ${MESSAGE.KEXDH_REPLY}`, 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } this._protocol._debug && this._protocol._debug( 'Received DH Reply' ); /* byte SSH_MSG_KEXDH_REPLY / SSH_MSG_KEX_DH_GEX_REPLY / SSH_MSG_KEX_ECDH_REPLY string server public host key and certificates (K_S) string string signature of H */ bufferParser.init(payload, 1); let hostPubKey; let dhData; let sig; if ((hostPubKey = bufferParser.readString()) === undefined || (dhData = bufferParser.readString()) === undefined || (sig = bufferParser.readString()) === undefined) { bufferParser.clear(); return doFatalError( this._protocol, 'Received malformed KEX*_REPLY', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } bufferParser.clear(); // Check that the host public key type matches what was negotiated // during KEXINIT swap bufferParser.init(hostPubKey, 0); const hostPubKeyType = bufferParser.readString(true); bufferParser.clear(); if (hostPubKeyType === undefined) { return doFatalError( this._protocol, 'Received malformed host public key', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } if (hostPubKeyType !== this.negotiated.serverHostKey) { // Check if we need to make an exception switch (this.negotiated.serverHostKey) { case 'rsa-sha2-256': case 'rsa-sha2-512': if (hostPubKeyType === 'ssh-rsa') break; // FALLTHROUGH default: return doFatalError( this._protocol, 'Host key does not match negotiated type', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } } this._hostKey = hostPubKey; this._dhData = dhData; this._sig = sig; let checked = false; let ret; if (this._protocol._hostVerifier === undefined) { ret = true; this._protocol._debug && this._protocol._debug( 'Host accepted by default (no verification)' ); } else { ret = this._protocol._hostVerifier(hostPubKey, (permitted) => { if (checked) return; checked = true; if (permitted === false) { this._protocol._debug && this._protocol._debug( 'Host denied (verification failed)' ); return doFatalError( this._protocol, 'Host denied (verification failed)', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } this._protocol._debug && this._protocol._debug( 'Host accepted (verified)' ); this._hostVerified = true; if (this._receivedNEWKEYS) this.finish(); else trySendNEWKEYS(this); }); } if (ret === undefined) { // Async host verification ++this._step; return; } checked = true; if (ret === false) { this._protocol._debug && this._protocol._debug( 'Host denied (verification failed)' ); return doFatalError( this._protocol, 'Host denied (verification failed)', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } this._protocol._debug && this._protocol._debug( 'Host accepted (verified)' ); this._hostVerified = true; trySendNEWKEYS(this); } ++this._step; break; case 2: if (type !== MESSAGE.NEWKEYS) { return doFatalError( this._protocol, `Received packet ${type} instead of ${MESSAGE.NEWKEYS}`, 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } this._protocol._debug && this._protocol._debug( 'Inbound: NEWKEYS' ); this._receivedNEWKEYS = true; ++this._step; return this.finish(!this._protocol._server && !this._hostVerified); default: return doFatalError( this._protocol, `Received unexpected packet ${type} after NEWKEYS`, 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } } } class Curve25519Exchange extends KeyExchange { constructor(hashName, ...args) { super(...args); this.type = '25519'; this.hashName = hashName; this._keys = null; } generateKeys() { if (!this._keys) this._keys = generateKeyPairSync('x25519'); } getPublicKey() { this.generateKeys(); const key = this._keys.publicKey.export({ type: 'spki', format: 'der' }); return key.slice(-32); // HACK: avoids parsing DER/BER header } convertPublicKey(key) { let newKey; let idx = 0; let len = key.length; while (key[idx] === 0x00) { ++idx; --len; } if (key.length === 32) return key; if (len !== key.length) { newKey = Buffer.allocUnsafe(len); key.copy(newKey, 0, idx); key = newKey; } return key; } computeSecret(otherPublicKey) { this.generateKeys(); try { const asnWriter = new Ber.Writer(); asnWriter.startSequence(); // algorithm asnWriter.startSequence(); asnWriter.writeOID('1.3.101.110'); // id-X25519 asnWriter.endSequence(); // PublicKey asnWriter.startSequence(Ber.BitString); asnWriter.writeByte(0x00); // XXX: hack to write a raw buffer without a tag -- yuck asnWriter._ensure(otherPublicKey.length); otherPublicKey.copy(asnWriter._buf, asnWriter._offset, 0, otherPublicKey.length); asnWriter._offset += otherPublicKey.length; asnWriter.endSequence(); asnWriter.endSequence(); return convertToMpint(diffieHellman({ privateKey: this._keys.privateKey, publicKey: createPublicKey({ key: asnWriter.buffer, type: 'spki', format: 'der', }), })); } catch (ex) { return ex; } } } class ECDHExchange extends KeyExchange { constructor(curveName, hashName, ...args) { super(...args); this.type = 'ecdh'; this.curveName = curveName; this.hashName = hashName; } generateKeys() { if (!this._dh) { this._dh = createECDH(this.curveName); this._public = this._dh.generateKeys(); } } } class DHGroupExchange extends KeyExchange { constructor(hashName, ...args) { super(...args); this.type = 'groupex'; this.hashName = hashName; this._prime = null; this._generator = null; this._minBits = GEX_MIN_BITS; this._prefBits = dhEstimate(this.negotiated); if (this._protocol._compatFlags & COMPAT.BUG_DHGEX_LARGE) this._prefBits = Math.min(this._prefBits, 4096); this._maxBits = GEX_MAX_BITS; } start() { if (this._protocol._server) return; this._protocol._debug && this._protocol._debug( 'Outbound: Sending KEXDH_GEX_REQUEST' ); let p = this._protocol._packetRW.write.allocStartKEX; const packet = this._protocol._packetRW.write.alloc( 1 + 4 + 4 + 4, true ); packet[p] = MESSAGE.KEXDH_GEX_REQUEST; writeUInt32BE(packet, this._minBits, ++p); writeUInt32BE(packet, this._prefBits, p += 4); writeUInt32BE(packet, this._maxBits, p += 4); this._protocol._cipher.encrypt( this._protocol._packetRW.write.finalize(packet, true) ); } generateKeys() { if (!this._dh && this._prime && this._generator) { this._dh = createDiffieHellman(this._prime, this._generator); this._public = this._dh.generateKeys(); } } setDHParams(prime, generator) { if (!Buffer.isBuffer(prime)) throw new Error('Invalid prime value'); if (!Buffer.isBuffer(generator)) throw new Error('Invalid generator value'); this._prime = prime; this._generator = generator; } getDHParams() { if (this._dh) { return { prime: convertToMpint(this._dh.getPrime()), generator: convertToMpint(this._dh.getGenerator()), }; } } parse(payload) { const type = payload[0]; switch (this._step) { case 1: { if (this._protocol._server) { if (type !== MESSAGE.KEXDH_GEX_REQUEST) { return doFatalError( this._protocol, `Received packet ${type} instead of ` + MESSAGE.KEXDH_GEX_REQUEST, 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } // TODO: allow user implementation to provide safe prime and // generator on demand to support group exchange on server side return doFatalError( this._protocol, 'Group exchange not implemented for server', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } if (type !== MESSAGE.KEXDH_GEX_GROUP) { return doFatalError( this._protocol, `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_GROUP}`, 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } this._protocol._debug && this._protocol._debug( 'Received DH GEX Group' ); /* byte SSH_MSG_KEX_DH_GEX_GROUP mpint p, safe prime mpint g, generator for subgroup in GF(p) */ bufferParser.init(payload, 1); let prime; let gen; if ((prime = bufferParser.readString()) === undefined || (gen = bufferParser.readString()) === undefined) { bufferParser.clear(); return doFatalError( this._protocol, 'Received malformed KEXDH_GEX_GROUP', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } bufferParser.clear(); // TODO: validate prime this.setDHParams(prime, gen); this.generateKeys(); const pubkey = this.getPublicKey(); this._protocol._debug && this._protocol._debug( 'Outbound: Sending KEXDH_GEX_INIT' ); let p = this._protocol._packetRW.write.allocStartKEX; const packet = this._protocol._packetRW.write.alloc(1 + 4 + pubkey.length, true); packet[p] = MESSAGE.KEXDH_GEX_INIT; writeUInt32BE(packet, pubkey.length, ++p); packet.set(pubkey, p += 4); this._protocol._cipher.encrypt( this._protocol._packetRW.write.finalize(packet, true) ); ++this._step; break; } case 2: if (this._protocol._server) { if (type !== MESSAGE.KEXDH_GEX_INIT) { return doFatalError( this._protocol, `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_INIT}`, 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } this._protocol._debug && this._protocol._debug( 'Received DH GEX Init' ); return doFatalError( this._protocol, 'Group exchange not implemented for server', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } else if (type !== MESSAGE.KEXDH_GEX_REPLY) { return doFatalError( this._protocol, `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_REPLY}`, 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } this._protocol._debug && this._protocol._debug( 'Received DH GEX Reply' ); this._step = 1; payload[0] = MESSAGE.KEXDH_REPLY; this.parse = KeyExchange.prototype.parse; this.parse(payload); } } } class DHExchange extends KeyExchange { constructor(groupName, hashName, ...args) { super(...args); this.type = 'group'; this.groupName = groupName; this.hashName = hashName; } start() { if (!this._protocol._server) { this._protocol._debug && this._protocol._debug( 'Outbound: Sending KEXDH_INIT' ); const pubKey = this.getPublicKey(); let p = this._protocol._packetRW.write.allocStartKEX; const packet = this._protocol._packetRW.write.alloc(1 + 4 + pubKey.length, true); packet[p] = MESSAGE.KEXDH_INIT; writeUInt32BE(packet, pubKey.length, ++p); packet.set(pubKey, p += 4); this._protocol._cipher.encrypt( this._protocol._packetRW.write.finalize(packet, true) ); } } generateKeys() { if (!this._dh) { this._dh = createDiffieHellmanGroup(this.groupName); this._public = this._dh.generateKeys(); } } getDHParams() { if (this._dh) { return { prime: convertToMpint(this._dh.getPrime()), generator: convertToMpint(this._dh.getGenerator()), }; } } } return (negotiated, ...args) => { if (typeof negotiated !== 'object' || negotiated === null) throw new Error('Invalid negotiated argument'); const kexType = negotiated.kex; if (typeof kexType === 'string') { args = [negotiated, ...args]; switch (kexType) { case 'curve25519-sha256': case 'curve25519-sha256@libssh.org': if (!curve25519Supported) break; return new Curve25519Exchange('sha256', ...args); case 'ecdh-sha2-nistp256': return new ECDHExchange('prime256v1', 'sha256', ...args); case 'ecdh-sha2-nistp384': return new ECDHExchange('secp384r1', 'sha384', ...args); case 'ecdh-sha2-nistp521': return new ECDHExchange('secp521r1', 'sha512', ...args); case 'diffie-hellman-group1-sha1': return new DHExchange('modp2', 'sha1', ...args); case 'diffie-hellman-group14-sha1': return new DHExchange('modp14', 'sha1', ...args); case 'diffie-hellman-group14-sha256': return new DHExchange('modp14', 'sha256', ...args); case 'diffie-hellman-group15-sha512': return new DHExchange('modp15', 'sha512', ...args); case 'diffie-hellman-group16-sha512': return new DHExchange('modp16', 'sha512', ...args); case 'diffie-hellman-group17-sha512': return new DHExchange('modp17', 'sha512', ...args); case 'diffie-hellman-group18-sha512': return new DHExchange('modp18', 'sha512', ...args); case 'diffie-hellman-group-exchange-sha1': return new DHGroupExchange('sha1', ...args); case 'diffie-hellman-group-exchange-sha256': return new DHGroupExchange('sha256', ...args); } throw new Error(`Unsupported key exchange algorithm: ${kexType}`); } throw new Error(`Invalid key exchange type: ${kexType}`); }; })(); const KexInit = (() => { const KEX_PROPERTY_NAMES = [ 'kex', 'serverHostKey', ['cs', 'cipher' ], ['sc', 'cipher' ], ['cs', 'mac' ], ['sc', 'mac' ], ['cs', 'compress' ], ['sc', 'compress' ], ['cs', 'lang' ], ['sc', 'lang' ], ]; return class KexInit { constructor(obj) { if (typeof obj !== 'object' || obj === null) throw new TypeError('Argument must be an object'); const lists = { kex: undefined, serverHostKey: undefined, cs: { cipher: undefined, mac: undefined, compress: undefined, lang: undefined, }, sc: { cipher: undefined, mac: undefined, compress: undefined, lang: undefined, }, all: undefined, }; let totalSize = 0; for (const prop of KEX_PROPERTY_NAMES) { let base; let val; let desc; let key; if (typeof prop === 'string') { base = lists; val = obj[prop]; desc = key = prop; } else { const parent = prop[0]; base = lists[parent]; key = prop[1]; val = obj[parent][key]; desc = `${parent}.${key}`; } const entry = { array: undefined, buffer: undefined }; if (Buffer.isBuffer(val)) { entry.array = ('' + val).split(','); entry.buffer = val; totalSize += 4 + val.length; } else { if (typeof val === 'string') val = val.split(','); if (Array.isArray(val)) { entry.array = val; entry.buffer = Buffer.from(val.join(',')); } else { throw new TypeError(`Invalid \`${desc}\` type: ${typeof val}`); } totalSize += 4 + entry.buffer.length; } base[key] = entry; } const all = Buffer.allocUnsafe(totalSize); lists.all = all; let allPos = 0; for (const prop of KEX_PROPERTY_NAMES) { let data; if (typeof prop === 'string') data = lists[prop].buffer; else data = lists[prop[0]][prop[1]].buffer; allPos = writeUInt32BE(all, data.length, allPos); all.set(data, allPos); allPos += data.length; } this.totalSize = totalSize; this.lists = lists; } copyAllTo(buf, offset) { const src = this.lists.all; if (typeof offset !== 'number') throw new TypeError(`Invalid offset value: ${typeof offset}`); if (buf.length - offset < src.length) throw new Error('Insufficient space to copy list'); buf.set(src, offset); return src.length; } }; })(); const hashString = (() => { const LEN = Buffer.allocUnsafe(4); return (hash, buf) => { writeUInt32BE(LEN, buf.length, 0); hash.update(LEN); hash.update(buf); }; })(); function generateKEXVal(len, hashName, secret, exchangeHash, sessionID, char) { let ret; if (len) { let digest = createHash(hashName) .update(secret) .update(exchangeHash) .update(char) .update(sessionID) .digest(); while (digest.length < len) { const chunk = createHash(hashName) .update(secret) .update(exchangeHash) .update(digest) .digest(); const extended = Buffer.allocUnsafe(digest.length + chunk.length); extended.set(digest, 0); extended.set(chunk, digest.length); digest = extended; } if (digest.length === len) ret = digest; else ret = new FastBuffer(digest.buffer, digest.byteOffset, len); } else { ret = EMPTY_BUFFER; } return ret; } function onKEXPayload(state, payload) { // XXX: move this to the Decipher implementations? if (payload.length === 0) { this._debug && this._debug('Inbound: Skipping empty packet payload'); return; } if (this._skipNextInboundPacket) { this._skipNextInboundPacket = false; return; } payload = this._packetRW.read.read(payload); const type = payload[0]; switch (type) { case MESSAGE.DISCONNECT: case MESSAGE.IGNORE: case MESSAGE.UNIMPLEMENTED: case MESSAGE.DEBUG: if (!MESSAGE_HANDLERS) MESSAGE_HANDLERS = __webpack_require__(92908); return MESSAGE_HANDLERS[type](this, payload); case MESSAGE.KEXINIT: if (!state.firstPacket) { return doFatalError( this, 'Received extra KEXINIT during handshake', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } state.firstPacket = false; return handleKexInit(this, payload); default: if (type < 20 || type > 49) { return doFatalError( this, `Received unexpected packet type ${type}`, 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } } return this._kex.parse(payload); } function dhEstimate(neg) { const csCipher = CIPHER_INFO[neg.cs.cipher]; const scCipher = CIPHER_INFO[neg.sc.cipher]; // XXX: if OpenSSH's `umac-*` MACs are ever supported, their key lengths will // also need to be considered when calculating `bits` const bits = Math.max( 0, (csCipher.sslName === 'des-ede3-cbc' ? 14 : csCipher.keyLen), csCipher.blockLen, csCipher.ivLen, (scCipher.sslName === 'des-ede3-cbc' ? 14 : scCipher.keyLen), scCipher.blockLen, scCipher.ivLen ) * 8; if (bits <= 112) return 2048; if (bits <= 128) return 3072; if (bits <= 192) return 7680; return 8192; } function trySendNEWKEYS(kex) { if (!kex._sentNEWKEYS) { kex._protocol._debug && kex._protocol._debug( 'Outbound: Sending NEWKEYS' ); const p = kex._protocol._packetRW.write.allocStartKEX; const packet = kex._protocol._packetRW.write.alloc(1, true); packet[p] = MESSAGE.NEWKEYS; kex._protocol._cipher.encrypt( kex._protocol._packetRW.write.finalize(packet, true) ); kex._sentNEWKEYS = true; } } module.exports = { KexInit, kexinit, onKEXPayload, DEFAULT_KEXINIT_CLIENT: new KexInit({ kex: DEFAULT_KEX.concat(['ext-info-c']), serverHostKey: DEFAULT_SERVER_HOST_KEY, cs: { cipher: DEFAULT_CIPHER, mac: DEFAULT_MAC, compress: DEFAULT_COMPRESSION, lang: [], }, sc: { cipher: DEFAULT_CIPHER, mac: DEFAULT_MAC, compress: DEFAULT_COMPRESSION, lang: [], }, }), DEFAULT_KEXINIT_SERVER: new KexInit({ kex: DEFAULT_KEX, serverHostKey: DEFAULT_SERVER_HOST_KEY, cs: { cipher: DEFAULT_CIPHER, mac: DEFAULT_MAC, compress: DEFAULT_COMPRESSION, lang: [], }, sc: { cipher: DEFAULT_CIPHER, mac: DEFAULT_MAC, compress: DEFAULT_COMPRESSION, lang: [], }, }), HANDLERS: { [MESSAGE.KEXINIT]: handleKexInit, }, }; /***/ }), /***/ 13781: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // TODO: // * utilize `crypto.create(Private|Public)Key()` and `keyObject.export()` // * handle multi-line header values (OpenSSH)? // * more thorough validation? const { createDecipheriv, createECDH, createHash, createHmac, createSign, createVerify, getCiphers, sign: sign_, verify: verify_, } = __webpack_require__(6113); const supportedOpenSSLCiphers = getCiphers(); const { Ber } = __webpack_require__(90476); const bcrypt_pbkdf = __webpack_require__(62703).pbkdf; const { CIPHER_INFO } = __webpack_require__(83877); const { eddsaSupported, SUPPORTED_CIPHER } = __webpack_require__(3190); const { bufferSlice, makeBufferParser, readString, readUInt32BE, writeUInt32BE, } = __webpack_require__(39205); const SYM_HASH_ALGO = Symbol('Hash Algorithm'); const SYM_PRIV_PEM = Symbol('Private key PEM'); const SYM_PUB_PEM = Symbol('Public key PEM'); const SYM_PUB_SSH = Symbol('Public key SSH'); const SYM_DECRYPTED = Symbol('Decrypted Key'); // Create OpenSSL cipher name -> SSH cipher name conversion table const CIPHER_INFO_OPENSSL = Object.create(null); { const keys = Object.keys(CIPHER_INFO); for (let i = 0; i < keys.length; ++i) { const cipherName = CIPHER_INFO[keys[i]].sslName; if (!cipherName || CIPHER_INFO_OPENSSL[cipherName]) continue; CIPHER_INFO_OPENSSL[cipherName] = CIPHER_INFO[keys[i]]; } } const binaryKeyParser = makeBufferParser(); function makePEM(type, data) { data = data.base64Slice(0, data.length); let formatted = data.replace(/.{64}/g, '$&\n'); if (data.length & 63) formatted += '\n'; return `-----BEGIN ${type} KEY-----\n${formatted}-----END ${type} KEY-----`; } function combineBuffers(buf1, buf2) { const result = Buffer.allocUnsafe(buf1.length + buf2.length); result.set(buf1, 0); result.set(buf2, buf1.length); return result; } function skipFields(buf, nfields) { const bufLen = buf.length; let pos = (buf._pos || 0); for (let i = 0; i < nfields; ++i) { const left = (bufLen - pos); if (pos >= bufLen || left < 4) return false; const len = readUInt32BE(buf, pos); if (left < 4 + len) return false; pos += 4 + len; } buf._pos = pos; return true; } function genOpenSSLRSAPub(n, e) { const asnWriter = new Ber.Writer(); asnWriter.startSequence(); // algorithm asnWriter.startSequence(); asnWriter.writeOID('1.2.840.113549.1.1.1'); // rsaEncryption // algorithm parameters (RSA has none) asnWriter.writeNull(); asnWriter.endSequence(); // subjectPublicKey asnWriter.startSequence(Ber.BitString); asnWriter.writeByte(0x00); asnWriter.startSequence(); asnWriter.writeBuffer(n, Ber.Integer); asnWriter.writeBuffer(e, Ber.Integer); asnWriter.endSequence(); asnWriter.endSequence(); asnWriter.endSequence(); return makePEM('PUBLIC', asnWriter.buffer); } function genOpenSSHRSAPub(n, e) { const publicKey = Buffer.allocUnsafe(4 + 7 + 4 + e.length + 4 + n.length); writeUInt32BE(publicKey, 7, 0); publicKey.utf8Write('ssh-rsa', 4, 7); let i = 4 + 7; writeUInt32BE(publicKey, e.length, i); publicKey.set(e, i += 4); writeUInt32BE(publicKey, n.length, i += e.length); publicKey.set(n, i + 4); return publicKey; } const genOpenSSLRSAPriv = (() => { function genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp) { const asnWriter = new Ber.Writer(); asnWriter.startSequence(); asnWriter.writeInt(0x00, Ber.Integer); asnWriter.writeBuffer(n, Ber.Integer); asnWriter.writeBuffer(e, Ber.Integer); asnWriter.writeBuffer(d, Ber.Integer); asnWriter.writeBuffer(p, Ber.Integer); asnWriter.writeBuffer(q, Ber.Integer); asnWriter.writeBuffer(dmp1, Ber.Integer); asnWriter.writeBuffer(dmq1, Ber.Integer); asnWriter.writeBuffer(iqmp, Ber.Integer); asnWriter.endSequence(); return asnWriter.buffer; } function bigIntFromBuffer(buf) { return BigInt(`0x${buf.hexSlice(0, buf.length)}`); } function bigIntToBuffer(bn) { let hex = bn.toString(16); if ((hex.length & 1) !== 0) { hex = `0${hex}`; } else { const sigbit = hex.charCodeAt(0); // BER/DER integers require leading zero byte to denote a positive value // when first byte >= 0x80 if (sigbit === 56/* '8' */ || sigbit === 57/* '9' */ || (sigbit >= 97/* 'a' */ && sigbit <= 102/* 'f' */)) { hex = `00${hex}`; } } return Buffer.from(hex, 'hex'); } return function genOpenSSLRSAPriv(n, e, d, iqmp, p, q) { const bn_d = bigIntFromBuffer(d); const dmp1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(p) - 1n)); const dmq1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(q) - 1n)); return makePEM('RSA PRIVATE', genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp)); }; })(); function genOpenSSLDSAPub(p, q, g, y) { const asnWriter = new Ber.Writer(); asnWriter.startSequence(); // algorithm asnWriter.startSequence(); asnWriter.writeOID('1.2.840.10040.4.1'); // id-dsa // algorithm parameters asnWriter.startSequence(); asnWriter.writeBuffer(p, Ber.Integer); asnWriter.writeBuffer(q, Ber.Integer); asnWriter.writeBuffer(g, Ber.Integer); asnWriter.endSequence(); asnWriter.endSequence(); // subjectPublicKey asnWriter.startSequence(Ber.BitString); asnWriter.writeByte(0x00); asnWriter.writeBuffer(y, Ber.Integer); asnWriter.endSequence(); asnWriter.endSequence(); return makePEM('PUBLIC', asnWriter.buffer); } function genOpenSSHDSAPub(p, q, g, y) { const publicKey = Buffer.allocUnsafe( 4 + 7 + 4 + p.length + 4 + q.length + 4 + g.length + 4 + y.length ); writeUInt32BE(publicKey, 7, 0); publicKey.utf8Write('ssh-dss', 4, 7); let i = 4 + 7; writeUInt32BE(publicKey, p.length, i); publicKey.set(p, i += 4); writeUInt32BE(publicKey, q.length, i += p.length); publicKey.set(q, i += 4); writeUInt32BE(publicKey, g.length, i += q.length); publicKey.set(g, i += 4); writeUInt32BE(publicKey, y.length, i += g.length); publicKey.set(y, i + 4); return publicKey; } function genOpenSSLDSAPriv(p, q, g, y, x) { const asnWriter = new Ber.Writer(); asnWriter.startSequence(); asnWriter.writeInt(0x00, Ber.Integer); asnWriter.writeBuffer(p, Ber.Integer); asnWriter.writeBuffer(q, Ber.Integer); asnWriter.writeBuffer(g, Ber.Integer); asnWriter.writeBuffer(y, Ber.Integer); asnWriter.writeBuffer(x, Ber.Integer); asnWriter.endSequence(); return makePEM('DSA PRIVATE', asnWriter.buffer); } function genOpenSSLEdPub(pub) { const asnWriter = new Ber.Writer(); asnWriter.startSequence(); // algorithm asnWriter.startSequence(); asnWriter.writeOID('1.3.101.112'); // id-Ed25519 asnWriter.endSequence(); // PublicKey asnWriter.startSequence(Ber.BitString); asnWriter.writeByte(0x00); // XXX: hack to write a raw buffer without a tag -- yuck asnWriter._ensure(pub.length); asnWriter._buf.set(pub, asnWriter._offset); asnWriter._offset += pub.length; asnWriter.endSequence(); asnWriter.endSequence(); return makePEM('PUBLIC', asnWriter.buffer); } function genOpenSSHEdPub(pub) { const publicKey = Buffer.allocUnsafe(4 + 11 + 4 + pub.length); writeUInt32BE(publicKey, 11, 0); publicKey.utf8Write('ssh-ed25519', 4, 11); writeUInt32BE(publicKey, pub.length, 15); publicKey.set(pub, 19); return publicKey; } function genOpenSSLEdPriv(priv) { const asnWriter = new Ber.Writer(); asnWriter.startSequence(); // version asnWriter.writeInt(0x00, Ber.Integer); // algorithm asnWriter.startSequence(); asnWriter.writeOID('1.3.101.112'); // id-Ed25519 asnWriter.endSequence(); // PrivateKey asnWriter.startSequence(Ber.OctetString); asnWriter.writeBuffer(priv, Ber.OctetString); asnWriter.endSequence(); asnWriter.endSequence(); return makePEM('PRIVATE', asnWriter.buffer); } function genOpenSSLECDSAPub(oid, Q) { const asnWriter = new Ber.Writer(); asnWriter.startSequence(); // algorithm asnWriter.startSequence(); asnWriter.writeOID('1.2.840.10045.2.1'); // id-ecPublicKey // algorithm parameters (namedCurve) asnWriter.writeOID(oid); asnWriter.endSequence(); // subjectPublicKey asnWriter.startSequence(Ber.BitString); asnWriter.writeByte(0x00); // XXX: hack to write a raw buffer without a tag -- yuck asnWriter._ensure(Q.length); asnWriter._buf.set(Q, asnWriter._offset); asnWriter._offset += Q.length; // end hack asnWriter.endSequence(); asnWriter.endSequence(); return makePEM('PUBLIC', asnWriter.buffer); } function genOpenSSHECDSAPub(oid, Q) { let curveName; switch (oid) { case '1.2.840.10045.3.1.7': // prime256v1/secp256r1 curveName = 'nistp256'; break; case '1.3.132.0.34': // secp384r1 curveName = 'nistp384'; break; case '1.3.132.0.35': // secp521r1 curveName = 'nistp521'; break; default: return; } const publicKey = Buffer.allocUnsafe(4 + 19 + 4 + 8 + 4 + Q.length); writeUInt32BE(publicKey, 19, 0); publicKey.utf8Write(`ecdsa-sha2-${curveName}`, 4, 19); writeUInt32BE(publicKey, 8, 23); publicKey.utf8Write(curveName, 27, 8); writeUInt32BE(publicKey, Q.length, 35); publicKey.set(Q, 39); return publicKey; } function genOpenSSLECDSAPriv(oid, pub, priv) { const asnWriter = new Ber.Writer(); asnWriter.startSequence(); // version asnWriter.writeInt(0x01, Ber.Integer); // privateKey asnWriter.writeBuffer(priv, Ber.OctetString); // parameters (optional) asnWriter.startSequence(0xA0); asnWriter.writeOID(oid); asnWriter.endSequence(); // publicKey (optional) asnWriter.startSequence(0xA1); asnWriter.startSequence(Ber.BitString); asnWriter.writeByte(0x00); // XXX: hack to write a raw buffer without a tag -- yuck asnWriter._ensure(pub.length); asnWriter._buf.set(pub, asnWriter._offset); asnWriter._offset += pub.length; // end hack asnWriter.endSequence(); asnWriter.endSequence(); asnWriter.endSequence(); return makePEM('EC PRIVATE', asnWriter.buffer); } function genOpenSSLECDSAPubFromPriv(curveName, priv) { const tempECDH = createECDH(curveName); tempECDH.setPrivateKey(priv); return tempECDH.getPublicKey(); } const BaseKey = { sign: (() => { if (typeof sign_ === 'function') { return function sign(data, algo) { const pem = this[SYM_PRIV_PEM]; if (pem === null) return new Error('No private key available'); if (!algo || typeof algo !== 'string') algo = this[SYM_HASH_ALGO]; try { return sign_(algo, data, pem); } catch (ex) { return ex; } }; } return function sign(data, algo) { const pem = this[SYM_PRIV_PEM]; if (pem === null) return new Error('No private key available'); if (!algo || typeof algo !== 'string') algo = this[SYM_HASH_ALGO]; const signature = createSign(algo); signature.update(data); try { return signature.sign(pem); } catch (ex) { return ex; } }; })(), verify: (() => { if (typeof verify_ === 'function') { return function verify(data, signature, algo) { const pem = this[SYM_PUB_PEM]; if (pem === null) return new Error('No public key available'); if (!algo || typeof algo !== 'string') algo = this[SYM_HASH_ALGO]; try { return verify_(algo, data, pem, signature); } catch (ex) { return ex; } }; } return function verify(data, signature, algo) { const pem = this[SYM_PUB_PEM]; if (pem === null) return new Error('No public key available'); if (!algo || typeof algo !== 'string') algo = this[SYM_HASH_ALGO]; const verifier = createVerify(algo); verifier.update(data); try { return verifier.verify(pem, signature); } catch (ex) { return ex; } }; })(), isPrivateKey: function isPrivateKey() { return (this[SYM_PRIV_PEM] !== null); }, getPrivatePEM: function getPrivatePEM() { return this[SYM_PRIV_PEM]; }, getPublicPEM: function getPublicPEM() { return this[SYM_PUB_PEM]; }, getPublicSSH: function getPublicSSH() { return this[SYM_PUB_SSH]; }, equals: function equals(key) { const parsed = parseKey(key); if (parsed instanceof Error) return false; return ( this.type === parsed.type && this[SYM_PRIV_PEM] === parsed[SYM_PRIV_PEM] && this[SYM_PUB_PEM] === parsed[SYM_PUB_PEM] && this[SYM_PUB_SSH] === parsed[SYM_PUB_SSH] ); }, }; function OpenSSH_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) { this.type = type; this.comment = comment; this[SYM_PRIV_PEM] = privPEM; this[SYM_PUB_PEM] = pubPEM; this[SYM_PUB_SSH] = pubSSH; this[SYM_HASH_ALGO] = algo; this[SYM_DECRYPTED] = decrypted; } OpenSSH_Private.prototype = BaseKey; { const regexp = /^-----BEGIN OPENSSH PRIVATE KEY-----(?:\r\n|\n)([\s\S]+)(?:\r\n|\n)-----END OPENSSH PRIVATE KEY-----$/; OpenSSH_Private.parse = (str, passphrase) => { const m = regexp.exec(str); if (m === null) return null; let ret; const data = Buffer.from(m[1], 'base64'); if (data.length < 31) // magic (+ magic null term.) + minimum field lengths return new Error('Malformed OpenSSH private key'); const magic = data.utf8Slice(0, 15); if (magic !== 'openssh-key-v1\0') return new Error(`Unsupported OpenSSH key magic: ${magic}`); const cipherName = readString(data, 15, true); if (cipherName === undefined) return new Error('Malformed OpenSSH private key'); if (cipherName !== 'none' && SUPPORTED_CIPHER.indexOf(cipherName) === -1) return new Error(`Unsupported cipher for OpenSSH key: ${cipherName}`); const kdfName = readString(data, data._pos, true); if (kdfName === undefined) return new Error('Malformed OpenSSH private key'); if (kdfName !== 'none') { if (cipherName === 'none') return new Error('Malformed OpenSSH private key'); if (kdfName !== 'bcrypt') return new Error(`Unsupported kdf name for OpenSSH key: ${kdfName}`); if (!passphrase) { return new Error( 'Encrypted private OpenSSH key detected, but no passphrase given' ); } } else if (cipherName !== 'none') { return new Error('Malformed OpenSSH private key'); } let encInfo; let cipherKey; let cipherIV; if (cipherName !== 'none') encInfo = CIPHER_INFO[cipherName]; const kdfOptions = readString(data, data._pos); if (kdfOptions === undefined) return new Error('Malformed OpenSSH private key'); if (kdfOptions.length) { switch (kdfName) { case 'none': return new Error('Malformed OpenSSH private key'); case 'bcrypt': { /* string salt uint32 rounds */ const salt = readString(kdfOptions, 0); if (salt === undefined || kdfOptions._pos + 4 > kdfOptions.length) return new Error('Malformed OpenSSH private key'); const rounds = readUInt32BE(kdfOptions, kdfOptions._pos); const gen = Buffer.allocUnsafe(encInfo.keyLen + encInfo.ivLen); const r = bcrypt_pbkdf(passphrase, passphrase.length, salt, salt.length, gen, gen.length, rounds); if (r !== 0) return new Error('Failed to generate information to decrypt key'); cipherKey = bufferSlice(gen, 0, encInfo.keyLen); cipherIV = bufferSlice(gen, encInfo.keyLen, gen.length); break; } } } else if (kdfName !== 'none') { return new Error('Malformed OpenSSH private key'); } if (data._pos + 3 >= data.length) return new Error('Malformed OpenSSH private key'); const keyCount = readUInt32BE(data, data._pos); data._pos += 4; if (keyCount > 0) { // TODO: place sensible limit on max `keyCount` // Read public keys first for (let i = 0; i < keyCount; ++i) { const pubData = readString(data, data._pos); if (pubData === undefined) return new Error('Malformed OpenSSH private key'); const type = readString(pubData, 0, true); if (type === undefined) return new Error('Malformed OpenSSH private key'); } let privBlob = readString(data, data._pos); if (privBlob === undefined) return new Error('Malformed OpenSSH private key'); if (cipherKey !== undefined) { // Encrypted private key(s) if (privBlob.length < encInfo.blockLen || (privBlob.length % encInfo.blockLen) !== 0) { return new Error('Malformed OpenSSH private key'); } try { const options = { authTagLength: encInfo.authLen }; const decipher = createDecipheriv(encInfo.sslName, cipherKey, cipherIV, options); decipher.setAutoPadding(false); if (encInfo.authLen > 0) { if (data.length - data._pos < encInfo.authLen) return new Error('Malformed OpenSSH private key'); decipher.setAuthTag( bufferSlice(data, data._pos, data._pos += encInfo.authLen) ); } privBlob = combineBuffers(decipher.update(privBlob), decipher.final()); } catch (ex) { return ex; } } // Nothing should we follow the private key(s), except a possible // authentication tag for relevant ciphers if (data._pos !== data.length) return new Error('Malformed OpenSSH private key'); ret = parseOpenSSHPrivKeys(privBlob, keyCount, cipherKey !== undefined); } else { ret = []; } if (ret instanceof Error) return ret; // This will need to change if/when OpenSSH ever starts storing multiple // keys in their key files return ret[0]; }; function parseOpenSSHPrivKeys(data, nkeys, decrypted) { const keys = []; /* uint32 checkint uint32 checkint string privatekey1 string comment1 string privatekey2 string comment2 ... string privatekeyN string commentN char 1 char 2 char 3 ... char padlen % 255 */ if (data.length < 8) return new Error('Malformed OpenSSH private key'); const check1 = readUInt32BE(data, 0); const check2 = readUInt32BE(data, 4); if (check1 !== check2) { if (decrypted) { return new Error( 'OpenSSH key integrity check failed -- bad passphrase?' ); } return new Error('OpenSSH key integrity check failed'); } data._pos = 8; let i; let oid; for (i = 0; i < nkeys; ++i) { let algo; let privPEM; let pubPEM; let pubSSH; // The OpenSSH documentation for the key format actually lies, the // entirety of the private key content is not contained with a string // field, it's actually the literal contents of the private key, so to be // able to find the end of the key data you need to know the layout/format // of each key type ... const type = readString(data, data._pos, true); if (type === undefined) return new Error('Malformed OpenSSH private key'); switch (type) { case 'ssh-rsa': { /* string n -- public string e -- public string d -- private string iqmp -- private string p -- private string q -- private */ const n = readString(data, data._pos); if (n === undefined) return new Error('Malformed OpenSSH private key'); const e = readString(data, data._pos); if (e === undefined) return new Error('Malformed OpenSSH private key'); const d = readString(data, data._pos); if (d === undefined) return new Error('Malformed OpenSSH private key'); const iqmp = readString(data, data._pos); if (iqmp === undefined) return new Error('Malformed OpenSSH private key'); const p = readString(data, data._pos); if (p === undefined) return new Error('Malformed OpenSSH private key'); const q = readString(data, data._pos); if (q === undefined) return new Error('Malformed OpenSSH private key'); pubPEM = genOpenSSLRSAPub(n, e); pubSSH = genOpenSSHRSAPub(n, e); privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q); algo = 'sha1'; break; } case 'ssh-dss': { /* string p -- public string q -- public string g -- public string y -- public string x -- private */ const p = readString(data, data._pos); if (p === undefined) return new Error('Malformed OpenSSH private key'); const q = readString(data, data._pos); if (q === undefined) return new Error('Malformed OpenSSH private key'); const g = readString(data, data._pos); if (g === undefined) return new Error('Malformed OpenSSH private key'); const y = readString(data, data._pos); if (y === undefined) return new Error('Malformed OpenSSH private key'); const x = readString(data, data._pos); if (x === undefined) return new Error('Malformed OpenSSH private key'); pubPEM = genOpenSSLDSAPub(p, q, g, y); pubSSH = genOpenSSHDSAPub(p, q, g, y); privPEM = genOpenSSLDSAPriv(p, q, g, y, x); algo = 'sha1'; break; } case 'ssh-ed25519': { if (!eddsaSupported) return new Error(`Unsupported OpenSSH private key type: ${type}`); /* * string public key * string private key + public key */ const edpub = readString(data, data._pos); if (edpub === undefined || edpub.length !== 32) return new Error('Malformed OpenSSH private key'); const edpriv = readString(data, data._pos); if (edpriv === undefined || edpriv.length !== 64) return new Error('Malformed OpenSSH private key'); pubPEM = genOpenSSLEdPub(edpub); pubSSH = genOpenSSHEdPub(edpub); privPEM = genOpenSSLEdPriv(bufferSlice(edpriv, 0, 32)); algo = null; break; } case 'ecdsa-sha2-nistp256': algo = 'sha256'; oid = '1.2.840.10045.3.1.7'; // FALLTHROUGH case 'ecdsa-sha2-nistp384': if (algo === undefined) { algo = 'sha384'; oid = '1.3.132.0.34'; } // FALLTHROUGH case 'ecdsa-sha2-nistp521': { if (algo === undefined) { algo = 'sha512'; oid = '1.3.132.0.35'; } /* string curve name string Q -- public string d -- private */ // TODO: validate curve name against type if (!skipFields(data, 1)) // Skip curve name return new Error('Malformed OpenSSH private key'); const ecpub = readString(data, data._pos); if (ecpub === undefined) return new Error('Malformed OpenSSH private key'); const ecpriv = readString(data, data._pos); if (ecpriv === undefined) return new Error('Malformed OpenSSH private key'); pubPEM = genOpenSSLECDSAPub(oid, ecpub); pubSSH = genOpenSSHECDSAPub(oid, ecpub); privPEM = genOpenSSLECDSAPriv(oid, ecpub, ecpriv); break; } default: return new Error(`Unsupported OpenSSH private key type: ${type}`); } const privComment = readString(data, data._pos, true); if (privComment === undefined) return new Error('Malformed OpenSSH private key'); keys.push( new OpenSSH_Private(type, privComment, privPEM, pubPEM, pubSSH, algo, decrypted) ); } let cnt = 0; for (i = data._pos; i < data.length; ++i) { if (data[i] !== (++cnt % 255)) return new Error('Malformed OpenSSH private key'); } return keys; } } function OpenSSH_Old_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) { this.type = type; this.comment = comment; this[SYM_PRIV_PEM] = privPEM; this[SYM_PUB_PEM] = pubPEM; this[SYM_PUB_SSH] = pubSSH; this[SYM_HASH_ALGO] = algo; this[SYM_DECRYPTED] = decrypted; } OpenSSH_Old_Private.prototype = BaseKey; { const regexp = /^-----BEGIN (RSA|DSA|EC) PRIVATE KEY-----(?:\r\n|\n)((?:[^:]+:\s*[\S].*(?:\r\n|\n))*)([\s\S]+)(?:\r\n|\n)-----END (RSA|DSA|EC) PRIVATE KEY-----$/; OpenSSH_Old_Private.parse = (str, passphrase) => { const m = regexp.exec(str); if (m === null) return null; let privBlob = Buffer.from(m[3], 'base64'); let headers = m[2]; let decrypted = false; if (headers !== undefined) { // encrypted key headers = headers.split(/\r\n|\n/g); for (let i = 0; i < headers.length; ++i) { const header = headers[i]; let sepIdx = header.indexOf(':'); if (header.slice(0, sepIdx) === 'DEK-Info') { const val = header.slice(sepIdx + 2); sepIdx = val.indexOf(','); if (sepIdx === -1) continue; const cipherName = val.slice(0, sepIdx).toLowerCase(); if (supportedOpenSSLCiphers.indexOf(cipherName) === -1) { return new Error( `Cipher (${cipherName}) not supported ` + 'for encrypted OpenSSH private key' ); } const encInfo = CIPHER_INFO_OPENSSL[cipherName]; if (!encInfo) { return new Error( `Cipher (${cipherName}) not supported ` + 'for encrypted OpenSSH private key' ); } const cipherIV = Buffer.from(val.slice(sepIdx + 1), 'hex'); if (cipherIV.length !== encInfo.ivLen) return new Error('Malformed encrypted OpenSSH private key'); if (!passphrase) { return new Error( 'Encrypted OpenSSH private key detected, but no passphrase given' ); } const ivSlice = bufferSlice(cipherIV, 0, 8); let cipherKey = createHash('md5') .update(passphrase) .update(ivSlice) .digest(); while (cipherKey.length < encInfo.keyLen) { cipherKey = combineBuffers( cipherKey, createHash('md5') .update(cipherKey) .update(passphrase) .update(ivSlice) .digest() ); } if (cipherKey.length > encInfo.keyLen) cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen); try { const decipher = createDecipheriv(cipherName, cipherKey, cipherIV); decipher.setAutoPadding(false); privBlob = combineBuffers(decipher.update(privBlob), decipher.final()); decrypted = true; } catch (ex) { return ex; } } } } let type; let privPEM; let pubPEM; let pubSSH; let algo; let reader; let errMsg = 'Malformed OpenSSH private key'; if (decrypted) errMsg += '. Bad passphrase?'; switch (m[1]) { case 'RSA': type = 'ssh-rsa'; privPEM = makePEM('RSA PRIVATE', privBlob); try { reader = new Ber.Reader(privBlob); reader.readSequence(); reader.readInt(); // skip version const n = reader.readString(Ber.Integer, true); if (n === null) return new Error(errMsg); const e = reader.readString(Ber.Integer, true); if (e === null) return new Error(errMsg); pubPEM = genOpenSSLRSAPub(n, e); pubSSH = genOpenSSHRSAPub(n, e); } catch { return new Error(errMsg); } algo = 'sha1'; break; case 'DSA': type = 'ssh-dss'; privPEM = makePEM('DSA PRIVATE', privBlob); try { reader = new Ber.Reader(privBlob); reader.readSequence(); reader.readInt(); // skip version const p = reader.readString(Ber.Integer, true); if (p === null) return new Error(errMsg); const q = reader.readString(Ber.Integer, true); if (q === null) return new Error(errMsg); const g = reader.readString(Ber.Integer, true); if (g === null) return new Error(errMsg); const y = reader.readString(Ber.Integer, true); if (y === null) return new Error(errMsg); pubPEM = genOpenSSLDSAPub(p, q, g, y); pubSSH = genOpenSSHDSAPub(p, q, g, y); } catch { return new Error(errMsg); } algo = 'sha1'; break; case 'EC': { let ecSSLName; let ecPriv; let ecOID; try { reader = new Ber.Reader(privBlob); reader.readSequence(); reader.readInt(); // skip version ecPriv = reader.readString(Ber.OctetString, true); reader.readByte(); // Skip "complex" context type byte const offset = reader.readLength(); // Skip context length if (offset !== null) { reader._offset = offset; ecOID = reader.readOID(); if (ecOID === null) return new Error(errMsg); switch (ecOID) { case '1.2.840.10045.3.1.7': // prime256v1/secp256r1 ecSSLName = 'prime256v1'; type = 'ecdsa-sha2-nistp256'; algo = 'sha256'; break; case '1.3.132.0.34': // secp384r1 ecSSLName = 'secp384r1'; type = 'ecdsa-sha2-nistp384'; algo = 'sha384'; break; case '1.3.132.0.35': // secp521r1 ecSSLName = 'secp521r1'; type = 'ecdsa-sha2-nistp521'; algo = 'sha512'; break; default: return new Error(`Unsupported private key EC OID: ${ecOID}`); } } else { return new Error(errMsg); } } catch { return new Error(errMsg); } privPEM = makePEM('EC PRIVATE', privBlob); const pubBlob = genOpenSSLECDSAPubFromPriv(ecSSLName, ecPriv); pubPEM = genOpenSSLECDSAPub(ecOID, pubBlob); pubSSH = genOpenSSHECDSAPub(ecOID, pubBlob); break; } } return new OpenSSH_Old_Private(type, '', privPEM, pubPEM, pubSSH, algo, decrypted); }; } function PPK_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) { this.type = type; this.comment = comment; this[SYM_PRIV_PEM] = privPEM; this[SYM_PUB_PEM] = pubPEM; this[SYM_PUB_SSH] = pubSSH; this[SYM_HASH_ALGO] = algo; this[SYM_DECRYPTED] = decrypted; } PPK_Private.prototype = BaseKey; { const EMPTY_PASSPHRASE = Buffer.alloc(0); const PPK_IV = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); const PPK_PP1 = Buffer.from([0, 0, 0, 0]); const PPK_PP2 = Buffer.from([0, 0, 0, 1]); const regexp = /^PuTTY-User-Key-File-2: (ssh-(?:rsa|dss))\r?\nEncryption: (aes256-cbc|none)\r?\nComment: ([^\r\n]*)\r?\nPublic-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-MAC: ([^\r\n]+)/; PPK_Private.parse = (str, passphrase) => { const m = regexp.exec(str); if (m === null) return null; // m[1] = key type // m[2] = encryption type // m[3] = comment // m[4] = base64-encoded public key data: // for "ssh-rsa": // string "ssh-rsa" // mpint e (public exponent) // mpint n (modulus) // for "ssh-dss": // string "ssh-dss" // mpint p (modulus) // mpint q (prime) // mpint g (base number) // mpint y (public key parameter: g^x mod p) // m[5] = base64-encoded private key data: // for "ssh-rsa": // mpint d (private exponent) // mpint p (prime 1) // mpint q (prime 2) // mpint iqmp ([inverse of q] mod p) // for "ssh-dss": // mpint x (private key parameter) // m[6] = SHA1 HMAC over: // string name of algorithm ("ssh-dss", "ssh-rsa") // string encryption type // string comment // string public key data // string private-plaintext (including the final padding) const cipherName = m[2]; const encrypted = (cipherName !== 'none'); if (encrypted && !passphrase) { return new Error( 'Encrypted PPK private key detected, but no passphrase given' ); } let privBlob = Buffer.from(m[5], 'base64'); if (encrypted) { const encInfo = CIPHER_INFO[cipherName]; let cipherKey = combineBuffers( createHash('sha1').update(PPK_PP1).update(passphrase).digest(), createHash('sha1').update(PPK_PP2).update(passphrase).digest() ); if (cipherKey.length > encInfo.keyLen) cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen); try { const decipher = createDecipheriv(encInfo.sslName, cipherKey, PPK_IV); decipher.setAutoPadding(false); privBlob = combineBuffers(decipher.update(privBlob), decipher.final()); } catch (ex) { return ex; } } const type = m[1]; const comment = m[3]; const pubBlob = Buffer.from(m[4], 'base64'); const mac = m[6]; const typeLen = type.length; const cipherNameLen = cipherName.length; const commentLen = Buffer.byteLength(comment); const pubLen = pubBlob.length; const privLen = privBlob.length; const macData = Buffer.allocUnsafe(4 + typeLen + 4 + cipherNameLen + 4 + commentLen + 4 + pubLen + 4 + privLen); let p = 0; writeUInt32BE(macData, typeLen, p); macData.utf8Write(type, p += 4, typeLen); writeUInt32BE(macData, cipherNameLen, p += typeLen); macData.utf8Write(cipherName, p += 4, cipherNameLen); writeUInt32BE(macData, commentLen, p += cipherNameLen); macData.utf8Write(comment, p += 4, commentLen); writeUInt32BE(macData, pubLen, p += commentLen); macData.set(pubBlob, p += 4); writeUInt32BE(macData, privLen, p += pubLen); macData.set(privBlob, p + 4); if (!passphrase) passphrase = EMPTY_PASSPHRASE; const calcMAC = createHmac( 'sha1', createHash('sha1') .update('putty-private-key-file-mac-key') .update(passphrase) .digest() ).update(macData).digest('hex'); if (calcMAC !== mac) { if (encrypted) { return new Error( 'PPK private key integrity check failed -- bad passphrase?' ); } return new Error('PPK private key integrity check failed'); } let pubPEM; let pubSSH; let privPEM; pubBlob._pos = 0; skipFields(pubBlob, 1); // skip (duplicate) key type switch (type) { case 'ssh-rsa': { const e = readString(pubBlob, pubBlob._pos); if (e === undefined) return new Error('Malformed PPK public key'); const n = readString(pubBlob, pubBlob._pos); if (n === undefined) return new Error('Malformed PPK public key'); const d = readString(privBlob, 0); if (d === undefined) return new Error('Malformed PPK private key'); const p = readString(privBlob, privBlob._pos); if (p === undefined) return new Error('Malformed PPK private key'); const q = readString(privBlob, privBlob._pos); if (q === undefined) return new Error('Malformed PPK private key'); const iqmp = readString(privBlob, privBlob._pos); if (iqmp === undefined) return new Error('Malformed PPK private key'); pubPEM = genOpenSSLRSAPub(n, e); pubSSH = genOpenSSHRSAPub(n, e); privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q); break; } case 'ssh-dss': { const p = readString(pubBlob, pubBlob._pos); if (p === undefined) return new Error('Malformed PPK public key'); const q = readString(pubBlob, pubBlob._pos); if (q === undefined) return new Error('Malformed PPK public key'); const g = readString(pubBlob, pubBlob._pos); if (g === undefined) return new Error('Malformed PPK public key'); const y = readString(pubBlob, pubBlob._pos); if (y === undefined) return new Error('Malformed PPK public key'); const x = readString(privBlob, 0); if (x === undefined) return new Error('Malformed PPK private key'); pubPEM = genOpenSSLDSAPub(p, q, g, y); pubSSH = genOpenSSHDSAPub(p, q, g, y); privPEM = genOpenSSLDSAPriv(p, q, g, y, x); break; } } return new PPK_Private(type, comment, privPEM, pubPEM, pubSSH, 'sha1', encrypted); }; } function OpenSSH_Public(type, comment, pubPEM, pubSSH, algo) { this.type = type; this.comment = comment; this[SYM_PRIV_PEM] = null; this[SYM_PUB_PEM] = pubPEM; this[SYM_PUB_SSH] = pubSSH; this[SYM_HASH_ALGO] = algo; this[SYM_DECRYPTED] = false; } OpenSSH_Public.prototype = BaseKey; { let regexp; if (eddsaSupported) regexp = /^(((?:ssh-(?:rsa|dss|ed25519))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/; else regexp = /^(((?:ssh-(?:rsa|dss))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/; OpenSSH_Public.parse = (str) => { const m = regexp.exec(str); if (m === null) return null; // m[1] = full type // m[2] = base type // m[3] = base64-encoded public key // m[4] = comment const fullType = m[1]; const baseType = m[2]; const data = Buffer.from(m[3], 'base64'); const comment = (m[4] || ''); const type = readString(data, data._pos, true); if (type === undefined || type.indexOf(baseType) !== 0) return new Error('Malformed OpenSSH public key'); return parseDER(data, baseType, comment, fullType); }; } function RFC4716_Public(type, comment, pubPEM, pubSSH, algo) { this.type = type; this.comment = comment; this[SYM_PRIV_PEM] = null; this[SYM_PUB_PEM] = pubPEM; this[SYM_PUB_SSH] = pubSSH; this[SYM_HASH_ALGO] = algo; this[SYM_DECRYPTED] = false; } RFC4716_Public.prototype = BaseKey; { const regexp = /^---- BEGIN SSH2 PUBLIC KEY ----(?:\r?\n)((?:.{0,72}\r?\n)+)---- END SSH2 PUBLIC KEY ----$/; const RE_DATA = /^[A-Z0-9a-z/+=\r\n]+$/; const RE_HEADER = /^([\x21-\x39\x3B-\x7E]{1,64}): ((?:[^\\]*\\\r?\n)*[^\r\n]+)\r?\n/gm; const RE_HEADER_ENDS = /\\\r?\n/g; RFC4716_Public.parse = (str) => { let m = regexp.exec(str); if (m === null) return null; const body = m[1]; let dataStart = 0; let comment = ''; while (m = RE_HEADER.exec(body)) { const headerName = m[1]; const headerValue = m[2].replace(RE_HEADER_ENDS, ''); if (headerValue.length > 1024) { RE_HEADER.lastIndex = 0; return new Error('Malformed RFC4716 public key'); } dataStart = RE_HEADER.lastIndex; if (headerName.toLowerCase() === 'comment') { comment = headerValue; if (comment.length > 1 && comment.charCodeAt(0) === 34/* '"' */ && comment.charCodeAt(comment.length - 1) === 34/* '"' */) { comment = comment.slice(1, -1); } } } let data = body.slice(dataStart); if (!RE_DATA.test(data)) return new Error('Malformed RFC4716 public key'); data = Buffer.from(data, 'base64'); const type = readString(data, 0, true); if (type === undefined) return new Error('Malformed RFC4716 public key'); let pubPEM = null; let pubSSH = null; switch (type) { case 'ssh-rsa': { const e = readString(data, data._pos); if (e === undefined) return new Error('Malformed RFC4716 public key'); const n = readString(data, data._pos); if (n === undefined) return new Error('Malformed RFC4716 public key'); pubPEM = genOpenSSLRSAPub(n, e); pubSSH = genOpenSSHRSAPub(n, e); break; } case 'ssh-dss': { const p = readString(data, data._pos); if (p === undefined) return new Error('Malformed RFC4716 public key'); const q = readString(data, data._pos); if (q === undefined) return new Error('Malformed RFC4716 public key'); const g = readString(data, data._pos); if (g === undefined) return new Error('Malformed RFC4716 public key'); const y = readString(data, data._pos); if (y === undefined) return new Error('Malformed RFC4716 public key'); pubPEM = genOpenSSLDSAPub(p, q, g, y); pubSSH = genOpenSSHDSAPub(p, q, g, y); break; } default: return new Error('Malformed RFC4716 public key'); } return new RFC4716_Public(type, comment, pubPEM, pubSSH, 'sha1'); }; } function parseDER(data, baseType, comment, fullType) { if (!isSupportedKeyType(baseType)) return new Error(`Unsupported OpenSSH public key type: ${baseType}`); let algo; let oid; let pubPEM = null; let pubSSH = null; switch (baseType) { case 'ssh-rsa': { const e = readString(data, data._pos || 0); if (e === undefined) return new Error('Malformed OpenSSH public key'); const n = readString(data, data._pos); if (n === undefined) return new Error('Malformed OpenSSH public key'); pubPEM = genOpenSSLRSAPub(n, e); pubSSH = genOpenSSHRSAPub(n, e); algo = 'sha1'; break; } case 'ssh-dss': { const p = readString(data, data._pos || 0); if (p === undefined) return new Error('Malformed OpenSSH public key'); const q = readString(data, data._pos); if (q === undefined) return new Error('Malformed OpenSSH public key'); const g = readString(data, data._pos); if (g === undefined) return new Error('Malformed OpenSSH public key'); const y = readString(data, data._pos); if (y === undefined) return new Error('Malformed OpenSSH public key'); pubPEM = genOpenSSLDSAPub(p, q, g, y); pubSSH = genOpenSSHDSAPub(p, q, g, y); algo = 'sha1'; break; } case 'ssh-ed25519': { const edpub = readString(data, data._pos || 0); if (edpub === undefined || edpub.length !== 32) return new Error('Malformed OpenSSH public key'); pubPEM = genOpenSSLEdPub(edpub); pubSSH = genOpenSSHEdPub(edpub); algo = null; break; } case 'ecdsa-sha2-nistp256': algo = 'sha256'; oid = '1.2.840.10045.3.1.7'; // FALLTHROUGH case 'ecdsa-sha2-nistp384': if (algo === undefined) { algo = 'sha384'; oid = '1.3.132.0.34'; } // FALLTHROUGH case 'ecdsa-sha2-nistp521': { if (algo === undefined) { algo = 'sha512'; oid = '1.3.132.0.35'; } // TODO: validate curve name against type if (!skipFields(data, 1)) // Skip curve name return new Error('Malformed OpenSSH public key'); const ecpub = readString(data, data._pos || 0); if (ecpub === undefined) return new Error('Malformed OpenSSH public key'); pubPEM = genOpenSSLECDSAPub(oid, ecpub); pubSSH = genOpenSSHECDSAPub(oid, ecpub); break; } default: return new Error(`Unsupported OpenSSH public key type: ${baseType}`); } return new OpenSSH_Public(fullType, comment, pubPEM, pubSSH, algo); } function isSupportedKeyType(type) { switch (type) { case 'ssh-rsa': case 'ssh-dss': case 'ecdsa-sha2-nistp256': case 'ecdsa-sha2-nistp384': case 'ecdsa-sha2-nistp521': return true; case 'ssh-ed25519': if (eddsaSupported) return true; // FALLTHROUGH default: return false; } } function isParsedKey(val) { if (!val) return false; return (typeof val[SYM_DECRYPTED] === 'boolean'); } function parseKey(data, passphrase) { if (isParsedKey(data)) return data; let origBuffer; if (Buffer.isBuffer(data)) { origBuffer = data; data = data.utf8Slice(0, data.length).trim(); } else if (typeof data === 'string') { data = data.trim(); } else { return new Error('Key data must be a Buffer or string'); } // eslint-disable-next-line eqeqeq if (passphrase != undefined) { if (typeof passphrase === 'string') passphrase = Buffer.from(passphrase); else if (!Buffer.isBuffer(passphrase)) return new Error('Passphrase must be a string or Buffer when supplied'); } let ret; // First try as printable string format (e.g. PEM) // Private keys if ((ret = OpenSSH_Private.parse(data, passphrase)) !== null) return ret; if ((ret = OpenSSH_Old_Private.parse(data, passphrase)) !== null) return ret; if ((ret = PPK_Private.parse(data, passphrase)) !== null) return ret; // Public keys if ((ret = OpenSSH_Public.parse(data)) !== null) return ret; if ((ret = RFC4716_Public.parse(data)) !== null) return ret; // Finally try as a binary format if we were originally passed binary data if (origBuffer) { binaryKeyParser.init(origBuffer, 0); const type = binaryKeyParser.readString(true); if (type !== undefined) { data = binaryKeyParser.readRaw(); if (data !== undefined) { ret = parseDER(data, type, '', type); // Ignore potentially useless errors in case the data was not actually // in the binary format if (ret instanceof Error) ret = null; } } binaryKeyParser.clear(); } if (ret) return ret; return new Error('Unsupported key format'); } module.exports = { isParsedKey, isSupportedKeyType, parseDERKey: (data, type) => parseDER(data, type, '', type), parseKey, }; /***/ }), /***/ 85607: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; const assert = __webpack_require__(39491); const { inspect } = __webpack_require__(73837); // Only use this for integers! Decimal numbers do not work with this function. function addNumericalSeparator(val) { let res = ''; let i = val.length; const start = val[0] === '-' ? 1 : 0; for (; i >= start + 4; i -= 3) res = `_${val.slice(i - 3, i)}${res}`; return `${val.slice(0, i)}${res}`; } function oneOf(expected, thing) { assert(typeof thing === 'string', '`thing` has to be of type string'); if (Array.isArray(expected)) { const len = expected.length; assert(len > 0, 'At least one expected value needs to be specified'); expected = expected.map((i) => String(i)); if (len > 2) { return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + expected[len - 1]; } else if (len === 2) { return `one of ${thing} ${expected[0]} or ${expected[1]}`; } return `of ${thing} ${expected[0]}`; } return `of ${thing} ${String(expected)}`; } exports.ERR_INTERNAL_ASSERTION = class ERR_INTERNAL_ASSERTION extends Error { constructor(message) { super(); Error.captureStackTrace(this, ERR_INTERNAL_ASSERTION); const suffix = 'This is caused by either a bug in ssh2 ' + 'or incorrect usage of ssh2 internals.\n' + 'Please open an issue with this stack trace at ' + 'https://github.com/mscdex/ssh2/issues\n'; this.message = (message === undefined ? suffix : `${message}\n${suffix}`); } }; const MAX_32BIT_INT = 2 ** 32; const MAX_32BIT_BIGINT = (() => { try { return new Function('return 2n ** 32n')(); } catch {} })(); exports.ERR_OUT_OF_RANGE = class ERR_OUT_OF_RANGE extends RangeError { constructor(str, range, input, replaceDefaultBoolean) { super(); Error.captureStackTrace(this, ERR_OUT_OF_RANGE); assert(range, 'Missing "range" argument'); let msg = (replaceDefaultBoolean ? str : `The value of "${str}" is out of range.`); let received; if (Number.isInteger(input) && Math.abs(input) > MAX_32BIT_INT) { received = addNumericalSeparator(String(input)); } else if (typeof input === 'bigint') { received = String(input); if (input > MAX_32BIT_BIGINT || input < -MAX_32BIT_BIGINT) received = addNumericalSeparator(received); received += 'n'; } else { received = inspect(input); } msg += ` It must be ${range}. Received ${received}`; this.message = msg; } }; class ERR_INVALID_ARG_TYPE extends TypeError { constructor(name, expected, actual) { super(); Error.captureStackTrace(this, ERR_INVALID_ARG_TYPE); assert(typeof name === 'string', `'name' must be a string`); // determiner: 'must be' or 'must not be' let determiner; if (typeof expected === 'string' && expected.startsWith('not ')) { determiner = 'must not be'; expected = expected.replace(/^not /, ''); } else { determiner = 'must be'; } let msg; if (name.endsWith(' argument')) { // For cases like 'first argument' msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; } else { const type = (name.includes('.') ? 'property' : 'argument'); msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; } msg += `. Received type ${typeof actual}`; this.message = msg; } } exports.ERR_INVALID_ARG_TYPE = ERR_INVALID_ARG_TYPE; exports.validateNumber = function validateNumber(value, name) { if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value); }; /***/ }), /***/ 39205: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const Ber = __webpack_require__(90476).Ber; let DISCONNECT_REASON; const FastBuffer = Buffer[Symbol.species]; const TypedArrayFill = Object.getPrototypeOf(Uint8Array.prototype).fill; function readUInt32BE(buf, offset) { return (buf[offset++] * 16777216) + (buf[offset++] * 65536) + (buf[offset++] * 256) + buf[offset]; } function bufferCopy(src, dest, srcStart, srcEnd, destStart) { if (!destStart) destStart = 0; if (srcEnd > src.length) srcEnd = src.length; let nb = srcEnd - srcStart; const destLeft = (dest.length - destStart); if (nb > destLeft) nb = destLeft; dest.set(new Uint8Array(src.buffer, src.byteOffset + srcStart, nb), destStart); return nb; } function bufferSlice(buf, start, end) { if (end === undefined) end = buf.length; return new FastBuffer(buf.buffer, buf.byteOffset + start, end - start); } function makeBufferParser() { let pos = 0; let buffer; const self = { init: (buf, start) => { buffer = buf; pos = (typeof start === 'number' ? start : 0); }, pos: () => pos, length: () => (buffer ? buffer.length : 0), avail: () => (buffer && pos < buffer.length ? buffer.length - pos : 0), clear: () => { buffer = undefined; }, readUInt32BE: () => { if (!buffer || pos + 3 >= buffer.length) return; return (buffer[pos++] * 16777216) + (buffer[pos++] * 65536) + (buffer[pos++] * 256) + buffer[pos++]; }, readUInt64BE: (behavior) => { if (!buffer || pos + 7 >= buffer.length) return; switch (behavior) { case 'always': return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`); case 'maybe': if (buffer[pos] > 0x1F) return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`); // FALLTHROUGH default: return (buffer[pos++] * 72057594037927940) + (buffer[pos++] * 281474976710656) + (buffer[pos++] * 1099511627776) + (buffer[pos++] * 4294967296) + (buffer[pos++] * 16777216) + (buffer[pos++] * 65536) + (buffer[pos++] * 256) + buffer[pos++]; } }, skip: (n) => { if (buffer && n > 0) pos += n; }, skipString: () => { const len = self.readUInt32BE(); if (len === undefined) return; pos += len; return (pos <= buffer.length ? len : undefined); }, readByte: () => { if (buffer && pos < buffer.length) return buffer[pos++]; }, readBool: () => { if (buffer && pos < buffer.length) return !!buffer[pos++]; }, readList: () => { const list = self.readString(true); if (list === undefined) return; return (list ? list.split(',') : []); }, readString: (dest, maxLen) => { if (typeof dest === 'number') { maxLen = dest; dest = undefined; } const len = self.readUInt32BE(); if (len === undefined) return; if ((buffer.length - pos) < len || (typeof maxLen === 'number' && len > maxLen)) { return; } if (dest) { if (Buffer.isBuffer(dest)) return bufferCopy(buffer, dest, pos, pos += len); return buffer.utf8Slice(pos, pos += len); } return bufferSlice(buffer, pos, pos += len); }, readRaw: (len) => { if (!buffer) return; if (typeof len !== 'number') return bufferSlice(buffer, pos, pos += (buffer.length - pos)); if ((buffer.length - pos) >= len) return bufferSlice(buffer, pos, pos += len); }, }; return self; } function makeError(msg, level, fatal) { const err = new Error(msg); if (typeof level === 'boolean') { fatal = level; err.level = 'protocol'; } else { err.level = level || 'protocol'; } err.fatal = !!fatal; return err; } function writeUInt32BE(buf, value, offset) { buf[offset++] = (value >>> 24); buf[offset++] = (value >>> 16); buf[offset++] = (value >>> 8); buf[offset++] = value; return offset; } const utilBufferParser = makeBufferParser(); module.exports = { bufferCopy, bufferSlice, FastBuffer, bufferFill: (buf, value, start, end) => { return TypedArrayFill.call(buf, value, start, end); }, makeError, doFatalError: (protocol, msg, level, reason) => { let err; if (DISCONNECT_REASON === undefined) ({ DISCONNECT_REASON } = __webpack_require__(3190)); if (msg instanceof Error) { // doFatalError(protocol, err[, reason]) err = msg; if (typeof level !== 'number') reason = DISCONNECT_REASON.PROTOCOL_ERROR; else reason = level; } else { // doFatalError(protocol, msg[, level[, reason]]) err = makeError(msg, level, true); } if (typeof reason !== 'number') reason = DISCONNECT_REASON.PROTOCOL_ERROR; protocol.disconnect(reason); protocol._destruct(); protocol._onError(err); return Infinity; }, readUInt32BE, writeUInt32BE, writeUInt32LE: (buf, value, offset) => { buf[offset++] = value; buf[offset++] = (value >>> 8); buf[offset++] = (value >>> 16); buf[offset++] = (value >>> 24); return offset; }, makeBufferParser, bufferParser: makeBufferParser(), readString: (buffer, start, dest, maxLen) => { if (typeof dest === 'number') { maxLen = dest; dest = undefined; } if (start === undefined) start = 0; const left = (buffer.length - start); if (start < 0 || start >= buffer.length || left < 4) return; const len = readUInt32BE(buffer, start); if (left < (4 + len) || (typeof maxLen === 'number' && len > maxLen)) return; start += 4; const end = start + len; buffer._pos = end; if (dest) { if (Buffer.isBuffer(dest)) return bufferCopy(buffer, dest, start, end); return buffer.utf8Slice(start, end); } return bufferSlice(buffer, start, end); }, sigSSHToASN1: (sig, type) => { switch (type) { case 'ssh-dss': { if (sig.length > 40) return sig; // Change bare signature r and s values to ASN.1 BER values for OpenSSL const asnWriter = new Ber.Writer(); asnWriter.startSequence(); let r = sig.slice(0, 20); let s = sig.slice(20); if (r[0] & 0x80) { const rNew = Buffer.allocUnsafe(21); rNew[0] = 0x00; r.copy(rNew, 1); r = rNew; } else if (r[0] === 0x00 && !(r[1] & 0x80)) { r = r.slice(1); } if (s[0] & 0x80) { const sNew = Buffer.allocUnsafe(21); sNew[0] = 0x00; s.copy(sNew, 1); s = sNew; } else if (s[0] === 0x00 && !(s[1] & 0x80)) { s = s.slice(1); } asnWriter.writeBuffer(r, Ber.Integer); asnWriter.writeBuffer(s, Ber.Integer); asnWriter.endSequence(); return asnWriter.buffer; } case 'ecdsa-sha2-nistp256': case 'ecdsa-sha2-nistp384': case 'ecdsa-sha2-nistp521': { utilBufferParser.init(sig, 0); const r = utilBufferParser.readString(); const s = utilBufferParser.readString(); utilBufferParser.clear(); if (r === undefined || s === undefined) return; const asnWriter = new Ber.Writer(); asnWriter.startSequence(); asnWriter.writeBuffer(r, Ber.Integer); asnWriter.writeBuffer(s, Ber.Integer); asnWriter.endSequence(); return asnWriter.buffer; } default: return sig; } }, convertSignature: (signature, keyType) => { switch (keyType) { case 'ssh-dss': { if (signature.length <= 40) return signature; // This is a quick and dirty way to get from BER encoded r and s that // OpenSSL gives us, to just the bare values back to back (40 bytes // total) like OpenSSH (and possibly others) are expecting const asnReader = new Ber.Reader(signature); asnReader.readSequence(); let r = asnReader.readString(Ber.Integer, true); let s = asnReader.readString(Ber.Integer, true); let rOffset = 0; let sOffset = 0; if (r.length < 20) { const rNew = Buffer.allocUnsafe(20); rNew.set(r, 1); r = rNew; r[0] = 0; } if (s.length < 20) { const sNew = Buffer.allocUnsafe(20); sNew.set(s, 1); s = sNew; s[0] = 0; } if (r.length > 20 && r[0] === 0) rOffset = 1; if (s.length > 20 && s[0] === 0) sOffset = 1; const newSig = Buffer.allocUnsafe((r.length - rOffset) + (s.length - sOffset)); bufferCopy(r, newSig, rOffset, r.length, 0); bufferCopy(s, newSig, sOffset, s.length, r.length - rOffset); return newSig; } case 'ecdsa-sha2-nistp256': case 'ecdsa-sha2-nistp384': case 'ecdsa-sha2-nistp521': { if (signature[0] === 0) return signature; // Convert SSH signature parameters to ASN.1 BER values for OpenSSL const asnReader = new Ber.Reader(signature); asnReader.readSequence(); const r = asnReader.readString(Ber.Integer, true); const s = asnReader.readString(Ber.Integer, true); if (r === null || s === null) return; const newSig = Buffer.allocUnsafe(4 + r.length + 4 + s.length); writeUInt32BE(newSig, r.length, 0); newSig.set(r, 4); writeUInt32BE(newSig, s.length, 4 + r.length); newSig.set(s, 4 + 4 + r.length); return newSig; } } return signature; }, sendPacket: (proto, packet, bypass) => { if (!bypass && proto._kexinit !== undefined) { // We're currently in the middle of a handshake if (proto._queue === undefined) proto._queue = []; proto._queue.push(packet); proto._debug && proto._debug('Outbound: ... packet queued'); return false; } proto._cipher.encrypt(packet); return true; }, }; /***/ }), /***/ 36993: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const { kMaxLength } = __webpack_require__(14300); const { createInflate, constants: { DEFLATE, INFLATE, Z_DEFAULT_CHUNK, Z_DEFAULT_COMPRESSION, Z_DEFAULT_MEMLEVEL, Z_DEFAULT_STRATEGY, Z_DEFAULT_WINDOWBITS, Z_PARTIAL_FLUSH, } } = __webpack_require__(59796); const ZlibHandle = createInflate()._handle.constructor; function processCallback() { throw new Error('Should not get here'); } function zlibOnError(message, errno, code) { const self = this._owner; // There is no way to cleanly recover. // Continuing only obscures problems. const error = new Error(message); error.errno = errno; error.code = code; self._err = error; } function _close(engine) { // Caller may invoke .close after a zlib error (which will null _handle). if (!engine._handle) return; engine._handle.close(); engine._handle = null; } class Zlib { constructor(mode) { const windowBits = Z_DEFAULT_WINDOWBITS; const level = Z_DEFAULT_COMPRESSION; const memLevel = Z_DEFAULT_MEMLEVEL; const strategy = Z_DEFAULT_STRATEGY; const dictionary = undefined; this._err = undefined; this._writeState = new Uint32Array(2); this._chunkSize = Z_DEFAULT_CHUNK; this._maxOutputLength = kMaxLength; this._outBuffer = Buffer.allocUnsafe(this._chunkSize); this._outOffset = 0; this._handle = new ZlibHandle(mode); this._handle._owner = this; this._handle.onerror = zlibOnError; this._handle.init(windowBits, level, memLevel, strategy, this._writeState, processCallback, dictionary); } writeSync(chunk, retChunks) { const handle = this._handle; if (!handle) throw new Error('Invalid Zlib instance'); let availInBefore = chunk.length; let availOutBefore = this._chunkSize - this._outOffset; let inOff = 0; let availOutAfter; let availInAfter; let buffers; let nread = 0; const state = this._writeState; let buffer = this._outBuffer; let offset = this._outOffset; const chunkSize = this._chunkSize; while (true) { handle.writeSync(Z_PARTIAL_FLUSH, chunk, // in inOff, // in_off availInBefore, // in_len buffer, // out offset, // out_off availOutBefore); // out_len if (this._err) throw this._err; availOutAfter = state[0]; availInAfter = state[1]; const inDelta = availInBefore - availInAfter; const have = availOutBefore - availOutAfter; if (have > 0) { const out = (offset === 0 && have === buffer.length ? buffer : buffer.slice(offset, offset + have)); offset += have; if (!buffers) buffers = out; else if (buffers.push === undefined) buffers = [buffers, out]; else buffers.push(out); nread += out.byteLength; if (nread > this._maxOutputLength) { _close(this); throw new Error( `Output length exceeded maximum of ${this._maxOutputLength}` ); } } else if (have !== 0) { throw new Error('have should not go down'); } // Exhausted the output buffer, or used all the input create a new one. if (availOutAfter === 0 || offset >= chunkSize) { availOutBefore = chunkSize; offset = 0; buffer = Buffer.allocUnsafe(chunkSize); } if (availOutAfter === 0) { // Not actually done. Need to reprocess. // Also, update the availInBefore to the availInAfter value, // so that if we have to hit it a third (fourth, etc.) time, // it'll have the correct byte counts. inOff += inDelta; availInBefore = availInAfter; } else { break; } } this._outBuffer = buffer; this._outOffset = offset; if (nread === 0) buffers = Buffer.alloc(0); if (retChunks) { buffers.totalLen = nread; return buffers; } if (buffers.push === undefined) return buffers; const output = Buffer.allocUnsafe(nread); for (let i = 0, p = 0; i < buffers.length; ++i) { const buf = buffers[i]; output.set(buf, p); p += buf.length; } return output; } } class ZlibPacketWriter { constructor(protocol) { this.allocStart = 0; this.allocStartKEX = 0; this._protocol = protocol; this._zlib = new Zlib(DEFLATE); } cleanup() { if (this._zlib) _close(this._zlib); } alloc(payloadSize, force) { return Buffer.allocUnsafe(payloadSize); } finalize(payload, force) { if (this._protocol._kexinit === undefined || force) { const output = this._zlib.writeSync(payload, true); const packet = this._protocol._cipher.allocPacket(output.totalLen); if (output.push === undefined) { packet.set(output, 5); } else { for (let i = 0, p = 5; i < output.length; ++i) { const chunk = output[i]; packet.set(chunk, p); p += chunk.length; } } return packet; } return payload; } } class PacketWriter { constructor(protocol) { this.allocStart = 5; this.allocStartKEX = 5; this._protocol = protocol; } cleanup() {} alloc(payloadSize, force) { if (this._protocol._kexinit === undefined || force) return this._protocol._cipher.allocPacket(payloadSize); return Buffer.allocUnsafe(payloadSize); } finalize(packet, force) { return packet; } } class ZlibPacketReader { constructor() { this._zlib = new Zlib(INFLATE); } cleanup() { if (this._zlib) _close(this._zlib); } read(data) { return this._zlib.writeSync(data, false); } } class PacketReader { cleanup() {} read(data) { return data; } } module.exports = { PacketReader, PacketWriter, ZlibPacketReader, ZlibPacketWriter, }; /***/ }), /***/ 37465: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // TODO: // * convert listenerCount() usage to emit() return value checking? // * emit error when connection severed early (e.g. before handshake) // * add '.connected' or similar property to connection objects to allow // immediate connection status checking const { Server: netServer } = __webpack_require__(41808); const EventEmitter = __webpack_require__(82361); const { listenerCount } = EventEmitter; const { CHANNEL_OPEN_FAILURE, DEFAULT_CIPHER, DEFAULT_COMPRESSION, DEFAULT_KEX, DEFAULT_MAC, DEFAULT_SERVER_HOST_KEY, DISCONNECT_REASON, DISCONNECT_REASON_BY_VALUE, SUPPORTED_CIPHER, SUPPORTED_COMPRESSION, SUPPORTED_KEX, SUPPORTED_MAC, SUPPORTED_SERVER_HOST_KEY, } = __webpack_require__(3190); const { init: cryptoInit } = __webpack_require__(83877); const { KexInit } = __webpack_require__(65260); const { parseKey } = __webpack_require__(13781); const Protocol = __webpack_require__(53603); const { SFTP } = __webpack_require__(64061); const { writeUInt32BE } = __webpack_require__(39205); const { Channel, MAX_WINDOW, PACKET_SIZE, windowAdjust, WINDOW_THRESHOLD, } = __webpack_require__(50491); const { ChannelManager, generateAlgorithmList, isWritable, onChannelOpenFailure, onCHANNEL_CLOSE, } = __webpack_require__(17236); const MAX_PENDING_AUTHS = 10; class AuthContext extends EventEmitter { constructor(protocol, username, service, method, cb) { super(); this.username = this.user = username; this.service = service; this.method = method; this._initialResponse = false; this._finalResponse = false; this._multistep = false; this._cbfinal = (allowed, methodsLeft, isPartial) => { if (!this._finalResponse) { this._finalResponse = true; cb(this, allowed, methodsLeft, isPartial); } }; this._protocol = protocol; } accept() { this._cleanup && this._cleanup(); this._initialResponse = true; this._cbfinal(true); } reject(methodsLeft, isPartial) { this._cleanup && this._cleanup(); this._initialResponse = true; this._cbfinal(false, methodsLeft, isPartial); } } class KeyboardAuthContext extends AuthContext { constructor(protocol, username, service, method, submethods, cb) { super(protocol, username, service, method, cb); this._multistep = true; this._cb = undefined; this._onInfoResponse = (responses) => { const callback = this._cb; if (callback) { this._cb = undefined; callback(responses); } }; this.submethods = submethods; this.on('abort', () => { this._cb && this._cb(new Error('Authentication request aborted')); }); } prompt(prompts, title, instructions, cb) { if (!Array.isArray(prompts)) prompts = [ prompts ]; if (typeof title === 'function') { cb = title; title = instructions = undefined; } else if (typeof instructions === 'function') { cb = instructions; instructions = undefined; } else if (typeof cb !== 'function') { cb = undefined; } for (let i = 0; i < prompts.length; ++i) { if (typeof prompts[i] === 'string') { prompts[i] = { prompt: prompts[i], echo: true }; } } this._cb = cb; this._initialResponse = true; this._protocol.authInfoReq(title, instructions, prompts); } } class PKAuthContext extends AuthContext { constructor(protocol, username, service, method, pkInfo, cb) { super(protocol, username, service, method, cb); this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key }; this.hashAlgo = pkInfo.hashAlgo; this.signature = pkInfo.signature; this.blob = pkInfo.blob; } accept() { if (!this.signature) { this._initialResponse = true; this._protocol.authPKOK(this.key.algo, this.key.data); } else { AuthContext.prototype.accept.call(this); } } } class HostbasedAuthContext extends AuthContext { constructor(protocol, username, service, method, pkInfo, cb) { super(protocol, username, service, method, cb); this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key }; this.hashAlgo = pkInfo.hashAlgo; this.signature = pkInfo.signature; this.blob = pkInfo.blob; this.localHostname = pkInfo.localHostname; this.localUsername = pkInfo.localUsername; } } class PwdAuthContext extends AuthContext { constructor(protocol, username, service, method, password, cb) { super(protocol, username, service, method, cb); this.password = password; this._changeCb = undefined; } requestChange(prompt, cb) { if (this._changeCb) throw new Error('Change request already in progress'); if (typeof prompt !== 'string') throw new Error('prompt argument must be a string'); if (typeof cb !== 'function') throw new Error('Callback argument must be a function'); this._changeCb = cb; this._protocol.authPasswdChg(prompt); } } class Session extends EventEmitter { constructor(client, info, localChan) { super(); this.type = 'session'; this.subtype = undefined; this.server = true; this._ending = false; this._channel = undefined; this._chanInfo = { type: 'session', incoming: { id: localChan, window: MAX_WINDOW, packetSize: PACKET_SIZE, state: 'open' }, outgoing: { id: info.sender, window: info.window, packetSize: info.packetSize, state: 'open' } }; } } class Server extends EventEmitter { constructor(cfg, listener) { super(); if (typeof cfg !== 'object' || cfg === null) throw new Error('Missing configuration object'); const hostKeys = Object.create(null); const hostKeyAlgoOrder = []; const hostKeys_ = cfg.hostKeys; if (!Array.isArray(hostKeys_)) throw new Error('hostKeys must be an array'); const cfgAlgos = ( typeof cfg.algorithms === 'object' && cfg.algorithms !== null ? cfg.algorithms : {} ); const hostKeyAlgos = generateAlgorithmList( cfgAlgos.serverHostKey, DEFAULT_SERVER_HOST_KEY, SUPPORTED_SERVER_HOST_KEY ); for (let i = 0; i < hostKeys_.length; ++i) { let privateKey; if (Buffer.isBuffer(hostKeys_[i]) || typeof hostKeys_[i] === 'string') privateKey = parseKey(hostKeys_[i]); else privateKey = parseKey(hostKeys_[i].key, hostKeys_[i].passphrase); if (privateKey instanceof Error) throw new Error(`Cannot parse privateKey: ${privateKey.message}`); if (Array.isArray(privateKey)) { // OpenSSH's newer format only stores 1 key for now privateKey = privateKey[0]; } if (privateKey.getPrivatePEM() === null) throw new Error('privateKey value contains an invalid private key'); // Discard key if we already found a key of the same type if (hostKeyAlgoOrder.includes(privateKey.type)) continue; if (privateKey.type === 'ssh-rsa') { // SSH supports multiple signature hashing algorithms for RSA, so we add // the algorithms in the desired order let sha1Pos = hostKeyAlgos.indexOf('ssh-rsa'); const sha256Pos = hostKeyAlgos.indexOf('rsa-sha2-256'); const sha512Pos = hostKeyAlgos.indexOf('rsa-sha2-512'); if (sha1Pos === -1) { // Fall back to giving SHA1 the lowest priority sha1Pos = Infinity; } [sha1Pos, sha256Pos, sha512Pos].sort(compareNumbers).forEach((pos) => { if (pos === -1) return; let type; switch (pos) { case sha1Pos: type = 'ssh-rsa'; break; case sha256Pos: type = 'rsa-sha2-256'; break; case sha512Pos: type = 'rsa-sha2-512'; break; default: return; } // Store same RSA key under each hash algorithm name for convenience hostKeys[type] = privateKey; hostKeyAlgoOrder.push(type); }); } else { hostKeys[privateKey.type] = privateKey; hostKeyAlgoOrder.push(privateKey.type); } } const algorithms = { kex: generateAlgorithmList(cfgAlgos.kex, DEFAULT_KEX, SUPPORTED_KEX), serverHostKey: hostKeyAlgoOrder, cs: { cipher: generateAlgorithmList( cfgAlgos.cipher, DEFAULT_CIPHER, SUPPORTED_CIPHER ), mac: generateAlgorithmList(cfgAlgos.hmac, DEFAULT_MAC, SUPPORTED_MAC), compress: generateAlgorithmList( cfgAlgos.compress, DEFAULT_COMPRESSION, SUPPORTED_COMPRESSION ), lang: [], }, sc: undefined, }; algorithms.sc = algorithms.cs; if (typeof listener === 'function') this.on('connection', listener); const origDebug = (typeof cfg.debug === 'function' ? cfg.debug : undefined); const ident = (cfg.ident ? Buffer.from(cfg.ident) : undefined); const offer = new KexInit(algorithms); this._srv = new netServer((socket) => { if (this._connections >= this.maxConnections) { socket.destroy(); return; } ++this._connections; socket.once('close', () => { --this._connections; }); let debug; if (origDebug) { // Prepend debug output with a unique identifier in case there are // multiple clients connected at the same time const debugPrefix = `[${process.hrtime().join('.')}] `; debug = (msg) => { origDebug(`${debugPrefix}${msg}`); }; } // eslint-disable-next-line no-use-before-define new Client(socket, hostKeys, ident, offer, debug, this, cfg); }).on('error', (err) => { this.emit('error', err); }).on('listening', () => { this.emit('listening'); }).on('close', () => { this.emit('close'); }); this._connections = 0; this.maxConnections = Infinity; } injectSocket(socket) { this._srv.emit('connection', socket); } listen(...args) { this._srv.listen(...args); return this; } address() { return this._srv.address(); } getConnections(cb) { this._srv.getConnections(cb); return this; } close(cb) { this._srv.close(cb); return this; } ref() { this._srv.ref(); return this; } unref() { this._srv.unref(); return this; } } Server.KEEPALIVE_CLIENT_INTERVAL = 15000; Server.KEEPALIVE_CLIENT_COUNT_MAX = 3; class Client extends EventEmitter { constructor(socket, hostKeys, ident, offer, debug, server, srvCfg) { super(); let exchanges = 0; let acceptedAuthSvc = false; let pendingAuths = []; let authCtx; let kaTimer; let onPacket; const unsentGlobalRequestsReplies = []; this._sock = socket; this._chanMgr = new ChannelManager(this); this._debug = debug; this.noMoreSessions = false; this.authenticated = false; // Silence pre-header errors function onClientPreHeaderError(err) {} this.on('error', onClientPreHeaderError); const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => { debug(`Debug output from client: ${JSON.stringify(msg)}`); }); const kaIntvl = ( typeof srvCfg.keepaliveInterval === 'number' && isFinite(srvCfg.keepaliveInterval) && srvCfg.keepaliveInterval > 0 ? srvCfg.keepaliveInterval : ( typeof Server.KEEPALIVE_CLIENT_INTERVAL === 'number' && isFinite(Server.KEEPALIVE_CLIENT_INTERVAL) && Server.KEEPALIVE_CLIENT_INTERVAL > 0 ? Server.KEEPALIVE_CLIENT_INTERVAL : -1 ) ); const kaCountMax = ( typeof srvCfg.keepaliveCountMax === 'number' && isFinite(srvCfg.keepaliveCountMax) && srvCfg.keepaliveCountMax >= 0 ? srvCfg.keepaliveCountMax : ( typeof Server.KEEPALIVE_CLIENT_COUNT_MAX === 'number' && isFinite(Server.KEEPALIVE_CLIENT_COUNT_MAX) && Server.KEEPALIVE_CLIENT_COUNT_MAX >= 0 ? Server.KEEPALIVE_CLIENT_COUNT_MAX : -1 ) ); let kaCurCount = 0; if (kaIntvl !== -1 && kaCountMax !== -1) { this.once('ready', () => { const onClose = () => { clearInterval(kaTimer); }; this.on('close', onClose).on('end', onClose); kaTimer = setInterval(() => { if (++kaCurCount > kaCountMax) { clearInterval(kaTimer); const err = new Error('Keepalive timeout'); err.level = 'client-timeout'; this.emit('error', err); this.end(); } else { // XXX: if the server ever starts sending real global requests to // the client, we will need to add a dummy callback here to // keep the correct reply order proto.ping(); } }, kaIntvl); }); // TODO: re-verify keepalive behavior with OpenSSH onPacket = () => { kaTimer && kaTimer.refresh(); kaCurCount = 0; }; } const proto = this._protocol = new Protocol({ server: true, hostKeys, ident, offer, onPacket, greeting: srvCfg.greeting, banner: srvCfg.banner, onWrite: (data) => { if (isWritable(socket)) socket.write(data); }, onError: (err) => { if (!proto._destruct) socket.removeAllListeners('data'); this.emit('error', err); try { socket.end(); } catch {} }, onHeader: (header) => { this.removeListener('error', onClientPreHeaderError); const info = { ip: socket.remoteAddress, family: socket.remoteFamily, port: socket.remotePort, header, }; if (!server.emit('connection', this, info)) { // auto reject proto.disconnect(DISCONNECT_REASON.BY_APPLICATION); socket.end(); return; } if (header.greeting) this.emit('greeting', header.greeting); }, onHandshakeComplete: (negotiated) => { if (++exchanges > 1) this.emit('rekey'); this.emit('handshake', negotiated); }, debug, messageHandlers: { DEBUG: DEBUG_HANDLER, DISCONNECT: (p, reason, desc) => { if (reason !== DISCONNECT_REASON.BY_APPLICATION) { if (!desc) { desc = DISCONNECT_REASON_BY_VALUE[reason]; if (desc === undefined) desc = `Unexpected disconnection reason: ${reason}`; } const err = new Error(desc); err.code = reason; this.emit('error', err); } socket.end(); }, CHANNEL_OPEN: (p, info) => { // Handle incoming requests from client // Do early reject in some cases to prevent wasteful channel // allocation if ((info.type === 'session' && this.noMoreSessions) || !this.authenticated) { const reasonCode = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; return proto.channelOpenFail(info.sender, reasonCode); } let localChan = -1; let reason; let replied = false; let accept; const reject = () => { if (replied) return; replied = true; if (reason === undefined) { if (localChan === -1) reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; else reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; } if (localChan !== -1) this._chanMgr.remove(localChan); proto.channelOpenFail(info.sender, reason, ''); }; const reserveChannel = () => { localChan = this._chanMgr.add(); if (localChan === -1) { reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; if (debug) { debug('Automatic rejection of incoming channel open: ' + 'no channels available'); } } return (localChan !== -1); }; const data = info.data; switch (info.type) { case 'session': if (listenerCount(this, 'session') && reserveChannel()) { accept = () => { if (replied) return; replied = true; const instance = new Session(this, info, localChan); this._chanMgr.update(localChan, instance); proto.channelOpenConfirm(info.sender, localChan, MAX_WINDOW, PACKET_SIZE); return instance; }; this.emit('session', accept, reject); return; } break; case 'direct-tcpip': if (listenerCount(this, 'tcpip') && reserveChannel()) { accept = () => { if (replied) return; replied = true; const chanInfo = { type: undefined, incoming: { id: localChan, window: MAX_WINDOW, packetSize: PACKET_SIZE, state: 'open' }, outgoing: { id: info.sender, window: info.window, packetSize: info.packetSize, state: 'open' } }; const stream = new Channel(this, chanInfo, { server: true }); this._chanMgr.update(localChan, stream); proto.channelOpenConfirm(info.sender, localChan, MAX_WINDOW, PACKET_SIZE); return stream; }; this.emit('tcpip', accept, reject, data); return; } break; case 'direct-streamlocal@openssh.com': if (listenerCount(this, 'openssh.streamlocal') && reserveChannel()) { accept = () => { if (replied) return; replied = true; const chanInfo = { type: undefined, incoming: { id: localChan, window: MAX_WINDOW, packetSize: PACKET_SIZE, state: 'open' }, outgoing: { id: info.sender, window: info.window, packetSize: info.packetSize, state: 'open' } }; const stream = new Channel(this, chanInfo, { server: true }); this._chanMgr.update(localChan, stream); proto.channelOpenConfirm(info.sender, localChan, MAX_WINDOW, PACKET_SIZE); return stream; }; this.emit('openssh.streamlocal', accept, reject, data); return; } break; default: // Automatically reject any unsupported channel open requests reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; if (debug) { debug('Automatic rejection of unsupported incoming channel open' + ` type: ${info.type}`); } } if (reason === undefined) { reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; if (debug) { debug('Automatic rejection of unexpected incoming channel open' + ` for: ${info.type}`); } } reject(); }, CHANNEL_OPEN_CONFIRMATION: (p, info) => { const channel = this._chanMgr.get(info.recipient); if (typeof channel !== 'function') return; const chanInfo = { type: channel.type, incoming: { id: info.recipient, window: MAX_WINDOW, packetSize: PACKET_SIZE, state: 'open' }, outgoing: { id: info.sender, window: info.window, packetSize: info.packetSize, state: 'open' } }; const instance = new Channel(this, chanInfo, { server: true }); this._chanMgr.update(info.recipient, instance); channel(undefined, instance); }, CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => { const channel = this._chanMgr.get(recipient); if (typeof channel !== 'function') return; const info = { reason, description }; onChannelOpenFailure(this, recipient, info, channel); }, CHANNEL_DATA: (p, recipient, data) => { let channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; if (channel.constructor === Session) { channel = channel._channel; if (!channel) return; } // The remote party should not be sending us data if there is no // window space available ... // TODO: raise error on data with not enough window? if (channel.incoming.window === 0) return; channel.incoming.window -= data.length; if (channel.push(data) === false) { channel._waitChanDrain = true; return; } if (channel.incoming.window <= WINDOW_THRESHOLD) windowAdjust(channel); }, CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => { // NOOP -- should not be sent by client }, CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => { let channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; if (channel.constructor === Session) { channel = channel._channel; if (!channel) return; } // The other side is allowing us to send `amount` more bytes of data channel.outgoing.window += amount; if (channel._waitWindow) { channel._waitWindow = false; if (channel._chunk) { channel._write(channel._chunk, null, channel._chunkcb); } else if (channel._chunkcb) { channel._chunkcb(); } else if (channel._chunkErr) { channel.stderr._write(channel._chunkErr, null, channel._chunkcbErr); } else if (channel._chunkcbErr) { channel._chunkcbErr(); } } }, CHANNEL_SUCCESS: (p, recipient) => { let channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; if (channel.constructor === Session) { channel = channel._channel; if (!channel) return; } if (channel._callbacks.length) channel._callbacks.shift()(false); }, CHANNEL_FAILURE: (p, recipient) => { let channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; if (channel.constructor === Session) { channel = channel._channel; if (!channel) return; } if (channel._callbacks.length) channel._callbacks.shift()(true); }, CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => { const session = this._chanMgr.get(recipient); if (typeof session !== 'object' || session === null) return; let replied = false; let accept; let reject; if (session.constructor !== Session) { // normal Channel instance if (wantReply) proto.channelFailure(session.outgoing.id); return; } if (wantReply) { // "real session" requests will have custom accept behaviors if (type !== 'shell' && type !== 'exec' && type !== 'subsystem') { accept = () => { if (replied || session._ending || session._channel) return; replied = true; proto.channelSuccess(session._chanInfo.outgoing.id); }; } reject = () => { if (replied || session._ending || session._channel) return; replied = true; proto.channelFailure(session._chanInfo.outgoing.id); }; } if (session._ending) { reject && reject(); return; } switch (type) { // "pre-real session start" requests case 'env': if (listenerCount(session, 'env')) { session.emit('env', accept, reject, { key: data.name, val: data.value }); return; } break; case 'pty-req': if (listenerCount(session, 'pty')) { session.emit('pty', accept, reject, data); return; } break; case 'window-change': if (listenerCount(session, 'window-change')) session.emit('window-change', accept, reject, data); else reject && reject(); break; case 'x11-req': if (listenerCount(session, 'x11')) { session.emit('x11', accept, reject, data); return; } break; // "post-real session start" requests case 'signal': if (listenerCount(session, 'signal')) { session.emit('signal', accept, reject, { name: data }); return; } break; // XXX: is `auth-agent-req@openssh.com` really "post-real session // start"? case 'auth-agent-req@openssh.com': if (listenerCount(session, 'auth-agent')) { session.emit('auth-agent', accept, reject); return; } break; // "real session start" requests case 'shell': if (listenerCount(session, 'shell')) { accept = () => { if (replied || session._ending || session._channel) return; replied = true; if (wantReply) proto.channelSuccess(session._chanInfo.outgoing.id); const channel = new Channel( this, session._chanInfo, { server: true } ); channel.subtype = session.subtype = type; session._channel = channel; return channel; }; session.emit('shell', accept, reject); return; } break; case 'exec': if (listenerCount(session, 'exec')) { accept = () => { if (replied || session._ending || session._channel) return; replied = true; if (wantReply) proto.channelSuccess(session._chanInfo.outgoing.id); const channel = new Channel( this, session._chanInfo, { server: true } ); channel.subtype = session.subtype = type; session._channel = channel; return channel; }; session.emit('exec', accept, reject, { command: data }); return; } break; case 'subsystem': { let useSFTP = (data === 'sftp'); accept = () => { if (replied || session._ending || session._channel) return; replied = true; if (wantReply) proto.channelSuccess(session._chanInfo.outgoing.id); let instance; if (useSFTP) { instance = new SFTP(this, session._chanInfo, { server: true, debug, }); } else { instance = new Channel( this, session._chanInfo, { server: true } ); instance.subtype = session.subtype = `${type}:${data}`; } session._channel = instance; return instance; }; if (data === 'sftp') { if (listenerCount(session, 'sftp')) { session.emit('sftp', accept, reject); return; } useSFTP = false; } if (listenerCount(session, 'subsystem')) { session.emit('subsystem', accept, reject, { name: data }); return; } break; } } debug && debug( `Automatic rejection of incoming channel request: ${type}` ); reject && reject(); }, CHANNEL_EOF: (p, recipient) => { let channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; if (channel.constructor === Session) { if (!channel._ending) { channel._ending = true; channel.emit('eof'); channel.emit('end'); } channel = channel._channel; if (!channel) return; } if (channel.incoming.state !== 'open') return; channel.incoming.state = 'eof'; if (channel.readable) channel.push(null); }, CHANNEL_CLOSE: (p, recipient) => { let channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; if (channel.constructor === Session) { channel._ending = true; channel.emit('close'); channel = channel._channel; if (!channel) return; } onCHANNEL_CLOSE(this, recipient, channel); }, // Begin service/auth-related ========================================== SERVICE_REQUEST: (p, service) => { if (exchanges === 0 || acceptedAuthSvc || this.authenticated || service !== 'ssh-userauth') { proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE); socket.end(); return; } acceptedAuthSvc = true; proto.serviceAccept(service); }, USERAUTH_REQUEST: (p, username, service, method, methodData) => { if (exchanges === 0 || this.authenticated || (authCtx && (authCtx.username !== username || authCtx.service !== service)) // TODO: support hostbased auth || (method !== 'password' && method !== 'publickey' && method !== 'hostbased' && method !== 'keyboard-interactive' && method !== 'none') || pendingAuths.length === MAX_PENDING_AUTHS) { proto.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR); socket.end(); return; } else if (service !== 'ssh-connection') { proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE); socket.end(); return; } let ctx; switch (method) { case 'keyboard-interactive': ctx = new KeyboardAuthContext(proto, username, service, method, methodData, onAuthDecide); break; case 'publickey': ctx = new PKAuthContext(proto, username, service, method, methodData, onAuthDecide); break; case 'hostbased': ctx = new HostbasedAuthContext(proto, username, service, method, methodData, onAuthDecide); break; case 'password': if (authCtx && authCtx instanceof PwdAuthContext && authCtx._changeCb) { const cb = authCtx._changeCb; authCtx._changeCb = undefined; cb(methodData.newPassword); return; } ctx = new PwdAuthContext(proto, username, service, method, methodData, onAuthDecide); break; case 'none': ctx = new AuthContext(proto, username, service, method, onAuthDecide); break; } if (authCtx) { if (!authCtx._initialResponse) { return pendingAuths.push(ctx); } else if (authCtx._multistep && !authCtx._finalResponse) { // RFC 4252 says to silently abort the current auth request if a // new auth request comes in before the final response from an // auth method that requires additional request/response exchanges // -- this means keyboard-interactive for now ... authCtx._cleanup && authCtx._cleanup(); authCtx.emit('abort'); } } authCtx = ctx; if (listenerCount(this, 'authentication')) this.emit('authentication', authCtx); else authCtx.reject(); }, USERAUTH_INFO_RESPONSE: (p, responses) => { if (authCtx && authCtx instanceof KeyboardAuthContext) authCtx._onInfoResponse(responses); }, // End service/auth-related ============================================ GLOBAL_REQUEST: (p, name, wantReply, data) => { const reply = { type: null, buf: null }; function setReply(type, buf) { reply.type = type; reply.buf = buf; sendReplies(); } if (wantReply) unsentGlobalRequestsReplies.push(reply); if ((name === 'tcpip-forward' || name === 'cancel-tcpip-forward' || name === 'no-more-sessions@openssh.com' || name === 'streamlocal-forward@openssh.com' || name === 'cancel-streamlocal-forward@openssh.com') && listenerCount(this, 'request') && this.authenticated) { let accept; let reject; if (wantReply) { let replied = false; accept = (chosenPort) => { if (replied) return; replied = true; let bufPort; if (name === 'tcpip-forward' && data.bindPort === 0 && typeof chosenPort === 'number') { bufPort = Buffer.allocUnsafe(4); writeUInt32BE(bufPort, chosenPort, 0); } setReply('SUCCESS', bufPort); }; reject = () => { if (replied) return; replied = true; setReply('FAILURE'); }; } if (name === 'no-more-sessions@openssh.com') { this.noMoreSessions = true; accept && accept(); return; } this.emit('request', accept, reject, name, data); } else if (wantReply) { setReply('FAILURE'); } }, }, }); socket.pause(); cryptoInit.then(() => { proto.start(); socket.on('data', (data) => { try { proto.parse(data, 0, data.length); } catch (ex) { this.emit('error', ex); try { if (isWritable(socket)) socket.end(); } catch {} } }); socket.resume(); }).catch((err) => { this.emit('error', err); try { if (isWritable(socket)) socket.end(); } catch {} }); socket.on('error', (err) => { err.level = 'socket'; this.emit('error', err); }).once('end', () => { debug && debug('Socket ended'); proto.cleanup(); this.emit('end'); }).once('close', () => { debug && debug('Socket closed'); proto.cleanup(); this.emit('close'); const err = new Error('No response from server'); // Simulate error for pending channels and close any open channels this._chanMgr.cleanup(err); }); const onAuthDecide = (ctx, allowed, methodsLeft, isPartial) => { if (authCtx === ctx && !this.authenticated) { if (allowed) { authCtx = undefined; this.authenticated = true; proto.authSuccess(); pendingAuths = []; this.emit('ready'); } else { proto.authFailure(methodsLeft, isPartial); if (pendingAuths.length) { authCtx = pendingAuths.pop(); if (listenerCount(this, 'authentication')) this.emit('authentication', authCtx); else authCtx.reject(); } } } }; function sendReplies() { while (unsentGlobalRequestsReplies.length > 0 && unsentGlobalRequestsReplies[0].type) { const reply = unsentGlobalRequestsReplies.shift(); if (reply.type === 'SUCCESS') proto.requestSuccess(reply.buf); if (reply.type === 'FAILURE') proto.requestFailure(); } } } end() { if (this._sock && isWritable(this._sock)) { this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION); this._sock.end(); } return this; } x11(originAddr, originPort, cb) { const opts = { originAddr, originPort }; openChannel(this, 'x11', opts, cb); return this; } forwardOut(boundAddr, boundPort, remoteAddr, remotePort, cb) { const opts = { boundAddr, boundPort, remoteAddr, remotePort }; openChannel(this, 'forwarded-tcpip', opts, cb); return this; } openssh_forwardOutStreamLocal(socketPath, cb) { const opts = { socketPath }; openChannel(this, 'forwarded-streamlocal@openssh.com', opts, cb); return this; } rekey(cb) { let error; try { this._protocol.rekey(); } catch (ex) { error = ex; } // TODO: re-throw error if no callback? if (typeof cb === 'function') { if (error) process.nextTick(cb, error); else this.once('rekey', cb); } } setNoDelay(noDelay) { if (this._sock && typeof this._sock.setNoDelay === 'function') this._sock.setNoDelay(noDelay); return this; } } function openChannel(self, type, opts, cb) { // Ask the client to open a channel for some purpose (e.g. a forwarded TCP // connection) const initWindow = MAX_WINDOW; const maxPacket = PACKET_SIZE; if (typeof opts === 'function') { cb = opts; opts = {}; } const wrapper = (err, stream) => { cb(err, stream); }; wrapper.type = type; const localChan = self._chanMgr.add(wrapper); if (localChan === -1) { cb(new Error('No free channels available')); return; } switch (type) { case 'forwarded-tcpip': self._protocol.forwardedTcpip(localChan, initWindow, maxPacket, opts); break; case 'x11': self._protocol.x11(localChan, initWindow, maxPacket, opts); break; case 'forwarded-streamlocal@openssh.com': self._protocol.openssh_forwardedStreamLocal( localChan, initWindow, maxPacket, opts ); break; default: throw new Error(`Unsupported channel type: ${type}`); } } function compareNumbers(a, b) { return a - b; } module.exports = Server; module.exports.IncomingClient = Client; /***/ }), /***/ 17236: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const { SFTP } = __webpack_require__(64061); const MAX_CHANNEL = 2 ** 32 - 1; function onChannelOpenFailure(self, recipient, info, cb) { self._chanMgr.remove(recipient); if (typeof cb !== 'function') return; let err; if (info instanceof Error) { err = info; } else if (typeof info === 'object' && info !== null) { err = new Error(`(SSH) Channel open failure: ${info.description}`); err.reason = info.reason; } else { err = new Error( '(SSH) Channel open failure: server closed channel unexpectedly' ); err.reason = ''; } cb(err); } function onCHANNEL_CLOSE(self, recipient, channel, err, dead) { if (typeof channel === 'function') { // We got CHANNEL_CLOSE instead of CHANNEL_OPEN_FAILURE when // requesting to open a channel onChannelOpenFailure(self, recipient, err, channel); return; } if (typeof channel !== 'object' || channel === null) return; if (channel.incoming && channel.incoming.state === 'closed') return; self._chanMgr.remove(recipient); if (channel.server && channel.constructor.name === 'Session') return; channel.incoming.state = 'closed'; if (channel.readable) channel.push(null); if (channel.server) { if (channel.stderr.writable) channel.stderr.end(); } else if (channel.stderr.readable) { channel.stderr.push(null); } if (channel.constructor !== SFTP && (channel.outgoing.state === 'open' || channel.outgoing.state === 'eof') && !dead) { channel.close(); } if (channel.outgoing.state === 'closing') channel.outgoing.state = 'closed'; const readState = channel._readableState; const writeState = channel._writableState; if (writeState && !writeState.ending && !writeState.finished && !dead) channel.end(); // Take care of any outstanding channel requests const chanCallbacks = channel._callbacks; channel._callbacks = []; for (let i = 0; i < chanCallbacks.length; ++i) chanCallbacks[i](true); if (channel.server) { if (!channel.readable || channel.destroyed || (readState && readState.endEmitted)) { channel.emit('close'); } else { channel.once('end', () => channel.emit('close')); } } else { let doClose; switch (channel.type) { case 'direct-streamlocal@openssh.com': case 'direct-tcpip': doClose = () => channel.emit('close'); break; default: { // Align more with node child processes, where the close event gets // the same arguments as the exit event const exit = channel._exit; doClose = () => { if (exit.code === null) channel.emit('close', exit.code, exit.signal, exit.dump, exit.desc); else channel.emit('close', exit.code); }; } } if (!channel.readable || channel.destroyed || (readState && readState.endEmitted)) { doClose(); } else { channel.once('end', doClose); } const errReadState = channel.stderr._readableState; if (!channel.stderr.readable || channel.stderr.destroyed || (errReadState && errReadState.endEmitted)) { channel.stderr.emit('close'); } else { channel.stderr.once('end', () => channel.stderr.emit('close')); } } } class ChannelManager { constructor(client) { this._client = client; this._channels = {}; this._cur = -1; this._count = 0; } add(val) { // Attempt to reserve an id let id; // Optimized paths if (this._cur < MAX_CHANNEL) { id = ++this._cur; } else if (this._count === 0) { // Revert and reset back to fast path once we no longer have any channels // open this._cur = 0; id = 0; } else { // Slower lookup path // This path is triggered we have opened at least MAX_CHANNEL channels // while having at least one channel open at any given time, so we have // to search for a free id. const channels = this._channels; for (let i = 0; i < MAX_CHANNEL; ++i) { if (channels[i] === undefined) { id = i; break; } } } if (id === undefined) return -1; this._channels[id] = (val || true); ++this._count; return id; } update(id, val) { if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) throw new Error(`Invalid channel id: ${id}`); if (val && this._channels[id]) this._channels[id] = val; } get(id) { if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) throw new Error(`Invalid channel id: ${id}`); return this._channels[id]; } remove(id) { if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) throw new Error(`Invalid channel id: ${id}`); if (this._channels[id]) { delete this._channels[id]; if (this._count) --this._count; } } cleanup(err) { const channels = this._channels; this._channels = {}; this._cur = -1; this._count = 0; const chanIDs = Object.keys(channels); const client = this._client; for (let i = 0; i < chanIDs.length; ++i) { const id = +chanIDs[i]; const channel = channels[id]; onCHANNEL_CLOSE(client, id, channel._channel || channel, err, true); } } } const isRegExp = (() => { const toString = Object.prototype.toString; return (val) => toString.call(val) === '[object RegExp]'; })(); function generateAlgorithmList(algoList, defaultList, supportedList) { if (Array.isArray(algoList) && algoList.length > 0) { // Exact list for (let i = 0; i < algoList.length; ++i) { if (supportedList.indexOf(algoList[i]) === -1) throw new Error(`Unsupported algorithm: ${algoList[i]}`); } return algoList; } if (typeof algoList === 'object' && algoList !== null) { // Operations based on the default list const keys = Object.keys(algoList); let list = defaultList; for (let i = 0; i < keys.length; ++i) { const key = keys[i]; let val = algoList[key]; switch (key) { case 'append': if (!Array.isArray(val)) val = [val]; if (Array.isArray(val)) { for (let j = 0; j < val.length; ++j) { const append = val[j]; if (typeof append === 'string') { if (!append || list.indexOf(append) !== -1) continue; if (supportedList.indexOf(append) === -1) throw new Error(`Unsupported algorithm: ${append}`); if (list === defaultList) list = list.slice(); list.push(append); } else if (isRegExp(append)) { for (let k = 0; k < supportedList.length; ++k) { const algo = supportedList[k]; if (append.test(algo)) { if (list.indexOf(algo) !== -1) continue; if (list === defaultList) list = list.slice(); list.push(algo); } } } } } break; case 'prepend': if (!Array.isArray(val)) val = [val]; if (Array.isArray(val)) { for (let j = val.length; j >= 0; --j) { const prepend = val[j]; if (typeof prepend === 'string') { if (!prepend || list.indexOf(prepend) !== -1) continue; if (supportedList.indexOf(prepend) === -1) throw new Error(`Unsupported algorithm: ${prepend}`); if (list === defaultList) list = list.slice(); list.unshift(prepend); } else if (isRegExp(prepend)) { for (let k = supportedList.length; k >= 0; --k) { const algo = supportedList[k]; if (prepend.test(algo)) { if (list.indexOf(algo) !== -1) continue; if (list === defaultList) list = list.slice(); list.unshift(algo); } } } } } break; case 'remove': if (!Array.isArray(val)) val = [val]; if (Array.isArray(val)) { for (let j = 0; j < val.length; ++j) { const search = val[j]; if (typeof search === 'string') { if (!search) continue; const idx = list.indexOf(search); if (idx === -1) continue; if (list === defaultList) list = list.slice(); list.splice(idx, 1); } else if (isRegExp(search)) { for (let k = 0; k < list.length; ++k) { if (search.test(list[k])) { if (list === defaultList) list = list.slice(); list.splice(k, 1); --k; } } } } } break; } } return list; } return defaultList; } module.exports = { ChannelManager, generateAlgorithmList, onChannelOpenFailure, onCHANNEL_CLOSE, isWritable: (stream) => { // XXX: hack to workaround regression in node // See: https://github.com/nodejs/node/issues/36029 return (stream && stream.writable && stream._readableState && stream._readableState.ended === false); }, }; /***/ }), /***/ 31852: /***/ ((module) => { module.exports = shift function shift (stream) { var rs = stream._readableState if (!rs) return null return (rs.objectMode || typeof stream._duplexState === 'number') ? stream.read() : stream.read(getStateLength(rs)) } function getStateLength (state) { if (state.buffer.length) { // Since node 6.3.0 state.buffer is a BufferList not an array if (state.buffer.head) { return state.buffer.head.data.length } return state.buffer[0].length } return state.length } /***/ }), /***/ 81237: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const { EventEmitter } = __webpack_require__(82361) const STREAM_DESTROYED = new Error('Stream was destroyed') const PREMATURE_CLOSE = new Error('Premature close') const FIFO = __webpack_require__(91607) const TextDecoder = __webpack_require__(27540) /* eslint-disable no-multi-spaces */ // 29 bits used total (4 from shared, 14 from read, and 11 from write) const MAX = ((1 << 29) - 1) // Shared state const OPENING = 0b0001 const PREDESTROYING = 0b0010 const DESTROYING = 0b0100 const DESTROYED = 0b1000 const NOT_OPENING = MAX ^ OPENING const NOT_PREDESTROYING = MAX ^ PREDESTROYING // Read state (4 bit offset from shared state) const READ_ACTIVE = 0b00000000000001 << 4 const READ_UPDATING = 0b00000000000010 << 4 const READ_PRIMARY = 0b00000000000100 << 4 const READ_QUEUED = 0b00000000001000 << 4 const READ_RESUMED = 0b00000000010000 << 4 const READ_PIPE_DRAINED = 0b00000000100000 << 4 const READ_ENDING = 0b00000001000000 << 4 const READ_EMIT_DATA = 0b00000010000000 << 4 const READ_EMIT_READABLE = 0b00000100000000 << 4 const READ_EMITTED_READABLE = 0b00001000000000 << 4 const READ_DONE = 0b00010000000000 << 4 const READ_NEXT_TICK = 0b00100000000000 << 4 const READ_NEEDS_PUSH = 0b01000000000000 << 4 const READ_READ_AHEAD = 0b10000000000000 << 4 // Combined read state const READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED const READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH const READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE const READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED const READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD const READ_NOT_ACTIVE = MAX ^ READ_ACTIVE const READ_NON_PRIMARY = MAX ^ READ_PRIMARY const READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH) const READ_PUSHED = MAX ^ READ_NEEDS_PUSH const READ_PAUSED = MAX ^ READ_RESUMED const READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE) const READ_NOT_ENDING = MAX ^ READ_ENDING const READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING const READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK const READ_NOT_UPDATING = MAX ^ READ_UPDATING const READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD const READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD // Write state (18 bit offset, 4 bit offset from shared state and 14 from read state) const WRITE_ACTIVE = 0b00000000001 << 18 const WRITE_UPDATING = 0b00000000010 << 18 const WRITE_PRIMARY = 0b00000000100 << 18 const WRITE_QUEUED = 0b00000001000 << 18 const WRITE_UNDRAINED = 0b00000010000 << 18 const WRITE_DONE = 0b00000100000 << 18 const WRITE_EMIT_DRAIN = 0b00001000000 << 18 const WRITE_NEXT_TICK = 0b00010000000 << 18 const WRITE_WRITING = 0b00100000000 << 18 const WRITE_FINISHING = 0b01000000000 << 18 const WRITE_CORKED = 0b10000000000 << 18 const WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING) const WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY const WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING) const WRITE_DRAINED = MAX ^ WRITE_UNDRAINED const WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED const WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK const WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING const WRITE_NOT_CORKED = MAX ^ WRITE_CORKED // Combined shared state const ACTIVE = READ_ACTIVE | WRITE_ACTIVE const NOT_ACTIVE = MAX ^ ACTIVE const DONE = READ_DONE | WRITE_DONE const DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING const OPEN_STATUS = DESTROY_STATUS | OPENING const AUTO_DESTROY = DESTROY_STATUS | DONE const NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY const ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK const TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE const IS_OPENING = OPEN_STATUS | TICKING // Combined shared state and read state const READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE const READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED const READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED const READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE const SHOULD_NOT_READ = OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD const READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE const READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY const READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING // Combined write state const WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE const WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED const WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE const WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE const WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED const WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE const WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING const WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE const WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE const WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY const WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS const asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator') class WritableState { constructor (stream, { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}) { this.stream = stream this.queue = new FIFO() this.highWaterMark = highWaterMark this.buffered = 0 this.error = null this.pipeline = null this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr this.byteLength = byteLengthWritable || byteLength || defaultByteLength this.map = mapWritable || map this.afterWrite = afterWrite.bind(this) this.afterUpdateNextTick = updateWriteNT.bind(this) } get ended () { return (this.stream._duplexState & WRITE_DONE) !== 0 } push (data) { if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false if (this.map !== null) data = this.map(data) this.buffered += this.byteLength(data) this.queue.push(data) if (this.buffered < this.highWaterMark) { this.stream._duplexState |= WRITE_QUEUED return true } this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED return false } shift () { const data = this.queue.shift() this.buffered -= this.byteLength(data) if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED return data } end (data) { if (typeof data === 'function') this.stream.once('finish', data) else if (data !== undefined && data !== null) this.push(data) this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY } autoBatch (data, cb) { const buffer = [] const stream = this.stream buffer.push(data) while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) { buffer.push(stream._writableState.shift()) } if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null) stream._writev(buffer, cb) } update () { const stream = this.stream stream._duplexState |= WRITE_UPDATING do { while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) { const data = this.shift() stream._duplexState |= WRITE_ACTIVE_AND_WRITING stream._write(data, this.afterWrite) } if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary() } while (this.continueUpdate() === true) stream._duplexState &= WRITE_NOT_UPDATING } updateNonPrimary () { const stream = this.stream if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) { stream._duplexState = stream._duplexState | WRITE_ACTIVE stream._final(afterFinal.bind(this)) return } if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) { if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) { stream._duplexState |= ACTIVE stream._destroy(afterDestroy.bind(this)) } return } if ((stream._duplexState & IS_OPENING) === OPENING) { stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING stream._open(afterOpen.bind(this)) } } continueUpdate () { if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false this.stream._duplexState &= WRITE_NOT_NEXT_TICK return true } updateCallback () { if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) this.update() else this.updateNextTick() } updateNextTick () { if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return this.stream._duplexState |= WRITE_NEXT_TICK if ((this.stream._duplexState & WRITE_UPDATING) === 0) queueMicrotask(this.afterUpdateNextTick) } } class ReadableState { constructor (stream, { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}) { this.stream = stream this.queue = new FIFO() this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark this.buffered = 0 this.readAhead = highWaterMark > 0 this.error = null this.pipeline = null this.byteLength = byteLengthReadable || byteLength || defaultByteLength this.map = mapReadable || map this.pipeTo = null this.afterRead = afterRead.bind(this) this.afterUpdateNextTick = updateReadNT.bind(this) } get ended () { return (this.stream._duplexState & READ_DONE) !== 0 } pipe (pipeTo, cb) { if (this.pipeTo !== null) throw new Error('Can only pipe to one destination') if (typeof cb !== 'function') cb = null this.stream._duplexState |= READ_PIPE_DRAINED this.pipeTo = pipeTo this.pipeline = new Pipeline(this.stream, pipeTo, cb) if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes if (isStreamx(pipeTo)) { pipeTo._writableState.pipeline = this.pipeline if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself } else { const onerror = this.pipeline.done.bind(this.pipeline, pipeTo) const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg pipeTo.on('error', onerror) pipeTo.on('close', onclose) pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) } pipeTo.on('drain', afterDrain.bind(this)) this.stream.emit('piping', pipeTo) pipeTo.emit('pipe', this.stream) } push (data) { const stream = this.stream if (data === null) { this.highWaterMark = 0 stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED return false } if (this.map !== null) { data = this.map(data) if (data === null) { stream._duplexState &= READ_PUSHED return this.buffered < this.highWaterMark } } this.buffered += this.byteLength(data) this.queue.push(data) stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED return this.buffered < this.highWaterMark } shift () { const data = this.queue.shift() this.buffered -= this.byteLength(data) if (this.buffered === 0) this.stream._duplexState &= READ_NOT_QUEUED return data } unshift (data) { const pending = [this.map !== null ? this.map(data) : data] while (this.buffered > 0) pending.push(this.shift()) for (let i = 0; i < pending.length - 1; i++) { const data = pending[i] this.buffered += this.byteLength(data) this.queue.push(data) } this.push(pending[pending.length - 1]) } read () { const stream = this.stream if ((stream._duplexState & READ_STATUS) === READ_QUEUED) { const data = this.shift() if (this.pipeTo !== null && this.pipeTo.write(data) === false) stream._duplexState &= READ_PIPE_NOT_DRAINED if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit('data', data) return data } if (this.readAhead === false) { stream._duplexState |= READ_READ_AHEAD this.updateNextTick() } return null } drain () { const stream = this.stream while ((stream._duplexState & READ_STATUS) === READ_QUEUED && (stream._duplexState & READ_FLOWING) !== 0) { const data = this.shift() if (this.pipeTo !== null && this.pipeTo.write(data) === false) stream._duplexState &= READ_PIPE_NOT_DRAINED if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit('data', data) } } update () { const stream = this.stream stream._duplexState |= READ_UPDATING do { this.drain() while (this.buffered < this.highWaterMark && (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD) { stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH stream._read(this.afterRead) this.drain() } if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) { stream._duplexState |= READ_EMITTED_READABLE stream.emit('readable') } if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary() } while (this.continueUpdate() === true) stream._duplexState &= READ_NOT_UPDATING } updateNonPrimary () { const stream = this.stream if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) { stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING stream.emit('end') if ((stream._duplexState & AUTO_DESTROY) === DONE) stream._duplexState |= DESTROYING if (this.pipeTo !== null) this.pipeTo.end() } if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) { if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) { stream._duplexState |= ACTIVE stream._destroy(afterDestroy.bind(this)) } return } if ((stream._duplexState & IS_OPENING) === OPENING) { stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING stream._open(afterOpen.bind(this)) } } continueUpdate () { if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false this.stream._duplexState &= READ_NOT_NEXT_TICK return true } updateCallback () { if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) this.update() else this.updateNextTick() } updateNextTickIfOpen () { if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return this.stream._duplexState |= READ_NEXT_TICK if ((this.stream._duplexState & READ_UPDATING) === 0) queueMicrotask(this.afterUpdateNextTick) } updateNextTick () { if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return this.stream._duplexState |= READ_NEXT_TICK if ((this.stream._duplexState & READ_UPDATING) === 0) queueMicrotask(this.afterUpdateNextTick) } } class TransformState { constructor (stream) { this.data = null this.afterTransform = afterTransform.bind(stream) this.afterFinal = null } } class Pipeline { constructor (src, dst, cb) { this.from = src this.to = dst this.afterPipe = cb this.error = null this.pipeToFinished = false } finished () { this.pipeToFinished = true } done (stream, err) { if (err) this.error = err if (stream === this.to) { this.to = null if (this.from !== null) { if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) { this.from.destroy(this.error || new Error('Writable stream closed prematurely')) } return } } if (stream === this.from) { this.from = null if (this.to !== null) { if ((stream._duplexState & READ_DONE) === 0) { this.to.destroy(this.error || new Error('Readable stream closed before ending')) } return } } if (this.afterPipe !== null) this.afterPipe(this.error) this.to = this.from = this.afterPipe = null } } function afterDrain () { this.stream._duplexState |= READ_PIPE_DRAINED this.updateCallback() } function afterFinal (err) { const stream = this.stream if (err) stream.destroy(err) if ((stream._duplexState & DESTROY_STATUS) === 0) { stream._duplexState |= WRITE_DONE stream.emit('finish') } if ((stream._duplexState & AUTO_DESTROY) === DONE) { stream._duplexState |= DESTROYING } stream._duplexState &= WRITE_NOT_FINISHING // no need to wait the extra tick here, so we short circuit that if ((stream._duplexState & WRITE_UPDATING) === 0) this.update() else this.updateNextTick() } function afterDestroy (err) { const stream = this.stream if (!err && this.error !== STREAM_DESTROYED) err = this.error if (err) stream.emit('error', err) stream._duplexState |= DESTROYED stream.emit('close') const rs = stream._readableState const ws = stream._writableState if (rs !== null && rs.pipeline !== null) rs.pipeline.done(stream, err) if (ws !== null) { while (ws.drains !== null && ws.drains.length > 0) ws.drains.shift().resolve(false) if (ws.pipeline !== null) ws.pipeline.done(stream, err) } } function afterWrite (err) { const stream = this.stream if (err) stream.destroy(err) stream._duplexState &= WRITE_NOT_ACTIVE if (this.drains !== null) tickDrains(this.drains) if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) { stream._duplexState &= WRITE_DRAINED if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) { stream.emit('drain') } } this.updateCallback() } function afterRead (err) { if (err) this.stream.destroy(err) this.stream._duplexState &= READ_NOT_ACTIVE if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) this.stream._duplexState &= READ_NO_READ_AHEAD this.updateCallback() } function updateReadNT () { if ((this.stream._duplexState & READ_UPDATING) === 0) { this.stream._duplexState &= READ_NOT_NEXT_TICK this.update() } } function updateWriteNT () { if ((this.stream._duplexState & WRITE_UPDATING) === 0) { this.stream._duplexState &= WRITE_NOT_NEXT_TICK this.update() } } function tickDrains (drains) { for (let i = 0; i < drains.length; i++) { // drains.writes are monotonic, so if one is 0 its always the first one if (--drains[i].writes === 0) { drains.shift().resolve(true) i-- } } } function afterOpen (err) { const stream = this.stream if (err) stream.destroy(err) if ((stream._duplexState & DESTROYING) === 0) { if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) stream._duplexState |= READ_PRIMARY if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) stream._duplexState |= WRITE_PRIMARY stream.emit('open') } stream._duplexState &= NOT_ACTIVE if (stream._writableState !== null) { stream._writableState.updateCallback() } if (stream._readableState !== null) { stream._readableState.updateCallback() } } function afterTransform (err, data) { if (data !== undefined && data !== null) this.push(data) this._writableState.afterWrite(err) } function newListener (name) { if (this._readableState !== null) { if (name === 'data') { this._duplexState |= (READ_EMIT_DATA | READ_RESUMED_READ_AHEAD) this._readableState.updateNextTick() } if (name === 'readable') { this._duplexState |= READ_EMIT_READABLE this._readableState.updateNextTick() } } if (this._writableState !== null) { if (name === 'drain') { this._duplexState |= WRITE_EMIT_DRAIN this._writableState.updateNextTick() } } } class Stream extends EventEmitter { constructor (opts) { super() this._duplexState = 0 this._readableState = null this._writableState = null if (opts) { if (opts.open) this._open = opts.open if (opts.destroy) this._destroy = opts.destroy if (opts.predestroy) this._predestroy = opts.predestroy if (opts.signal) { opts.signal.addEventListener('abort', abort.bind(this)) } } this.on('newListener', newListener) } _open (cb) { cb(null) } _destroy (cb) { cb(null) } _predestroy () { // does nothing } get readable () { return this._readableState !== null ? true : undefined } get writable () { return this._writableState !== null ? true : undefined } get destroyed () { return (this._duplexState & DESTROYED) !== 0 } get destroying () { return (this._duplexState & DESTROY_STATUS) !== 0 } destroy (err) { if ((this._duplexState & DESTROY_STATUS) === 0) { if (!err) err = STREAM_DESTROYED this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY if (this._readableState !== null) { this._readableState.highWaterMark = 0 this._readableState.error = err } if (this._writableState !== null) { this._writableState.highWaterMark = 0 this._writableState.error = err } this._duplexState |= PREDESTROYING this._predestroy() this._duplexState &= NOT_PREDESTROYING if (this._readableState !== null) this._readableState.updateNextTick() if (this._writableState !== null) this._writableState.updateNextTick() } } } class Readable extends Stream { constructor (opts) { super(opts) this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD this._readableState = new ReadableState(this, opts) if (opts) { if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD if (opts.read) this._read = opts.read if (opts.eagerOpen) this._readableState.updateNextTick() if (opts.encoding) this.setEncoding(opts.encoding) } } setEncoding (encoding) { const dec = new TextDecoder(encoding) const map = this._readableState.map || echo this._readableState.map = mapOrSkip return this function mapOrSkip (data) { const next = dec.push(data) return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next) } } _read (cb) { cb(null) } pipe (dest, cb) { this._readableState.updateNextTick() this._readableState.pipe(dest, cb) return dest } read () { this._readableState.updateNextTick() return this._readableState.read() } push (data) { this._readableState.updateNextTickIfOpen() return this._readableState.push(data) } unshift (data) { this._readableState.updateNextTickIfOpen() return this._readableState.unshift(data) } resume () { this._duplexState |= READ_RESUMED_READ_AHEAD this._readableState.updateNextTick() return this } pause () { this._duplexState &= (this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED) return this } static _fromAsyncIterator (ite, opts) { let destroy const rs = new Readable({ ...opts, read (cb) { ite.next().then(push).then(cb.bind(null, null)).catch(cb) }, predestroy () { destroy = ite.return() }, destroy (cb) { if (!destroy) return cb(null) destroy.then(cb.bind(null, null)).catch(cb) } }) return rs function push (data) { if (data.done) rs.push(null) else rs.push(data.value) } } static from (data, opts) { if (isReadStreamx(data)) return data if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts) if (!Array.isArray(data)) data = data === undefined ? [] : [data] let i = 0 return new Readable({ ...opts, read (cb) { this.push(i === data.length ? null : data[i++]) cb(null) } }) } static isBackpressured (rs) { return (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 || rs._readableState.buffered >= rs._readableState.highWaterMark } static isPaused (rs) { return (rs._duplexState & READ_RESUMED) === 0 } [asyncIterator] () { const stream = this let error = null let promiseResolve = null let promiseReject = null this.on('error', (err) => { error = err }) this.on('readable', onreadable) this.on('close', onclose) return { [asyncIterator] () { return this }, next () { return new Promise(function (resolve, reject) { promiseResolve = resolve promiseReject = reject const data = stream.read() if (data !== null) ondata(data) else if ((stream._duplexState & DESTROYED) !== 0) ondata(null) }) }, return () { return destroy(null) }, throw (err) { return destroy(err) } } function onreadable () { if (promiseResolve !== null) ondata(stream.read()) } function onclose () { if (promiseResolve !== null) ondata(null) } function ondata (data) { if (promiseReject === null) return if (error) promiseReject(error) else if (data === null && (stream._duplexState & READ_DONE) === 0) promiseReject(STREAM_DESTROYED) else promiseResolve({ value: data, done: data === null }) promiseReject = promiseResolve = null } function destroy (err) { stream.destroy(err) return new Promise((resolve, reject) => { if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true }) stream.once('close', function () { if (err) reject(err) else resolve({ value: undefined, done: true }) }) }) } } } class Writable extends Stream { constructor (opts) { super(opts) this._duplexState |= OPENING | READ_DONE this._writableState = new WritableState(this, opts) if (opts) { if (opts.writev) this._writev = opts.writev if (opts.write) this._write = opts.write if (opts.final) this._final = opts.final if (opts.eagerOpen) this._writableState.updateNextTick() } } cork () { this._duplexState |= WRITE_CORKED } uncork () { this._duplexState &= WRITE_NOT_CORKED this._writableState.updateNextTick() } _writev (batch, cb) { cb(null) } _write (data, cb) { this._writableState.autoBatch(data, cb) } _final (cb) { cb(null) } static isBackpressured (ws) { return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0 } static drained (ws) { if (ws.destroyed) return Promise.resolve(false) const state = ws._writableState const pending = (isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length) const writes = pending + ((ws._duplexState & WRITE_WRITING) ? 1 : 0) if (writes === 0) return Promise.resolve(true) if (state.drains === null) state.drains = [] return new Promise((resolve) => { state.drains.push({ writes, resolve }) }) } write (data) { this._writableState.updateNextTick() return this._writableState.push(data) } end (data) { this._writableState.updateNextTick() this._writableState.end(data) return this } } class Duplex extends Readable { // and Writable constructor (opts) { super(opts) this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD) this._writableState = new WritableState(this, opts) if (opts) { if (opts.writev) this._writev = opts.writev if (opts.write) this._write = opts.write if (opts.final) this._final = opts.final } } cork () { this._duplexState |= WRITE_CORKED } uncork () { this._duplexState &= WRITE_NOT_CORKED this._writableState.updateNextTick() } _writev (batch, cb) { cb(null) } _write (data, cb) { this._writableState.autoBatch(data, cb) } _final (cb) { cb(null) } write (data) { this._writableState.updateNextTick() return this._writableState.push(data) } end (data) { this._writableState.updateNextTick() this._writableState.end(data) return this } } class Transform extends Duplex { constructor (opts) { super(opts) this._transformState = new TransformState(this) if (opts) { if (opts.transform) this._transform = opts.transform if (opts.flush) this._flush = opts.flush } } _write (data, cb) { if (this._readableState.buffered >= this._readableState.highWaterMark) { this._transformState.data = data } else { this._transform(data, this._transformState.afterTransform) } } _read (cb) { if (this._transformState.data !== null) { const data = this._transformState.data this._transformState.data = null cb(null) this._transform(data, this._transformState.afterTransform) } else { cb(null) } } destroy (err) { super.destroy(err) if (this._transformState.data !== null) { this._transformState.data = null this._transformState.afterTransform() } } _transform (data, cb) { cb(null, data) } _flush (cb) { cb(null) } _final (cb) { this._transformState.afterFinal = cb this._flush(transformAfterFlush.bind(this)) } } class PassThrough extends Transform {} function transformAfterFlush (err, data) { const cb = this._transformState.afterFinal if (err) return cb(err) if (data !== null && data !== undefined) this.push(data) this.push(null) cb(null) } function pipelinePromise (...streams) { return new Promise((resolve, reject) => { return pipeline(...streams, (err) => { if (err) return reject(err) resolve() }) }) } function pipeline (stream, ...streams) { const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams] const done = (all.length && typeof all[all.length - 1] === 'function') ? all.pop() : null if (all.length < 2) throw new Error('Pipeline requires at least 2 streams') let src = all[0] let dest = null let error = null for (let i = 1; i < all.length; i++) { dest = all[i] if (isStreamx(src)) { src.pipe(dest, onerror) } else { errorHandle(src, true, i > 1, onerror) src.pipe(dest) } src = dest } if (done) { let fin = false const autoDestroy = isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy) dest.on('error', (err) => { if (error === null) error = err }) dest.on('finish', () => { fin = true if (!autoDestroy) done(error) }) if (autoDestroy) { dest.on('close', () => done(error || (fin ? null : PREMATURE_CLOSE))) } } return dest function errorHandle (s, rd, wr, onerror) { s.on('error', onerror) s.on('close', onclose) function onclose () { if (rd && s._readableState && !s._readableState.ended) return onerror(PREMATURE_CLOSE) if (wr && s._writableState && !s._writableState.ended) return onerror(PREMATURE_CLOSE) } } function onerror (err) { if (!err || error) return error = err for (const s of all) { s.destroy(err) } } } function echo (s) { return s } function isStream (stream) { return !!stream._readableState || !!stream._writableState } function isStreamx (stream) { return typeof stream._duplexState === 'number' && isStream(stream) } function isEnded (stream) { return !!stream._readableState && stream._readableState.ended } function isFinished (stream) { return !!stream._writableState && stream._writableState.ended } function getStreamError (stream, opts = {}) { const err = (stream._readableState && stream._readableState.error) || (stream._writableState && stream._writableState.error) // avoid implicit errors by default return (!opts.all && err === STREAM_DESTROYED) ? null : err } function isReadStreamx (stream) { return isStreamx(stream) && stream.readable } function isDisturbed (stream) { return (stream._duplexState & OPENING) !== OPENING || (stream._duplexState & ACTIVE_OR_TICKING) !== 0 } function isTypedArray (data) { return typeof data === 'object' && data !== null && typeof data.byteLength === 'number' } function defaultByteLength (data) { return isTypedArray(data) ? data.byteLength : 1024 } function noop () {} function abort () { this.destroy(new Error('Stream aborted.')) } function isWritev (s) { return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev } module.exports = { pipeline, pipelinePromise, isStream, isStreamx, isEnded, isFinished, isDisturbed, getStreamError, Stream, Writable, Readable, Duplex, Transform, // Export PassThrough for compatibility with Node.js core's stream module PassThrough } /***/ }), /***/ 64028: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var util = __webpack_require__(73837) var bl = __webpack_require__(10022) var headers = __webpack_require__(86510) var Writable = __webpack_require__(11451).Writable var PassThrough = __webpack_require__(11451).PassThrough var noop = function () {} var overflow = function (size) { size &= 511 return size && 512 - size } var emptyStream = function (self, offset) { var s = new Source(self, offset) s.end() return s } var mixinPax = function (header, pax) { if (pax.path) header.name = pax.path if (pax.linkpath) header.linkname = pax.linkpath if (pax.size) header.size = parseInt(pax.size, 10) header.pax = pax return header } var Source = function (self, offset) { this._parent = self this.offset = offset PassThrough.call(this, { autoDestroy: false }) } util.inherits(Source, PassThrough) Source.prototype.destroy = function (err) { this._parent.destroy(err) } var Extract = function (opts) { if (!(this instanceof Extract)) return new Extract(opts) Writable.call(this, opts) opts = opts || {} this._offset = 0 this._buffer = bl() this._missing = 0 this._partial = false this._onparse = noop this._header = null this._stream = null this._overflow = null this._cb = null this._locked = false this._destroyed = false this._pax = null this._paxGlobal = null this._gnuLongPath = null this._gnuLongLinkPath = null var self = this var b = self._buffer var oncontinue = function () { self._continue() } var onunlock = function (err) { self._locked = false if (err) return self.destroy(err) if (!self._stream) oncontinue() } var onstreamend = function () { self._stream = null var drain = overflow(self._header.size) if (drain) self._parse(drain, ondrain) else self._parse(512, onheader) if (!self._locked) oncontinue() } var ondrain = function () { self._buffer.consume(overflow(self._header.size)) self._parse(512, onheader) oncontinue() } var onpaxglobalheader = function () { var size = self._header.size self._paxGlobal = headers.decodePax(b.slice(0, size)) b.consume(size) onstreamend() } var onpaxheader = function () { var size = self._header.size self._pax = headers.decodePax(b.slice(0, size)) if (self._paxGlobal) self._pax = Object.assign({}, self._paxGlobal, self._pax) b.consume(size) onstreamend() } var ongnulongpath = function () { var size = self._header.size this._gnuLongPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding) b.consume(size) onstreamend() } var ongnulonglinkpath = function () { var size = self._header.size this._gnuLongLinkPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding) b.consume(size) onstreamend() } var onheader = function () { var offset = self._offset var header try { header = self._header = headers.decode(b.slice(0, 512), opts.filenameEncoding, opts.allowUnknownFormat) } catch (err) { self.emit('error', err) } b.consume(512) if (!header) { self._parse(512, onheader) oncontinue() return } if (header.type === 'gnu-long-path') { self._parse(header.size, ongnulongpath) oncontinue() return } if (header.type === 'gnu-long-link-path') { self._parse(header.size, ongnulonglinkpath) oncontinue() return } if (header.type === 'pax-global-header') { self._parse(header.size, onpaxglobalheader) oncontinue() return } if (header.type === 'pax-header') { self._parse(header.size, onpaxheader) oncontinue() return } if (self._gnuLongPath) { header.name = self._gnuLongPath self._gnuLongPath = null } if (self._gnuLongLinkPath) { header.linkname = self._gnuLongLinkPath self._gnuLongLinkPath = null } if (self._pax) { self._header = header = mixinPax(header, self._pax) self._pax = null } self._locked = true if (!header.size || header.type === 'directory') { self._parse(512, onheader) self.emit('entry', header, emptyStream(self, offset), onunlock) return } self._stream = new Source(self, offset) self.emit('entry', header, self._stream, onunlock) self._parse(header.size, onstreamend) oncontinue() } this._onheader = onheader this._parse(512, onheader) } util.inherits(Extract, Writable) Extract.prototype.destroy = function (err) { if (this._destroyed) return this._destroyed = true if (err) this.emit('error', err) this.emit('close') if (this._stream) this._stream.emit('close') } Extract.prototype._parse = function (size, onparse) { if (this._destroyed) return this._offset += size this._missing = size if (onparse === this._onheader) this._partial = false this._onparse = onparse } Extract.prototype._continue = function () { if (this._destroyed) return var cb = this._cb this._cb = noop if (this._overflow) this._write(this._overflow, undefined, cb) else cb() } Extract.prototype._write = function (data, enc, cb) { if (this._destroyed) return var s = this._stream var b = this._buffer var missing = this._missing if (data.length) this._partial = true // we do not reach end-of-chunk now. just forward it if (data.length < missing) { this._missing -= data.length this._overflow = null if (s) return s.write(data, cb) b.append(data) return cb() } // end-of-chunk. the parser should call cb. this._cb = cb this._missing = 0 var overflow = null if (data.length > missing) { overflow = data.slice(missing) data = data.slice(0, missing) } if (s) s.end(data) else b.append(data) this._overflow = overflow this._onparse() } Extract.prototype._final = function (cb) { if (this._partial) return this.destroy(new Error('Unexpected end of data')) cb() } module.exports = Extract /***/ }), /***/ 86510: /***/ ((__unused_webpack_module, exports) => { var alloc = Buffer.alloc var ZEROS = '0000000000000000000' var SEVENS = '7777777777777777777' var ZERO_OFFSET = '0'.charCodeAt(0) var USTAR_MAGIC = Buffer.from('ustar\x00', 'binary') var USTAR_VER = Buffer.from('00', 'binary') var GNU_MAGIC = Buffer.from('ustar\x20', 'binary') var GNU_VER = Buffer.from('\x20\x00', 'binary') var MASK = parseInt('7777', 8) var MAGIC_OFFSET = 257 var VERSION_OFFSET = 263 var clamp = function (index, len, defaultValue) { if (typeof index !== 'number') return defaultValue index = ~~index // Coerce to integer. if (index >= len) return len if (index >= 0) return index index += len if (index >= 0) return index return 0 } var toType = function (flag) { switch (flag) { case 0: return 'file' case 1: return 'link' case 2: return 'symlink' case 3: return 'character-device' case 4: return 'block-device' case 5: return 'directory' case 6: return 'fifo' case 7: return 'contiguous-file' case 72: return 'pax-header' case 55: return 'pax-global-header' case 27: return 'gnu-long-link-path' case 28: case 30: return 'gnu-long-path' } return null } var toTypeflag = function (flag) { switch (flag) { case 'file': return 0 case 'link': return 1 case 'symlink': return 2 case 'character-device': return 3 case 'block-device': return 4 case 'directory': return 5 case 'fifo': return 6 case 'contiguous-file': return 7 case 'pax-header': return 72 } return 0 } var indexOf = function (block, num, offset, end) { for (; offset < end; offset++) { if (block[offset] === num) return offset } return end } var cksum = function (block) { var sum = 8 * 32 for (var i = 0; i < 148; i++) sum += block[i] for (var j = 156; j < 512; j++) sum += block[j] return sum } var encodeOct = function (val, n) { val = val.toString(8) if (val.length > n) return SEVENS.slice(0, n) + ' ' else return ZEROS.slice(0, n - val.length) + val + ' ' } /* Copied from the node-tar repo and modified to meet * tar-stream coding standard. * * Source: https://github.com/npm/node-tar/blob/51b6627a1f357d2eb433e7378e5f05e83b7aa6cd/lib/header.js#L349 */ function parse256 (buf) { // first byte MUST be either 80 or FF // 80 for positive, FF for 2's comp var positive if (buf[0] === 0x80) positive = true else if (buf[0] === 0xFF) positive = false else return null // build up a base-256 tuple from the least sig to the highest var tuple = [] for (var i = buf.length - 1; i > 0; i--) { var byte = buf[i] if (positive) tuple.push(byte) else tuple.push(0xFF - byte) } var sum = 0 var l = tuple.length for (i = 0; i < l; i++) { sum += tuple[i] * Math.pow(256, i) } return positive ? sum : -1 * sum } var decodeOct = function (val, offset, length) { val = val.slice(offset, offset + length) offset = 0 // If prefixed with 0x80 then parse as a base-256 integer if (val[offset] & 0x80) { return parse256(val) } else { // Older versions of tar can prefix with spaces while (offset < val.length && val[offset] === 32) offset++ var end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length) while (offset < end && val[offset] === 0) offset++ if (end === offset) return 0 return parseInt(val.slice(offset, end).toString(), 8) } } var decodeStr = function (val, offset, length, encoding) { return val.slice(offset, indexOf(val, 0, offset, offset + length)).toString(encoding) } var addLength = function (str) { var len = Buffer.byteLength(str) var digits = Math.floor(Math.log(len) / Math.log(10)) + 1 if (len + digits >= Math.pow(10, digits)) digits++ return (len + digits) + str } exports.decodeLongPath = function (buf, encoding) { return decodeStr(buf, 0, buf.length, encoding) } exports.encodePax = function (opts) { // TODO: encode more stuff in pax var result = '' if (opts.name) result += addLength(' path=' + opts.name + '\n') if (opts.linkname) result += addLength(' linkpath=' + opts.linkname + '\n') var pax = opts.pax if (pax) { for (var key in pax) { result += addLength(' ' + key + '=' + pax[key] + '\n') } } return Buffer.from(result) } exports.decodePax = function (buf) { var result = {} while (buf.length) { var i = 0 while (i < buf.length && buf[i] !== 32) i++ var len = parseInt(buf.slice(0, i).toString(), 10) if (!len) return result var b = buf.slice(i + 1, len - 1).toString() var keyIndex = b.indexOf('=') if (keyIndex === -1) return result result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1) buf = buf.slice(len) } return result } exports.encode = function (opts) { var buf = alloc(512) var name = opts.name var prefix = '' if (opts.typeflag === 5 && name[name.length - 1] !== '/') name += '/' if (Buffer.byteLength(name) !== name.length) return null // utf-8 while (Buffer.byteLength(name) > 100) { var i = name.indexOf('/') if (i === -1) return null prefix += prefix ? '/' + name.slice(0, i) : name.slice(0, i) name = name.slice(i + 1) } if (Buffer.byteLength(name) > 100 || Buffer.byteLength(prefix) > 155) return null if (opts.linkname && Buffer.byteLength(opts.linkname) > 100) return null buf.write(name) buf.write(encodeOct(opts.mode & MASK, 6), 100) buf.write(encodeOct(opts.uid, 6), 108) buf.write(encodeOct(opts.gid, 6), 116) buf.write(encodeOct(opts.size, 11), 124) buf.write(encodeOct((opts.mtime.getTime() / 1000) | 0, 11), 136) buf[156] = ZERO_OFFSET + toTypeflag(opts.type) if (opts.linkname) buf.write(opts.linkname, 157) USTAR_MAGIC.copy(buf, MAGIC_OFFSET) USTAR_VER.copy(buf, VERSION_OFFSET) if (opts.uname) buf.write(opts.uname, 265) if (opts.gname) buf.write(opts.gname, 297) buf.write(encodeOct(opts.devmajor || 0, 6), 329) buf.write(encodeOct(opts.devminor || 0, 6), 337) if (prefix) buf.write(prefix, 345) buf.write(encodeOct(cksum(buf), 6), 148) return buf } exports.decode = function (buf, filenameEncoding, allowUnknownFormat) { var typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET var name = decodeStr(buf, 0, 100, filenameEncoding) var mode = decodeOct(buf, 100, 8) var uid = decodeOct(buf, 108, 8) var gid = decodeOct(buf, 116, 8) var size = decodeOct(buf, 124, 12) var mtime = decodeOct(buf, 136, 12) var type = toType(typeflag) var linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding) var uname = decodeStr(buf, 265, 32) var gname = decodeStr(buf, 297, 32) var devmajor = decodeOct(buf, 329, 8) var devminor = decodeOct(buf, 337, 8) var c = cksum(buf) // checksum is still initial value if header was null. if (c === 8 * 32) return null // valid checksum if (c !== decodeOct(buf, 148, 8)) throw new Error('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?') if (USTAR_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0) { // ustar (posix) format. // prepend prefix, if present. if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + '/' + name } else if (GNU_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0 && GNU_VER.compare(buf, VERSION_OFFSET, VERSION_OFFSET + 2) === 0) { // 'gnu'/'oldgnu' format. Similar to ustar, but has support for incremental and // multi-volume tarballs. } else { if (!allowUnknownFormat) { throw new Error('Invalid tar header: unknown format.') } } // to support old tar versions that use trailing / to indicate dirs if (typeflag === 0 && name && name[name.length - 1] === '/') typeflag = 5 return { name, mode, uid, gid, size, mtime: new Date(1000 * mtime), type, linkname, uname, gname, devmajor, devminor } } /***/ }), /***/ 53871: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { exports.extract = __webpack_require__(64028) exports.pack = __webpack_require__(70809) /***/ }), /***/ 70809: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var constants = __webpack_require__(17268) var eos = __webpack_require__(12840) var inherits = __webpack_require__(94378) var alloc = Buffer.alloc var Readable = __webpack_require__(11451).Readable var Writable = __webpack_require__(11451).Writable var StringDecoder = __webpack_require__(71576).StringDecoder var headers = __webpack_require__(86510) var DMODE = parseInt('755', 8) var FMODE = parseInt('644', 8) var END_OF_TAR = alloc(1024) var noop = function () {} var overflow = function (self, size) { size &= 511 if (size) self.push(END_OF_TAR.slice(0, 512 - size)) } function modeToType (mode) { switch (mode & constants.S_IFMT) { case constants.S_IFBLK: return 'block-device' case constants.S_IFCHR: return 'character-device' case constants.S_IFDIR: return 'directory' case constants.S_IFIFO: return 'fifo' case constants.S_IFLNK: return 'symlink' } return 'file' } var Sink = function (to) { Writable.call(this) this.written = 0 this._to = to this._destroyed = false } inherits(Sink, Writable) Sink.prototype._write = function (data, enc, cb) { this.written += data.length if (this._to.push(data)) return cb() this._to._drain = cb } Sink.prototype.destroy = function () { if (this._destroyed) return this._destroyed = true this.emit('close') } var LinkSink = function () { Writable.call(this) this.linkname = '' this._decoder = new StringDecoder('utf-8') this._destroyed = false } inherits(LinkSink, Writable) LinkSink.prototype._write = function (data, enc, cb) { this.linkname += this._decoder.write(data) cb() } LinkSink.prototype.destroy = function () { if (this._destroyed) return this._destroyed = true this.emit('close') } var Void = function () { Writable.call(this) this._destroyed = false } inherits(Void, Writable) Void.prototype._write = function (data, enc, cb) { cb(new Error('No body allowed for this entry')) } Void.prototype.destroy = function () { if (this._destroyed) return this._destroyed = true this.emit('close') } var Pack = function (opts) { if (!(this instanceof Pack)) return new Pack(opts) Readable.call(this, opts) this._drain = noop this._finalized = false this._finalizing = false this._destroyed = false this._stream = null } inherits(Pack, Readable) Pack.prototype.entry = function (header, buffer, callback) { if (this._stream) throw new Error('already piping an entry') if (this._finalized || this._destroyed) return if (typeof buffer === 'function') { callback = buffer buffer = null } if (!callback) callback = noop var self = this if (!header.size || header.type === 'symlink') header.size = 0 if (!header.type) header.type = modeToType(header.mode) if (!header.mode) header.mode = header.type === 'directory' ? DMODE : FMODE if (!header.uid) header.uid = 0 if (!header.gid) header.gid = 0 if (!header.mtime) header.mtime = new Date() if (typeof buffer === 'string') buffer = Buffer.from(buffer) if (Buffer.isBuffer(buffer)) { header.size = buffer.length this._encode(header) var ok = this.push(buffer) overflow(self, header.size) if (ok) process.nextTick(callback) else this._drain = callback return new Void() } if (header.type === 'symlink' && !header.linkname) { var linkSink = new LinkSink() eos(linkSink, function (err) { if (err) { // stream was closed self.destroy() return callback(err) } header.linkname = linkSink.linkname self._encode(header) callback() }) return linkSink } this._encode(header) if (header.type !== 'file' && header.type !== 'contiguous-file') { process.nextTick(callback) return new Void() } var sink = new Sink(this) this._stream = sink eos(sink, function (err) { self._stream = null if (err) { // stream was closed self.destroy() return callback(err) } if (sink.written !== header.size) { // corrupting tar self.destroy() return callback(new Error('size mismatch')) } overflow(self, header.size) if (self._finalizing) self.finalize() callback() }) return sink } Pack.prototype.finalize = function () { if (this._stream) { this._finalizing = true return } if (this._finalized) return this._finalized = true this.push(END_OF_TAR) this.push(null) } Pack.prototype.destroy = function (err) { if (this._destroyed) return this._destroyed = true if (err) this.emit('error', err) this.emit('close') if (this._stream && this._stream.destroy) this._stream.destroy() } Pack.prototype._encode = function (header) { if (!header.pax) { var buf = headers.encode(header) if (buf) { this.push(buf) return } } this._encodePax(header) } Pack.prototype._encodePax = function (header) { var paxHeader = headers.encodePax({ name: header.name, linkname: header.linkname, pax: header.pax }) var newHeader = { name: 'PaxHeader', mode: header.mode, uid: header.uid, gid: header.gid, size: paxHeader.length, mtime: header.mtime, type: 'pax-header', linkname: header.linkname && 'PaxHeader', uname: header.uname, gname: header.gname, devmajor: header.devmajor, devminor: header.devminor } this.push(headers.encode(newHeader)) this.push(paxHeader) overflow(this, paxHeader.length) newHeader.size = header.size newHeader.type = header.type this.push(headers.encode(newHeader)) } Pack.prototype._read = function (n) { var drain = this._drain this._drain = noop drain() } module.exports = Pack /***/ }), /***/ 27540: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const PassThroughDecoder = __webpack_require__(30558) const UTF8Decoder = __webpack_require__(86888) module.exports = class TextDecoder { constructor (encoding = 'utf8') { this.encoding = normalizeEncoding(encoding) switch (this.encoding) { case 'utf8': this.decoder = new UTF8Decoder() break case 'utf16le': case 'base64': throw new Error('Unsupported encoding: ' + this.encoding) default: this.decoder = new PassThroughDecoder(this.encoding) } } get remaining () { return this.decoder.remaining } push (data) { if (typeof data === 'string') return data return this.decoder.decode(data) } // For Node.js compatibility write (data) { return this.push(data) } end (data) { let result = '' if (data) result = this.push(data) result += this.decoder.flush() return result } } function normalizeEncoding (encoding) { encoding = encoding.toLowerCase() switch (encoding) { case 'utf8': case 'utf-8': return 'utf8' case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return 'utf16le' case 'latin1': case 'binary': return 'latin1' case 'base64': case 'ascii': case 'hex': return encoding default: throw new Error('Unknown encoding: ' + encoding) } }; /***/ }), /***/ 30558: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const b4a = __webpack_require__(85792) module.exports = class PassThroughDecoder { constructor (encoding) { this.encoding = encoding } get remaining () { return 0 } decode (tail) { return b4a.toString(tail, this.encoding) } flush () { return '' } } /***/ }), /***/ 86888: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const b4a = __webpack_require__(85792) /** * https://encoding.spec.whatwg.org/#utf-8-decoder */ module.exports = class UTF8Decoder { constructor () { this.codePoint = 0 this.bytesSeen = 0 this.bytesNeeded = 0 this.lowerBoundary = 0x80 this.upperBoundary = 0xbf } get remaining () { return this.bytesSeen } decode (data) { // If we have a fast path, just sniff if the last part is a boundary if (this.bytesNeeded === 0) { let isBoundary = true for (let i = Math.max(0, data.byteLength - 4), n = data.byteLength; i < n && isBoundary; i++) { isBoundary = data[i] <= 0x7f } if (isBoundary) return b4a.toString(data, 'utf8') } let result = '' for (let i = 0, n = data.byteLength; i < n; i++) { const byte = data[i] if (this.bytesNeeded === 0) { if (byte <= 0x7f) { result += String.fromCharCode(byte) } else { this.bytesSeen = 1 if (byte >= 0xc2 && byte <= 0xdf) { this.bytesNeeded = 2 this.codePoint = byte & 0x1f } else if (byte >= 0xe0 && byte <= 0xef) { if (byte === 0xe0) this.lowerBoundary = 0xa0 else if (byte === 0xed) this.upperBoundary = 0x9f this.bytesNeeded = 3 this.codePoint = byte & 0xf } else if (byte >= 0xf0 && byte <= 0xf4) { if (byte === 0xf0) this.lowerBoundary = 0x90 if (byte === 0xf4) this.upperBoundary = 0x8f this.bytesNeeded = 4 this.codePoint = byte & 0x7 } else { result += '\ufffd' } } continue } if (byte < this.lowerBoundary || byte > this.upperBoundary) { this.codePoint = 0 this.bytesNeeded = 0 this.bytesSeen = 0 this.lowerBoundary = 0x80 this.upperBoundary = 0xbf result += '\ufffd' continue } this.lowerBoundary = 0x80 this.upperBoundary = 0xbf this.codePoint = (this.codePoint << 6) | (byte & 0x3f) this.bytesSeen++ if (this.bytesSeen !== this.bytesNeeded) continue result += String.fromCodePoint(this.codePoint) this.codePoint = 0 this.bytesNeeded = 0 this.bytesSeen = 0 } return result } flush () { const result = this.bytesNeeded > 0 ? '\ufffd' : '' this.codePoint = 0 this.bytesNeeded = 0 this.bytesSeen = 0 this.lowerBoundary = 0x80 this.upperBoundary = 0xbf return result } } /***/ }), /***/ 75575: /***/ ((module, exports, __webpack_require__) => { "use strict"; var fs = Object.create(__webpack_require__(57147)) var Promise = __webpack_require__(58259) module.exports = exports = fs for (var key in fs) if (!(typeof fs[key] != 'function' || key.match(/Sync$/) || key.match(/^[A-Z]/) || key.match(/^create/) || key.match(/^(un)?watch/) )) add(key) function add(key) { var original = fs[key] if (key !== 'exists') fs[key] = Promise.denodeify(original) else fs[key] = function() { var args = [].slice.call(arguments) return new Promise(function(resolve, reject) { args.push(resolve) original.apply(null, args) }) } } /***/ }), /***/ 35940: /***/ ((module) => { var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; /***/ }), /***/ 45867: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from // Writable. /**/ var pna = __webpack_require__(88212); /**/ /**/ var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { keys.push(key); }return keys; }; /**/ module.exports = Duplex; /**/ var util = Object.create(__webpack_require__(16497)); util.inherits = __webpack_require__(94378); /**/ var Readable = __webpack_require__(44278); var Writable = __webpack_require__(10759); util.inherits(Duplex, Readable); { // avoid scope creep, the keys array can then be collected var keys = objectKeys(Writable.prototype); for (var v = 0; v < keys.length; v++) { var method = keys[v]; if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } } function Duplex(options) { if (!(this instanceof Duplex)) return new Duplex(options); Readable.call(this, options); Writable.call(this, options); if (options && options.readable === false) this.readable = false; if (options && options.writable === false) this.writable = false; this.allowHalfOpen = true; if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; this.once('end', onend); } Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function () { return this._writableState.highWaterMark; } }); // the no-half-open enforcer function onend() { // if we allow half-open state, or if the writable side ended, // then we're ok. if (this.allowHalfOpen || this._writableState.ended) return; // no more data can be written. // But allow more writes to happen in this tick. pna.nextTick(onEndNT, this); } function onEndNT(self) { self.end(); } Object.defineProperty(Duplex.prototype, 'destroyed', { get: function () { if (this._readableState === undefined || this._writableState === undefined) { return false; } return this._readableState.destroyed && this._writableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (this._readableState === undefined || this._writableState === undefined) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; this._writableState.destroyed = value; } }); Duplex.prototype._destroy = function (err, cb) { this.push(null); this.end(); pna.nextTick(cb, err); }; /***/ }), /***/ 3431: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. module.exports = PassThrough; var Transform = __webpack_require__(60062); /**/ var util = Object.create(__webpack_require__(16497)); util.inherits = __webpack_require__(94378); /**/ util.inherits(PassThrough, Transform); function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options); Transform.call(this, options); } PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; /***/ }), /***/ 44278: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /**/ var pna = __webpack_require__(88212); /**/ module.exports = Readable; /**/ var isArray = __webpack_require__(35940); /**/ /**/ var Duplex; /**/ Readable.ReadableState = ReadableState; /**/ var EE = __webpack_require__(82361).EventEmitter; var EElistenerCount = function (emitter, type) { return emitter.listeners(type).length; }; /**/ /**/ var Stream = __webpack_require__(95829); /**/ /**/ var Buffer = __webpack_require__(89509).Buffer; var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } /**/ /**/ var util = Object.create(__webpack_require__(16497)); util.inherits = __webpack_require__(94378); /**/ /**/ var debugUtil = __webpack_require__(73837); var debug = void 0; if (debugUtil && debugUtil.debuglog) { debug = debugUtil.debuglog('stream'); } else { debug = function () {}; } /**/ var BufferList = __webpack_require__(93912); var destroyImpl = __webpack_require__(55513); var StringDecoder; util.inherits(Readable, Stream); var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; function prependListener(emitter, event, fn) { // Sadly this is not cacheable as some libraries bundle their own // event emitter implementation with them. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any // userland ones. NEVER DO THIS. This is here only because this code needs // to continue to work with older versions of Node.js that do not include // the prependListener() method. The goal is to eventually remove this hack. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; } function ReadableState(options, stream) { Duplex = Duplex || __webpack_require__(45867); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. var isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to // make all the buffer merging and length checks go away this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer // Note: 0 is a valid value, means "don't call _read preemptively ever" var hwm = options.highWaterMark; var readableHwm = options.readableHighWaterMark; var defaultHwm = this.objectMode ? 16 : 16 * 1024; if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; // cast to ints. this.highWaterMark = Math.floor(this.highWaterMark); // A linked list is used to store data chunks instead of an array because the // linked list can remove elements from the beginning faster than // array.shift() this.buffer = new BufferList(); this.length = 0; this.pipes = null; this.pipesCount = 0; this.flowing = null; this.ended = false; this.endEmitted = false; this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted // immediately, or on a later tick. We set this to true at first, because // any actions that shouldn't happen until "later" should generally also // not happen before the first read call. this.sync = true; // whenever we return null, then we set a flag to say // that we're awaiting a 'readable' event emission. this.needReadable = false; this.emittedReadable = false; this.readableListening = false; this.resumeScheduled = false; // has it been destroyed this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled this.readingMore = false; this.decoder = null; this.encoding = null; if (options.encoding) { if (!StringDecoder) StringDecoder = __webpack_require__(47989)/* .StringDecoder */ .s; this.decoder = new StringDecoder(options.encoding); this.encoding = options.encoding; } } function Readable(options) { Duplex = Duplex || __webpack_require__(45867); if (!(this instanceof Readable)) return new Readable(options); this._readableState = new ReadableState(options, this); // legacy this.readable = true; if (options) { if (typeof options.read === 'function') this._read = options.read; if (typeof options.destroy === 'function') this._destroy = options.destroy; } Stream.call(this); } Object.defineProperty(Readable.prototype, 'destroyed', { get: function () { if (this._readableState === undefined) { return false; } return this._readableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (!this._readableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; } }); Readable.prototype.destroy = destroyImpl.destroy; Readable.prototype._undestroy = destroyImpl.undestroy; Readable.prototype._destroy = function (err, cb) { this.push(null); cb(err); }; // Manually shove something into the read() buffer. // This returns true if the highWaterMark has not been hit yet, // similar to how Writable.write() returns true if you should // write() some more. Readable.prototype.push = function (chunk, encoding) { var state = this._readableState; var skipChunkCheck; if (!state.objectMode) { if (typeof chunk === 'string') { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { chunk = Buffer.from(chunk, encoding); encoding = ''; } skipChunkCheck = true; } } else { skipChunkCheck = true; } return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); }; // Unshift should *always* be something directly out of read() Readable.prototype.unshift = function (chunk) { return readableAddChunk(this, chunk, null, true, false); }; function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { var state = stream._readableState; if (chunk === null) { state.reading = false; onEofChunk(stream, state); } else { var er; if (!skipChunkCheck) er = chunkInvalid(state, chunk); if (er) { stream.emit('error', er); } else if (state.objectMode || chunk && chunk.length > 0) { if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { chunk = _uint8ArrayToBuffer(chunk); } if (addToFront) { if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); } else if (state.ended) { stream.emit('error', new Error('stream.push() after EOF')); } else { state.reading = false; if (state.decoder && !encoding) { chunk = state.decoder.write(chunk); if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); } else { addChunk(stream, state, chunk, false); } } } else if (!addToFront) { state.reading = false; } } return needMoreData(state); } function addChunk(stream, state, chunk, addToFront) { if (state.flowing && state.length === 0 && !state.sync) { stream.emit('data', chunk); stream.read(0); } else { // update the buffer info. state.length += state.objectMode ? 1 : chunk.length; if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); if (state.needReadable) emitReadable(stream); } maybeReadMore(stream, state); } function chunkInvalid(state, chunk) { var er; if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } return er; } // if it's past the high water mark, we can push in some more. // Also, if we have no data yet, we can stand some // more bytes. This is to work around cases where hwm=0, // such as the repl. Also, if the push() triggered a // readable event, and the user called read(largeNumber) such that // needReadable was set, then we ought to push more, so that another // 'readable' event will be triggered. function needMoreData(state) { return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); } Readable.prototype.isPaused = function () { return this._readableState.flowing === false; }; // backwards compatibility. Readable.prototype.setEncoding = function (enc) { if (!StringDecoder) StringDecoder = __webpack_require__(47989)/* .StringDecoder */ .s; this._readableState.decoder = new StringDecoder(enc); this._readableState.encoding = enc; return this; }; // Don't raise the hwm > 8MB var MAX_HWM = 0x800000; function computeNewHighWaterMark(n) { if (n >= MAX_HWM) { n = MAX_HWM; } else { // Get the next highest power of 2 to prevent increasing hwm excessively in // tiny amounts n--; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; n++; } return n; } // This function is designed to be inlinable, so please take care when making // changes to the function body. function howMuchToRead(n, state) { if (n <= 0 || state.length === 0 && state.ended) return 0; if (state.objectMode) return 1; if (n !== n) { // Only flow one buffer at a time if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; } // If we're asking for more than the current hwm, then raise the hwm. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); if (n <= state.length) return n; // Don't have enough if (!state.ended) { state.needReadable = true; return 0; } return state.length; } // you can override either this method, or the async _read(n) below. Readable.prototype.read = function (n) { debug('read', n); n = parseInt(n, 10); var state = this._readableState; var nOrig = n; if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we // already have a bunch of data in the buffer, then just trigger // the 'readable' event and move on. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { debug('read: emitReadable', state.length, state.ended); if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); return null; } n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. if (n === 0 && state.ended) { if (state.length === 0) endReadable(this); return null; } // All the actual chunk generation logic needs to be // *below* the call to _read. The reason is that in certain // synthetic stream cases, such as passthrough streams, _read // may be a completely synchronous operation which may change // the state of the read buffer, providing enough data when // before there was *not* enough. // // So, the steps are: // 1. Figure out what the state of things will be after we do // a read from the buffer. // // 2. If that resulting state will trigger a _read, then call _read. // Note that this may be asynchronous, or synchronous. Yes, it is // deeply ugly to write APIs this way, but that still doesn't mean // that the Readable class should behave improperly, as streams are // designed to be sync/async agnostic. // Take note if the _read call is sync or async (ie, if the read call // has returned yet), so that we know whether or not it's safe to emit // 'readable' etc. // // 3. Actually pull the requested chunks out of the buffer and return. // if we need a readable event, then we need to do some reading. var doRead = state.needReadable; debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; debug('length less than watermark', doRead); } // however, if we've ended, then there's no point, and if we're already // reading, then it's unnecessary. if (state.ended || state.reading) { doRead = false; debug('reading or ended', doRead); } else if (doRead) { debug('do read'); state.reading = true; state.sync = true; // if the length is currently zero, then we *need* a readable event. if (state.length === 0) state.needReadable = true; // call internal read method this._read(state.highWaterMark); state.sync = false; // If _read pushed data synchronously, then `reading` will be false, // and we need to re-evaluate how much data we can return to the user. if (!state.reading) n = howMuchToRead(nOrig, state); } var ret; if (n > 0) ret = fromList(n, state);else ret = null; if (ret === null) { state.needReadable = true; n = 0; } else { state.length -= n; } if (state.length === 0) { // If we have nothing in the buffer, then we want to know // as soon as we *do* get something into the buffer. if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. if (nOrig !== n && state.ended) endReadable(this); } if (ret !== null) this.emit('data', ret); return ret; }; function onEofChunk(stream, state) { if (state.ended) return; if (state.decoder) { var chunk = state.decoder.end(); if (chunk && chunk.length) { state.buffer.push(chunk); state.length += state.objectMode ? 1 : chunk.length; } } state.ended = true; // emit 'readable' now to make sure it gets picked up. emitReadable(stream); } // Don't emit readable right away in sync mode, because this can trigger // another read() call => stack overflow. This way, it might trigger // a nextTick recursion warning, but that's not so bad. function emitReadable(stream) { var state = stream._readableState; state.needReadable = false; if (!state.emittedReadable) { debug('emitReadable', state.flowing); state.emittedReadable = true; if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); } } function emitReadable_(stream) { debug('emit readable'); stream.emit('readable'); flow(stream); } // at this point, the user has presumably seen the 'readable' event, // and called read() to consume some data. that may have triggered // in turn another _read(n) call, in which case reading = true if // it's in progress. // However, if we're not ended, or reading, and the length < hwm, // then go ahead and try to read some more preemptively. function maybeReadMore(stream, state) { if (!state.readingMore) { state.readingMore = true; pna.nextTick(maybeReadMore_, stream, state); } } function maybeReadMore_(stream, state) { var len = state.length; while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { debug('maybeReadMore read 0'); stream.read(0); if (len === state.length) // didn't get any data, stop spinning. break;else len = state.length; } state.readingMore = false; } // abstract method. to be overridden in specific implementation classes. // call cb(er, data) where data is <= n in length. // for virtual (non-string, non-buffer) streams, "length" is somewhat // arbitrary, and perhaps not very meaningful. Readable.prototype._read = function (n) { this.emit('error', new Error('_read() is not implemented')); }; Readable.prototype.pipe = function (dest, pipeOpts) { var src = this; var state = this._readableState; switch (state.pipesCount) { case 0: state.pipes = dest; break; case 1: state.pipes = [state.pipes, dest]; break; default: state.pipes.push(dest); break; } state.pipesCount += 1; debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; var endFn = doEnd ? onend : unpipe; if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); dest.on('unpipe', onunpipe); function onunpipe(readable, unpipeInfo) { debug('onunpipe'); if (readable === src) { if (unpipeInfo && unpipeInfo.hasUnpiped === false) { unpipeInfo.hasUnpiped = true; cleanup(); } } } function onend() { debug('onend'); dest.end(); } // when the dest drains, it reduces the awaitDrain counter // on the source. This would be more elegant with a .once() // handler in flow(), but adding and removing repeatedly is // too slow. var ondrain = pipeOnDrain(src); dest.on('drain', ondrain); var cleanedUp = false; function cleanup() { debug('cleanup'); // cleanup event handlers once the pipe is broken dest.removeListener('close', onclose); dest.removeListener('finish', onfinish); dest.removeListener('drain', ondrain); dest.removeListener('error', onerror); dest.removeListener('unpipe', onunpipe); src.removeListener('end', onend); src.removeListener('end', unpipe); src.removeListener('data', ondata); cleanedUp = true; // if the reader is waiting for a drain event from this // specific writer, then it would cause it to never start // flowing again. // So, if this is awaiting a drain, then we just call it now. // If we don't know, then assume that we are waiting for one. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } // If the user pushes more data while we're writing to dest then we'll end up // in ondata again. However, we only want to increase awaitDrain once because // dest will only emit one 'drain' event for the multiple writes. // => Introduce a guard on increasing awaitDrain. var increasedAwaitDrain = false; src.on('data', ondata); function ondata(chunk) { debug('ondata'); increasedAwaitDrain = false; var ret = dest.write(chunk); if (false === ret && !increasedAwaitDrain) { // If the user unpiped during `dest.write()`, it is possible // to get stuck in a permanently paused state if that write // also returned false. // => Check whether `dest` is still a piping destination. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { debug('false write response, pause', state.awaitDrain); state.awaitDrain++; increasedAwaitDrain = true; } src.pause(); } } // if the dest has an error, then stop piping into it. // however, don't suppress the throwing behavior for this. function onerror(er) { debug('onerror', er); unpipe(); dest.removeListener('error', onerror); if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); } // Make sure our error handler is attached before userland ones. prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. function onclose() { dest.removeListener('finish', onfinish); unpipe(); } dest.once('close', onclose); function onfinish() { debug('onfinish'); dest.removeListener('close', onclose); unpipe(); } dest.once('finish', onfinish); function unpipe() { debug('unpipe'); src.unpipe(dest); } // tell the dest that it's being piped to dest.emit('pipe', src); // start the flow if it hasn't been started already. if (!state.flowing) { debug('pipe resume'); src.resume(); } return dest; }; function pipeOnDrain(src) { return function () { var state = src._readableState; debug('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { state.flowing = true; flow(src); } }; } Readable.prototype.unpipe = function (dest) { var state = this._readableState; var unpipeInfo = { hasUnpiped: false }; // if we're not piping anywhere, then do nothing. if (state.pipesCount === 0) return this; // just one destination. most common case. if (state.pipesCount === 1) { // passed in one, but it's not the right one. if (dest && dest !== state.pipes) return this; if (!dest) dest = state.pipes; // got a match. state.pipes = null; state.pipesCount = 0; state.flowing = false; if (dest) dest.emit('unpipe', this, unpipeInfo); return this; } // slow case. multiple pipe destinations. if (!dest) { // remove all. var dests = state.pipes; var len = state.pipesCount; state.pipes = null; state.pipesCount = 0; state.flowing = false; for (var i = 0; i < len; i++) { dests[i].emit('unpipe', this, { hasUnpiped: false }); }return this; } // try to find the right one. var index = indexOf(state.pipes, dest); if (index === -1) return this; state.pipes.splice(index, 1); state.pipesCount -= 1; if (state.pipesCount === 1) state.pipes = state.pipes[0]; dest.emit('unpipe', this, unpipeInfo); return this; }; // set up data events if they are asked for // Ensure readable listeners eventually get something Readable.prototype.on = function (ev, fn) { var res = Stream.prototype.on.call(this, ev, fn); if (ev === 'data') { // Start flowing on next tick if stream isn't explicitly paused if (this._readableState.flowing !== false) this.resume(); } else if (ev === 'readable') { var state = this._readableState; if (!state.endEmitted && !state.readableListening) { state.readableListening = state.needReadable = true; state.emittedReadable = false; if (!state.reading) { pna.nextTick(nReadingNextTick, this); } else if (state.length) { emitReadable(this); } } } return res; }; Readable.prototype.addListener = Readable.prototype.on; function nReadingNextTick(self) { debug('readable nexttick read 0'); self.read(0); } // pause() and resume() are remnants of the legacy readable stream API // If the user uses them, then switch into old mode. Readable.prototype.resume = function () { var state = this._readableState; if (!state.flowing) { debug('resume'); state.flowing = true; resume(this, state); } return this; }; function resume(stream, state) { if (!state.resumeScheduled) { state.resumeScheduled = true; pna.nextTick(resume_, stream, state); } } function resume_(stream, state) { if (!state.reading) { debug('resume read 0'); stream.read(0); } state.resumeScheduled = false; state.awaitDrain = 0; stream.emit('resume'); flow(stream); if (state.flowing && !state.reading) stream.read(0); } Readable.prototype.pause = function () { debug('call pause flowing=%j', this._readableState.flowing); if (false !== this._readableState.flowing) { debug('pause'); this._readableState.flowing = false; this.emit('pause'); } return this; }; function flow(stream) { var state = stream._readableState; debug('flow', state.flowing); while (state.flowing && stream.read() !== null) {} } // wrap an old-style stream as the async data source. // This is *not* part of the readable stream interface. // It is an ugly unfortunate mess of history. Readable.prototype.wrap = function (stream) { var _this = this; var state = this._readableState; var paused = false; stream.on('end', function () { debug('wrapped end'); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) _this.push(chunk); } _this.push(null); }); stream.on('data', function (chunk) { debug('wrapped data'); if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; var ret = _this.push(chunk); if (!ret) { paused = true; stream.pause(); } }); // proxy all the other methods. // important when wrapping filters and duplexes. for (var i in stream) { if (this[i] === undefined && typeof stream[i] === 'function') { this[i] = function (method) { return function () { return stream[method].apply(stream, arguments); }; }(i); } } // proxy certain important events. for (var n = 0; n < kProxyEvents.length; n++) { stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); } // when we try to consume some more bytes, simply unpause the // underlying stream. this._read = function (n) { debug('wrapped _read', n); if (paused) { paused = false; stream.resume(); } }; return this; }; Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function () { return this._readableState.highWaterMark; } }); // exposed for testing purposes only. Readable._fromList = fromList; // Pluck off n bytes from an array of buffers. // Length is the combined lengths of all the buffers in the list. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromList(n, state) { // nothing buffered if (state.length === 0) return null; var ret; if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { // read it all, truncate the list if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); state.buffer.clear(); } else { // read part of list ret = fromListPartial(n, state.buffer, state.decoder); } return ret; } // Extracts only enough buffered data to satisfy the amount requested. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromListPartial(n, list, hasStrings) { var ret; if (n < list.head.data.length) { // slice is the same for buffers and strings ret = list.head.data.slice(0, n); list.head.data = list.head.data.slice(n); } else if (n === list.head.data.length) { // first chunk is a perfect match ret = list.shift(); } else { // result spans more than one buffer ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); } return ret; } // Copies a specified amount of characters from the list of buffered data // chunks. // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBufferString(n, list) { var p = list.head; var c = 1; var ret = p.data; n -= ret.length; while (p = p.next) { var str = p.data; var nb = n > str.length ? str.length : n; if (nb === str.length) ret += str;else ret += str.slice(0, n); n -= nb; if (n === 0) { if (nb === str.length) { ++c; if (p.next) list.head = p.next;else list.head = list.tail = null; } else { list.head = p; p.data = str.slice(nb); } break; } ++c; } list.length -= c; return ret; } // Copies a specified amount of bytes from the list of buffered data chunks. // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBuffer(n, list) { var ret = Buffer.allocUnsafe(n); var p = list.head; var c = 1; p.data.copy(ret); n -= p.data.length; while (p = p.next) { var buf = p.data; var nb = n > buf.length ? buf.length : n; buf.copy(ret, ret.length - n, 0, nb); n -= nb; if (n === 0) { if (nb === buf.length) { ++c; if (p.next) list.head = p.next;else list.head = list.tail = null; } else { list.head = p; p.data = buf.slice(nb); } break; } ++c; } list.length -= c; return ret; } function endReadable(stream) { var state = stream._readableState; // If we get here before consuming all the bytes, then that is a // bug in node. Should never happen. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); if (!state.endEmitted) { state.ended = true; pna.nextTick(endReadableNT, state, stream); } } function endReadableNT(state, stream) { // Check that we didn't get one last unshift. if (!state.endEmitted && state.length === 0) { state.endEmitted = true; stream.readable = false; stream.emit('end'); } } function indexOf(xs, x) { for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) return i; } return -1; } /***/ }), /***/ 60062: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where // some bits pass through, and others are simply ignored. (That would // be a valid example of a transform, of course.) // // While the output is causally related to the input, it's not a // necessarily symmetric or synchronous transformation. For example, // a zlib stream might take multiple plain-text writes(), and then // emit a single compressed chunk some time in the future. // // Here's how this works: // // The Transform stream has all the aspects of the readable and writable // stream classes. When you write(chunk), that calls _write(chunk,cb) // internally, and returns false if there's a lot of pending writes // buffered up. When you call read(), that calls _read(n) until // there's enough pending readable data buffered up. // // In a transform stream, the written data is placed in a buffer. When // _read(n) is called, it transforms the queued up data, calling the // buffered _write cb's as it consumes chunks. If consuming a single // written chunk would result in multiple output chunks, then the first // outputted bit calls the readcb, and subsequent chunks just go into // the read buffer, and will cause it to emit 'readable' if necessary. // // This way, back-pressure is actually determined by the reading side, // since _read has to be called to start processing a new chunk. However, // a pathological inflate type of transform can cause excessive buffering // here. For example, imagine a stream where every byte of input is // interpreted as an integer from 0-255, and then results in that many // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in // 1kb of data being output. In this case, you could write a very small // amount of input, and end up with a very large amount of output. In // such a pathological inflating mechanism, there'd be no way to tell // the system to stop doing the transform. A single 4MB write could // cause the system to run out of memory. // // However, even in such a pathological case, only a single written chunk // would be consumed, and then the rest would wait (un-transformed) until // the results of the previous transformed chunk were consumed. module.exports = Transform; var Duplex = __webpack_require__(45867); /**/ var util = Object.create(__webpack_require__(16497)); util.inherits = __webpack_require__(94378); /**/ util.inherits(Transform, Duplex); function afterTransform(er, data) { var ts = this._transformState; ts.transforming = false; var cb = ts.writecb; if (!cb) { return this.emit('error', new Error('write callback called multiple times')); } ts.writechunk = null; ts.writecb = null; if (data != null) // single equals check for both `null` and `undefined` this.push(data); cb(er); var rs = this._readableState; rs.reading = false; if (rs.needReadable || rs.length < rs.highWaterMark) { this._read(rs.highWaterMark); } } function Transform(options) { if (!(this instanceof Transform)) return new Transform(options); Duplex.call(this, options); this._transformState = { afterTransform: afterTransform.bind(this), needTransform: false, transforming: false, writecb: null, writechunk: null, writeencoding: null }; // start out asking for a readable event once data is transformed. this._readableState.needReadable = true; // we have implemented the _read method, and done the other things // that Readable wants before the first _read call, so unset the // sync guard flag. this._readableState.sync = false; if (options) { if (typeof options.transform === 'function') this._transform = options.transform; if (typeof options.flush === 'function') this._flush = options.flush; } // When the writable side finishes, then flush out anything remaining. this.on('prefinish', prefinish); } function prefinish() { var _this = this; if (typeof this._flush === 'function') { this._flush(function (er, data) { done(_this, er, data); }); } else { done(this, null, null); } } Transform.prototype.push = function (chunk, encoding) { this._transformState.needTransform = false; return Duplex.prototype.push.call(this, chunk, encoding); }; // This is the part where you do stuff! // override this function in implementation classes. // 'chunk' is an input chunk. // // Call `push(newChunk)` to pass along transformed output // to the readable side. You may call 'push' zero or more times. // // Call `cb(err)` when you are done with this chunk. If you pass // an error, then that'll put the hurt on the whole operation. If you // never call cb(), then you'll never get another chunk. Transform.prototype._transform = function (chunk, encoding, cb) { throw new Error('_transform() is not implemented'); }; Transform.prototype._write = function (chunk, encoding, cb) { var ts = this._transformState; ts.writecb = cb; ts.writechunk = chunk; ts.writeencoding = encoding; if (!ts.transforming) { var rs = this._readableState; if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } }; // Doesn't matter what the args are here. // _transform does all the work. // That we got here means that the readable side wants more data. Transform.prototype._read = function (n) { var ts = this._transformState; if (ts.writechunk !== null && ts.writecb && !ts.transforming) { ts.transforming = true; this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { // mark that we need a transform, so that any data that comes in // will get processed, now that we've asked for it. ts.needTransform = true; } }; Transform.prototype._destroy = function (err, cb) { var _this2 = this; Duplex.prototype._destroy.call(this, err, function (err2) { cb(err2); _this2.emit('close'); }); }; function done(stream, er, data) { if (er) return stream.emit('error', er); if (data != null) // single equals check for both `null` and `undefined` stream.push(data); // if there's nothing in the write buffer, then that means // that nothing more will ever be provided if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); return stream.push(null); } /***/ }), /***/ 10759: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // A bit simpler than readable streams. // Implement an async ._write(chunk, encoding, cb), and it'll handle all // the drain event emission and buffering. /**/ var pna = __webpack_require__(88212); /**/ module.exports = Writable; /* */ function WriteReq(chunk, encoding, cb) { this.chunk = chunk; this.encoding = encoding; this.callback = cb; this.next = null; } // It seems a linked list but it is not // there will be only 2 of these for each stream function CorkedRequest(state) { var _this = this; this.next = null; this.entry = null; this.finish = function () { onCorkedFinish(_this, state); }; } /* */ /**/ var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; /**/ /**/ var Duplex; /**/ Writable.WritableState = WritableState; /**/ var util = Object.create(__webpack_require__(16497)); util.inherits = __webpack_require__(94378); /**/ /**/ var internalUtil = { deprecate: __webpack_require__(41159) }; /**/ /**/ var Stream = __webpack_require__(95829); /**/ /**/ var Buffer = __webpack_require__(89509).Buffer; var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } /**/ var destroyImpl = __webpack_require__(55513); util.inherits(Writable, Stream); function nop() {} function WritableState(options, stream) { Duplex = Duplex || __webpack_require__(45867); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. var isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream // contains buffers or objects. this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false // Note: 0 is a valid value, means that we always return false if // the entire buffer is not flushed immediately on write() var hwm = options.highWaterMark; var writableHwm = options.writableHighWaterMark; var defaultHwm = this.objectMode ? 16 : 16 * 1024; if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; // cast to ints. this.highWaterMark = Math.floor(this.highWaterMark); // if _final has been called this.finalCalled = false; // drain event flag. this.needDrain = false; // at the start of calling end() this.ending = false; // when end() has been called, and returned this.ended = false; // when 'finish' is emitted this.finished = false; // has it been destroyed this.destroyed = false; // should we decode strings into buffers before passing to _write? // this is here so that some node-core streams can optimize string // handling at a lower level. var noDecode = options.decodeStrings === false; this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement // of how much we're waiting to get pushed to some underlying // socket or file. this.length = 0; // a flag to see when we're in the middle of a write. this.writing = false; // when true all writes will be buffered until .uncork() call this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, because any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. this.sync = true; // a flag to know if we're processing previously buffered items, which // may call the _write() callback in the same tick, so that we don't // end up in an overlapped onwrite situation. this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) this.onwrite = function (er) { onwrite(stream, er); }; // the callback that the user supplies to write(chunk,encoding,cb) this.writecb = null; // the amount that is being written when _write is called. this.writelen = 0; this.bufferedRequest = null; this.lastBufferedRequest = null; // number of pending user-supplied write callbacks // this must be 0 before 'finish' can be emitted this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs // This is relevant for synchronous Transform streams this.prefinished = false; // True if the error was already emitted and should not be thrown again this.errorEmitted = false; // count buffered requests this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always // one allocated and free to use, and we maintain at most two this.corkedRequestsFree = new CorkedRequest(this); } WritableState.prototype.getBuffer = function getBuffer() { var current = this.bufferedRequest; var out = []; while (current) { out.push(current); current = current.next; } return out; }; (function () { try { Object.defineProperty(WritableState.prototype, 'buffer', { get: internalUtil.deprecate(function () { return this.getBuffer(); }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') }); } catch (_) {} })(); // Test _writableState for inheritance to account for Duplex streams, // whose prototype chain only points to Readable. var realHasInstance; if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { realHasInstance = Function.prototype[Symbol.hasInstance]; Object.defineProperty(Writable, Symbol.hasInstance, { value: function (object) { if (realHasInstance.call(this, object)) return true; if (this !== Writable) return false; return object && object._writableState instanceof WritableState; } }); } else { realHasInstance = function (object) { return object instanceof this; }; } function Writable(options) { Duplex = Duplex || __webpack_require__(45867); // Writable ctor is applied to Duplexes, too. // `realHasInstance` is necessary because using plain `instanceof` // would return false, as no `_writableState` property is attached. // Trying to use the custom `instanceof` for Writable here will also break the // Node.js LazyTransform implementation, which has a non-trivial getter for // `_writableState` that would lead to infinite recursion. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { return new Writable(options); } this._writableState = new WritableState(options, this); // legacy. this.writable = true; if (options) { if (typeof options.write === 'function') this._write = options.write; if (typeof options.writev === 'function') this._writev = options.writev; if (typeof options.destroy === 'function') this._destroy = options.destroy; if (typeof options.final === 'function') this._final = options.final; } Stream.call(this); } // Otherwise people can pipe Writable streams, which is just wrong. Writable.prototype.pipe = function () { this.emit('error', new Error('Cannot pipe, not readable')); }; function writeAfterEnd(stream, cb) { var er = new Error('write after end'); // TODO: defer error events consistently everywhere, not just the cb stream.emit('error', er); pna.nextTick(cb, er); } // Checks that a user-supplied chunk is valid, especially for the particular // mode the stream is in. Currently this means that `null` is never accepted // and undefined/non-string values are only allowed in object mode. function validChunk(stream, state, chunk, cb) { var valid = true; var er = false; if (chunk === null) { er = new TypeError('May not write null values to stream'); } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } if (er) { stream.emit('error', er); pna.nextTick(cb, er); valid = false; } return valid; } Writable.prototype.write = function (chunk, encoding, cb) { var state = this._writableState; var ret = false; var isBuf = !state.objectMode && _isUint8Array(chunk); if (isBuf && !Buffer.isBuffer(chunk)) { chunk = _uint8ArrayToBuffer(chunk); } if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; if (typeof cb !== 'function') cb = nop; if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { state.pendingcb++; ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); } return ret; }; Writable.prototype.cork = function () { var state = this._writableState; state.corked++; }; Writable.prototype.uncork = function () { var state = this._writableState; if (state.corked) { state.corked--; if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); } }; Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { // node::ParseEncoding() requires lower case. if (typeof encoding === 'string') encoding = encoding.toLowerCase(); if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); this._writableState.defaultEncoding = encoding; return this; }; function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { chunk = Buffer.from(chunk, encoding); } return chunk; } Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function () { return this._writableState.highWaterMark; } }); // if we're already writing something, then just put this // in the queue, and wait our turn. Otherwise, call _write // If we return false, then we need a drain event, so set that flag. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { if (!isBuf) { var newChunk = decodeChunk(state, chunk, encoding); if (chunk !== newChunk) { isBuf = true; encoding = 'buffer'; chunk = newChunk; } } var len = state.objectMode ? 1 : chunk.length; state.length += len; var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. if (!ret) state.needDrain = true; if (state.writing || state.corked) { var last = state.lastBufferedRequest; state.lastBufferedRequest = { chunk: chunk, encoding: encoding, isBuf: isBuf, callback: cb, next: null }; if (last) { last.next = state.lastBufferedRequest; } else { state.bufferedRequest = state.lastBufferedRequest; } state.bufferedRequestCount += 1; } else { doWrite(stream, state, false, len, chunk, encoding, cb); } return ret; } function doWrite(stream, state, writev, len, chunk, encoding, cb) { state.writelen = len; state.writecb = cb; state.writing = true; state.sync = true; if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); state.sync = false; } function onwriteError(stream, state, sync, er, cb) { --state.pendingcb; if (sync) { // defer the callback if we are being called synchronously // to avoid piling up things on the stack pna.nextTick(cb, er); // this can emit finish, and it will always happen // after error pna.nextTick(finishMaybe, stream, state); stream._writableState.errorEmitted = true; stream.emit('error', er); } else { // the caller expect this to happen before if // it is async cb(er); stream._writableState.errorEmitted = true; stream.emit('error', er); // this can emit finish, but finish must // always follow error finishMaybe(stream, state); } } function onwriteStateUpdate(state) { state.writing = false; state.writecb = null; state.length -= state.writelen; state.writelen = 0; } function onwrite(stream, er) { var state = stream._writableState; var sync = state.sync; var cb = state.writecb; onwriteStateUpdate(state); if (er) onwriteError(stream, state, sync, er, cb);else { // Check if we're actually ready to finish, but don't emit yet var finished = needFinish(state); if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { clearBuffer(stream, state); } if (sync) { /**/ asyncWrite(afterWrite, stream, state, finished, cb); /**/ } else { afterWrite(stream, state, finished, cb); } } } function afterWrite(stream, state, finished, cb) { if (!finished) onwriteDrain(stream, state); state.pendingcb--; cb(); finishMaybe(stream, state); } // Must force callback to be called on nextTick, so that we don't // emit 'drain' before the write() consumer gets the 'false' return // value, and has a chance to attach a 'drain' listener. function onwriteDrain(stream, state) { if (state.length === 0 && state.needDrain) { state.needDrain = false; stream.emit('drain'); } } // if there's something in the buffer waiting, then process it function clearBuffer(stream, state) { state.bufferProcessing = true; var entry = state.bufferedRequest; if (stream._writev && entry && entry.next) { // Fast case, write everything using _writev() var l = state.bufferedRequestCount; var buffer = new Array(l); var holder = state.corkedRequestsFree; holder.entry = entry; var count = 0; var allBuffers = true; while (entry) { buffer[count] = entry; if (!entry.isBuf) allBuffers = false; entry = entry.next; count += 1; } buffer.allBuffers = allBuffers; doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time // as the hot path ends with doWrite state.pendingcb++; state.lastBufferedRequest = null; if (holder.next) { state.corkedRequestsFree = holder.next; holder.next = null; } else { state.corkedRequestsFree = new CorkedRequest(state); } state.bufferedRequestCount = 0; } else { // Slow case, write chunks one-by-one while (entry) { var chunk = entry.chunk; var encoding = entry.encoding; var cb = entry.callback; var len = state.objectMode ? 1 : chunk.length; doWrite(stream, state, false, len, chunk, encoding, cb); entry = entry.next; state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then // it means that we need to wait until it does. // also, that means that the chunk and cb are currently // being processed, so move the buffer counter past them. if (state.writing) { break; } } if (entry === null) state.lastBufferedRequest = null; } state.bufferedRequest = entry; state.bufferProcessing = false; } Writable.prototype._write = function (chunk, encoding, cb) { cb(new Error('_write() is not implemented')); }; Writable.prototype._writev = null; Writable.prototype.end = function (chunk, encoding, cb) { var state = this._writableState; if (typeof chunk === 'function') { cb = chunk; chunk = null; encoding = null; } else if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks if (state.corked) { state.corked = 1; this.uncork(); } // ignore unnecessary end() calls. if (!state.ending) endWritable(this, state, cb); }; function needFinish(state) { return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; } function callFinal(stream, state) { stream._final(function (err) { state.pendingcb--; if (err) { stream.emit('error', err); } state.prefinished = true; stream.emit('prefinish'); finishMaybe(stream, state); }); } function prefinish(stream, state) { if (!state.prefinished && !state.finalCalled) { if (typeof stream._final === 'function') { state.pendingcb++; state.finalCalled = true; pna.nextTick(callFinal, stream, state); } else { state.prefinished = true; stream.emit('prefinish'); } } } function finishMaybe(stream, state) { var need = needFinish(state); if (need) { prefinish(stream, state); if (state.pendingcb === 0) { state.finished = true; stream.emit('finish'); } } return need; } function endWritable(stream, state, cb) { state.ending = true; finishMaybe(stream, state); if (cb) { if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); } state.ended = true; stream.writable = false; } function onCorkedFinish(corkReq, state, err) { var entry = corkReq.entry; corkReq.entry = null; while (entry) { var cb = entry.callback; state.pendingcb--; cb(err); entry = entry.next; } // reuse the free corkReq. state.corkedRequestsFree.next = corkReq; } Object.defineProperty(Writable.prototype, 'destroyed', { get: function () { if (this._writableState === undefined) { return false; } return this._writableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (!this._writableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._writableState.destroyed = value; } }); Writable.prototype.destroy = destroyImpl.destroy; Writable.prototype._undestroy = destroyImpl.undestroy; Writable.prototype._destroy = function (err, cb) { this.end(); cb(err); }; /***/ }), /***/ 93912: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Buffer = __webpack_require__(89509).Buffer; var util = __webpack_require__(73837); function copyBuffer(src, target, offset) { src.copy(target, offset); } module.exports = function () { function BufferList() { _classCallCheck(this, BufferList); this.head = null; this.tail = null; this.length = 0; } BufferList.prototype.push = function push(v) { var entry = { data: v, next: null }; if (this.length > 0) this.tail.next = entry;else this.head = entry; this.tail = entry; ++this.length; }; BufferList.prototype.unshift = function unshift(v) { var entry = { data: v, next: this.head }; if (this.length === 0) this.tail = entry; this.head = entry; ++this.length; }; BufferList.prototype.shift = function shift() { if (this.length === 0) return; var ret = this.head.data; if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; --this.length; return ret; }; BufferList.prototype.clear = function clear() { this.head = this.tail = null; this.length = 0; }; BufferList.prototype.join = function join(s) { if (this.length === 0) return ''; var p = this.head; var ret = '' + p.data; while (p = p.next) { ret += s + p.data; }return ret; }; BufferList.prototype.concat = function concat(n) { if (this.length === 0) return Buffer.alloc(0); var ret = Buffer.allocUnsafe(n >>> 0); var p = this.head; var i = 0; while (p) { copyBuffer(p.data, ret, i); i += p.data.length; p = p.next; } return ret; }; return BufferList; }(); if (util && util.inspect && util.inspect.custom) { module.exports.prototype[util.inspect.custom] = function () { var obj = util.inspect({ length: this.length }); return this.constructor.name + ' ' + obj; }; } /***/ }), /***/ 55513: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /**/ var pna = __webpack_require__(88212); /**/ // undocumented cb() API, needed for core, not for public API function destroy(err, cb) { var _this = this; var readableDestroyed = this._readableState && this._readableState.destroyed; var writableDestroyed = this._writableState && this._writableState.destroyed; if (readableDestroyed || writableDestroyed) { if (cb) { cb(err); } else if (err) { if (!this._writableState) { pna.nextTick(emitErrorNT, this, err); } else if (!this._writableState.errorEmitted) { this._writableState.errorEmitted = true; pna.nextTick(emitErrorNT, this, err); } } return this; } // we set destroyed to true before firing error callbacks in order // to make it re-entrance safe in case destroy() is called within callbacks if (this._readableState) { this._readableState.destroyed = true; } // if this is a duplex stream mark the writable part as destroyed as well if (this._writableState) { this._writableState.destroyed = true; } this._destroy(err || null, function (err) { if (!cb && err) { if (!_this._writableState) { pna.nextTick(emitErrorNT, _this, err); } else if (!_this._writableState.errorEmitted) { _this._writableState.errorEmitted = true; pna.nextTick(emitErrorNT, _this, err); } } else if (cb) { cb(err); } }); return this; } function undestroy() { if (this._readableState) { this._readableState.destroyed = false; this._readableState.reading = false; this._readableState.ended = false; this._readableState.endEmitted = false; } if (this._writableState) { this._writableState.destroyed = false; this._writableState.ended = false; this._writableState.ending = false; this._writableState.finalCalled = false; this._writableState.prefinished = false; this._writableState.finished = false; this._writableState.errorEmitted = false; } } function emitErrorNT(self, err) { self.emit('error', err); } module.exports = { destroy: destroy, undestroy: undestroy }; /***/ }), /***/ 95829: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = __webpack_require__(12781); /***/ }), /***/ 15638: /***/ ((module, exports, __webpack_require__) => { var Stream = __webpack_require__(12781); if (process.env.READABLE_STREAM === 'disable' && Stream) { module.exports = Stream; exports = module.exports = Stream.Readable; exports.Readable = Stream.Readable; exports.Writable = Stream.Writable; exports.Duplex = Stream.Duplex; exports.Transform = Stream.Transform; exports.PassThrough = Stream.PassThrough; exports.Stream = Stream; } else { exports = module.exports = __webpack_require__(44278); exports.Stream = Stream || exports; exports.Readable = exports; exports.Writable = __webpack_require__(10759); exports.Duplex = __webpack_require__(45867); exports.Transform = __webpack_require__(60062); exports.PassThrough = __webpack_require__(3431); } /***/ }), /***/ 47989: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /**/ var Buffer = __webpack_require__(89509).Buffer; /**/ var isEncoding = Buffer.isEncoding || function (encoding) { encoding = '' + encoding; switch (encoding && encoding.toLowerCase()) { case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': return true; default: return false; } }; function _normalizeEncoding(enc) { if (!enc) return 'utf8'; var retried; while (true) { switch (enc) { case 'utf8': case 'utf-8': return 'utf8'; case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return 'utf16le'; case 'latin1': case 'binary': return 'latin1'; case 'base64': case 'ascii': case 'hex': return enc; default: if (retried) return; // undefined enc = ('' + enc).toLowerCase(); retried = true; } } }; // Do not cache `Buffer.isEncoding` when checking encoding names as some // modules monkey-patch it to support additional encodings function normalizeEncoding(enc) { var nenc = _normalizeEncoding(enc); if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); return nenc || enc; } // StringDecoder provides an interface for efficiently splitting a series of // buffers into a series of JS strings without breaking apart multi-byte // characters. exports.s = StringDecoder; function StringDecoder(encoding) { this.encoding = normalizeEncoding(encoding); var nb; switch (this.encoding) { case 'utf16le': this.text = utf16Text; this.end = utf16End; nb = 4; break; case 'utf8': this.fillLast = utf8FillLast; nb = 4; break; case 'base64': this.text = base64Text; this.end = base64End; nb = 3; break; default: this.write = simpleWrite; this.end = simpleEnd; return; } this.lastNeed = 0; this.lastTotal = 0; this.lastChar = Buffer.allocUnsafe(nb); } StringDecoder.prototype.write = function (buf) { if (buf.length === 0) return ''; var r; var i; if (this.lastNeed) { r = this.fillLast(buf); if (r === undefined) return ''; i = this.lastNeed; this.lastNeed = 0; } else { i = 0; } if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); return r || ''; }; StringDecoder.prototype.end = utf8End; // Returns only complete characters in a Buffer StringDecoder.prototype.text = utf8Text; // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer StringDecoder.prototype.fillLast = function (buf) { if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); this.lastNeed -= buf.length; }; // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a // continuation byte. If an invalid byte is detected, -2 is returned. function utf8CheckByte(byte) { if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; return byte >> 6 === 0x02 ? -1 : -2; } // Checks at most 3 bytes at the end of a Buffer in order to detect an // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) // needed to complete the UTF-8 character (if applicable) are returned. function utf8CheckIncomplete(self, buf, i) { var j = buf.length - 1; if (j < i) return 0; var nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 1; return nb; } if (--j < i || nb === -2) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 2; return nb; } if (--j < i || nb === -2) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) { if (nb === 2) nb = 0;else self.lastNeed = nb - 3; } return nb; } return 0; } // Validates as many continuation bytes for a multi-byte UTF-8 character as // needed or are available. If we see a non-continuation byte where we expect // one, we "replace" the validated continuation bytes we've seen so far with // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding // behavior. The continuation byte check is included three times in the case // where all of the continuation bytes for a character exist in the same buffer. // It is also done this way as a slight performance increase instead of using a // loop. function utf8CheckExtraBytes(self, buf, p) { if ((buf[0] & 0xC0) !== 0x80) { self.lastNeed = 0; return '\ufffd'; } if (self.lastNeed > 1 && buf.length > 1) { if ((buf[1] & 0xC0) !== 0x80) { self.lastNeed = 1; return '\ufffd'; } if (self.lastNeed > 2 && buf.length > 2) { if ((buf[2] & 0xC0) !== 0x80) { self.lastNeed = 2; return '\ufffd'; } } } } // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. function utf8FillLast(buf) { var p = this.lastTotal - this.lastNeed; var r = utf8CheckExtraBytes(this, buf, p); if (r !== undefined) return r; if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, p, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, p, 0, buf.length); this.lastNeed -= buf.length; } // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a // partial character, the character's bytes are buffered until the required // number of bytes are available. function utf8Text(buf, i) { var total = utf8CheckIncomplete(this, buf, i); if (!this.lastNeed) return buf.toString('utf8', i); this.lastTotal = total; var end = buf.length - (total - this.lastNeed); buf.copy(this.lastChar, 0, end); return buf.toString('utf8', i, end); } // For UTF-8, a replacement character is added when ending on a partial // character. function utf8End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + '\ufffd'; return r; } // UTF-16LE typically needs two bytes per character, but even if we have an even // number of bytes available, we need to check if we end on a leading/high // surrogate. In that case, we need to wait for the next two bytes in order to // decode the last character properly. function utf16Text(buf, i) { if ((buf.length - i) % 2 === 0) { var r = buf.toString('utf16le', i); if (r) { var c = r.charCodeAt(r.length - 1); if (c >= 0xD800 && c <= 0xDBFF) { this.lastNeed = 2; this.lastTotal = 4; this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; return r.slice(0, -1); } } return r; } this.lastNeed = 1; this.lastTotal = 2; this.lastChar[0] = buf[buf.length - 1]; return buf.toString('utf16le', i, buf.length - 1); } // For UTF-16LE we do not explicitly append special replacement characters if we // end on a partial character, we simply let v8 handle that. function utf16End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) { var end = this.lastTotal - this.lastNeed; return r + this.lastChar.toString('utf16le', 0, end); } return r; } function base64Text(buf, i) { var n = (buf.length - i) % 3; if (n === 0) return buf.toString('base64', i); this.lastNeed = 3 - n; this.lastTotal = 3; if (n === 1) { this.lastChar[0] = buf[buf.length - 1]; } else { this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; } return buf.toString('base64', i, buf.length - n); } function base64End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); return r; } // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) function simpleWrite(buf) { return buf.toString(this.encoding); } function simpleEnd(buf) { return buf && buf.length ? this.write(buf) : ''; } /***/ }), /***/ 14650: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var Transform = __webpack_require__(15638).Transform , inherits = __webpack_require__(73837).inherits , xtend = __webpack_require__(47529) function DestroyableTransform(opts) { Transform.call(this, opts) this._destroyed = false } inherits(DestroyableTransform, Transform) DestroyableTransform.prototype.destroy = function(err) { if (this._destroyed) return this._destroyed = true var self = this process.nextTick(function() { if (err) self.emit('error', err) self.emit('close') }) } // a noop _transform function function noop (chunk, enc, callback) { callback(null, chunk) } // create a new export function, used by both the main export and // the .ctor export, contains common logic for dealing with arguments function through2 (construct) { return function (options, transform, flush) { if (typeof options == 'function') { flush = transform transform = options options = {} } if (typeof transform != 'function') transform = noop if (typeof flush != 'function') flush = null return construct(options, transform, flush) } } // main export, just make me a transform stream! module.exports = through2(function (options, transform, flush) { var t2 = new DestroyableTransform(options) t2._transform = transform if (flush) t2._flush = flush return t2 }) // make me a reusable prototype that I can `new`, or implicitly `new` // with a constructor call module.exports.ctor = through2(function (options, transform, flush) { function Through2 (override) { if (!(this instanceof Through2)) return new Through2(override) this.options = xtend(options, override) DestroyableTransform.call(this, this.options) } inherits(Through2, DestroyableTransform) Through2.prototype._transform = transform if (flush) Through2.prototype._flush = flush return Through2 }) module.exports.obj = through2(function (options, transform, flush) { var t2 = new DestroyableTransform(xtend({ objectMode: true, highWaterMark: 16 }, options)) t2._transform = transform if (flush) t2._flush = flush return t2 }) /***/ }), /***/ 36276: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /*! * Tmp * * Copyright (c) 2011-2017 KARASZI Istvan * * MIT Licensed */ /* * Module dependencies. */ const fs = __webpack_require__(57147); const path = __webpack_require__(71017); const crypto = __webpack_require__(6113); const osTmpDir = __webpack_require__(55339); const _c = process.binding('constants'); /* * The working inner variables. */ const /** * The temporary directory. * @type {string} */ tmpDir = osTmpDir(), // the random characters to choose from RANDOM_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', TEMPLATE_PATTERN = /XXXXXX/, DEFAULT_TRIES = 3, CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR), EBADF = _c.EBADF || _c.os.errno.EBADF, ENOENT = _c.ENOENT || _c.os.errno.ENOENT, DIR_MODE = 448 /* 0o700 */, FILE_MODE = 384 /* 0o600 */, // this will hold the objects need to be removed on exit _removeObjects = []; var _gracefulCleanup = false, _uncaughtException = false; /** * Random name generator based on crypto. * Adapted from http://blog.tompawlak.org/how-to-generate-random-values-nodejs-javascript * * @param {number} howMany * @returns {string} the generated random name * @private */ function _randomChars(howMany) { var value = [], rnd = null; // make sure that we do not fail because we ran out of entropy try { rnd = crypto.randomBytes(howMany); } catch (e) { rnd = crypto.pseudoRandomBytes(howMany); } for (var i = 0; i < howMany; i++) { value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]); } return value.join(''); } /** * Checks whether the `obj` parameter is defined or not. * * @param {Object} obj * @returns {boolean} true if the object is undefined * @private */ function _isUndefined(obj) { return typeof obj === 'undefined'; } /** * Parses the function arguments. * * This function helps to have optional arguments. * * @param {(Options|Function)} options * @param {Function} callback * @returns {Array} parsed arguments * @private */ function _parseArguments(options, callback) { if (typeof options == 'function') { return [callback || {}, options]; } if (_isUndefined(options)) { return [{}, callback]; } return [options, callback]; } /** * Generates a new temporary name. * * @param {Object} opts * @returns {string} the new random name according to opts * @private */ function _generateTmpName(opts) { if (opts.name) { return path.join(opts.dir || tmpDir, opts.name); } // mkstemps like template if (opts.template) { return opts.template.replace(TEMPLATE_PATTERN, _randomChars(6)); } // prefix and postfix const name = [ opts.prefix || 'tmp-', process.pid, _randomChars(12), opts.postfix || '' ].join(''); return path.join(opts.dir || tmpDir, name); } /** * Gets a temporary file name. * * @param {(Options|tmpNameCallback)} options options or callback * @param {?tmpNameCallback} callback the callback function */ function tmpName(options, callback) { var args = _parseArguments(options, callback), opts = args[0], cb = args[1], tries = opts.name ? 1 : opts.tries || DEFAULT_TRIES; if (isNaN(tries) || tries < 0) return cb(new Error('Invalid tries')); if (opts.template && !opts.template.match(TEMPLATE_PATTERN)) return cb(new Error('Invalid template provided')); (function _getUniqueName() { const name = _generateTmpName(opts); // check whether the path exists then retry if needed fs.stat(name, function (err) { if (!err) { if (tries-- > 0) return _getUniqueName(); return cb(new Error('Could not get a unique tmp filename, max tries reached ' + name)); } cb(null, name); }); }()); } /** * Synchronous version of tmpName. * * @param {Object} options * @returns {string} the generated random name * @throws {Error} if the options are invalid or could not generate a filename */ function tmpNameSync(options) { var args = _parseArguments(options), opts = args[0], tries = opts.name ? 1 : opts.tries || DEFAULT_TRIES; if (isNaN(tries) || tries < 0) throw new Error('Invalid tries'); if (opts.template && !opts.template.match(TEMPLATE_PATTERN)) throw new Error('Invalid template provided'); do { const name = _generateTmpName(opts); try { fs.statSync(name); } catch (e) { return name; } } while (tries-- > 0); throw new Error('Could not get a unique tmp filename, max tries reached'); } /** * Creates and opens a temporary file. * * @param {(Options|fileCallback)} options the config options or the callback function * @param {?fileCallback} callback */ function file(options, callback) { var args = _parseArguments(options, callback), opts = args[0], cb = args[1]; opts.postfix = (_isUndefined(opts.postfix)) ? '.tmp' : opts.postfix; // gets a temporary filename tmpName(opts, function _tmpNameCreated(err, name) { if (err) return cb(err); // create and open the file fs.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err, fd) { if (err) return cb(err); if (opts.discardDescriptor) { return fs.close(fd, function _discardCallback(err) { if (err) { // Low probability, and the file exists, so this could be // ignored. If it isn't we certainly need to unlink the // file, and if that fails too its error is more // important. try { fs.unlinkSync(name); } catch (e) { if (!isENOENT(e)) { err = e; } } return cb(err); } cb(null, name, undefined, _prepareTmpFileRemoveCallback(name, -1, opts)); }); } if (opts.detachDescriptor) { return cb(null, name, fd, _prepareTmpFileRemoveCallback(name, -1, opts)); } cb(null, name, fd, _prepareTmpFileRemoveCallback(name, fd, opts)); }); }); } /** * Synchronous version of file. * * @param {Options} options * @returns {FileSyncObject} object consists of name, fd and removeCallback * @throws {Error} if cannot create a file */ function fileSync(options) { var args = _parseArguments(options), opts = args[0]; opts.postfix = opts.postfix || '.tmp'; const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; const name = tmpNameSync(opts); var fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); if (opts.discardDescriptor) { fs.closeSync(fd); fd = undefined; } return { name: name, fd: fd, removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts) }; } /** * Removes files and folders in a directory recursively. * * @param {string} root * @private */ function _rmdirRecursiveSync(root) { const dirs = [root]; do { var dir = dirs.pop(), deferred = false, files = fs.readdirSync(dir); for (var i = 0, length = files.length; i < length; i++) { var file = path.join(dir, files[i]), stat = fs.lstatSync(file); // lstat so we don't recurse into symlinked directories if (stat.isDirectory()) { if (!deferred) { deferred = true; dirs.push(dir); } dirs.push(file); } else { fs.unlinkSync(file); } } if (!deferred) { fs.rmdirSync(dir); } } while (dirs.length !== 0); } /** * Creates a temporary directory. * * @param {(Options|dirCallback)} options the options or the callback function * @param {?dirCallback} callback */ function dir(options, callback) { var args = _parseArguments(options, callback), opts = args[0], cb = args[1]; // gets a temporary filename tmpName(opts, function _tmpNameCreated(err, name) { if (err) return cb(err); // create the directory fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err) { if (err) return cb(err); cb(null, name, _prepareTmpDirRemoveCallback(name, opts)); }); }); } /** * Synchronous version of dir. * * @param {Options} options * @returns {DirSyncObject} object consists of name and removeCallback * @throws {Error} if it cannot create a directory */ function dirSync(options) { var args = _parseArguments(options), opts = args[0]; const name = tmpNameSync(opts); fs.mkdirSync(name, opts.mode || DIR_MODE); return { name: name, removeCallback: _prepareTmpDirRemoveCallback(name, opts) }; } /** * Prepares the callback for removal of the temporary file. * * @param {string} name the path of the file * @param {number} fd file descriptor * @param {Object} opts * @returns {fileCallback} * @private */ function _prepareTmpFileRemoveCallback(name, fd, opts) { const removeCallback = _prepareRemoveCallback(function _removeCallback(fdPath) { try { if (0 <= fdPath[0]) { fs.closeSync(fdPath[0]); } } catch (e) { // under some node/windows related circumstances, a temporary file // may have not be created as expected or the file was already closed // by the user, in which case we will simply ignore the error if (!isEBADF(e) && !isENOENT(e)) { // reraise any unanticipated error throw e; } } try { fs.unlinkSync(fdPath[1]); } catch (e) { if (!isENOENT(e)) { // reraise any unanticipated error throw e; } } }, [fd, name]); if (!opts.keep) { _removeObjects.unshift(removeCallback); } return removeCallback; } /** * Prepares the callback for removal of the temporary directory. * * @param {string} name * @param {Object} opts * @returns {Function} the callback * @private */ function _prepareTmpDirRemoveCallback(name, opts) { const removeFunction = opts.unsafeCleanup ? _rmdirRecursiveSync : fs.rmdirSync.bind(fs); const removeCallback = _prepareRemoveCallback(removeFunction, name); if (!opts.keep) { _removeObjects.unshift(removeCallback); } return removeCallback; } /** * Creates a guarded function wrapping the removeFunction call. * * @param {Function} removeFunction * @param {Object} arg * @returns {Function} * @private */ function _prepareRemoveCallback(removeFunction, arg) { var called = false; return function _cleanupCallback(next) { if (!called) { const index = _removeObjects.indexOf(_cleanupCallback); if (index >= 0) { _removeObjects.splice(index, 1); } called = true; removeFunction(arg); } if (next) next(null); }; } /** * The garbage collector. * * @private */ function _garbageCollector() { if (_uncaughtException && !_gracefulCleanup) { return; } // the function being called removes itself from _removeObjects, // loop until _removeObjects is empty while (_removeObjects.length) { try { _removeObjects[0].call(null); } catch (e) { // already removed? } } } /** * Helper for testing against EBADF to compensate changes made to Node 7.x under Windows. */ function isEBADF(error) { return isExpectedError(error, -EBADF, 'EBADF'); } /** * Helper for testing against ENOENT to compensate changes made to Node 7.x under Windows. */ function isENOENT(error) { return isExpectedError(error, -ENOENT, 'ENOENT'); } /** * Helper to determine whether the expected error code matches the actual code and errno, * which will differ between the supported node versions. * * - Node >= 7.0: * error.code {String} * error.errno {String|Number} any numerical value will be negated * * - Node >= 6.0 < 7.0: * error.code {String} * error.errno {Number} negated * * - Node >= 4.0 < 6.0: introduces SystemError * error.code {String} * error.errno {Number} negated * * - Node >= 0.10 < 4.0: * error.code {Number} negated * error.errno n/a */ function isExpectedError(error, code, errno) { return error.code == code || error.code == errno; } /** * Sets the graceful cleanup. * * Also removes the created files and directories when an uncaught exception occurs. */ function setGracefulCleanup() { _gracefulCleanup = true; } const version = process.versions.node.split('.').map(function (value) { return parseInt(value, 10); }); if (version[0] === 0 && (version[1] < 9 || version[1] === 9 && version[2] < 5)) { process.addListener('uncaughtException', function _uncaughtExceptionThrown(err) { _uncaughtException = true; _garbageCollector(); throw err; }); } process.addListener('exit', function _exit(code) { if (code) _uncaughtException = true; _garbageCollector(); }); /** * Configuration options. * * @typedef {Object} Options * @property {?number} tries the number of tries before give up the name generation * @property {?string} template the "mkstemp" like filename template * @property {?string} name fix name * @property {?string} dir the tmp directory to use * @property {?string} prefix prefix for the generated name * @property {?string} postfix postfix for the generated name */ /** * @typedef {Object} FileSyncObject * @property {string} name the name of the file * @property {string} fd the file descriptor * @property {fileCallback} removeCallback the callback function to remove the file */ /** * @typedef {Object} DirSyncObject * @property {string} name the name of the directory * @property {fileCallback} removeCallback the callback function to remove the directory */ /** * @callback tmpNameCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name */ /** * @callback fileCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {number} fd the file descriptor * @param {cleanupCallback} fn the cleanup callback function */ /** * @callback dirCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {cleanupCallback} fn the cleanup callback function */ /** * Removes the temporary created file or directory. * * @callback cleanupCallback * @param {simpleCallback} [next] function to call after entry was removed */ /** * Callback function for function composition. * @see {@link https://github.com/raszi/node-tmp/issues/57|raszi/node-tmp#57} * * @callback simpleCallback */ // exporting all the needed methods module.exports.tmpdir = tmpDir; module.exports.dir = dir; module.exports.dirSync = dirSync; module.exports.file = file; module.exports.fileSync = fileSync; module.exports.tmpName = tmpName; module.exports.tmpNameSync = tmpNameSync; module.exports.setGracefulCleanup = setGracefulCleanup; /***/ }), /***/ 45702: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * to-regex-range * * Copyright (c) 2015-present, Jon Schlinkert. * Released under the MIT License. */ const isNumber = __webpack_require__(19924); const toRegexRange = (min, max, options) => { if (isNumber(min) === false) { throw new TypeError('toRegexRange: expected the first argument to be a number'); } if (max === void 0 || min === max) { return String(min); } if (isNumber(max) === false) { throw new TypeError('toRegexRange: expected the second argument to be a number.'); } let opts = { relaxZeros: true, ...options }; if (typeof opts.strictZeros === 'boolean') { opts.relaxZeros = opts.strictZeros === false; } let relax = String(opts.relaxZeros); let shorthand = String(opts.shorthand); let capture = String(opts.capture); let wrap = String(opts.wrap); let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; if (toRegexRange.cache.hasOwnProperty(cacheKey)) { return toRegexRange.cache[cacheKey].result; } let a = Math.min(min, max); let b = Math.max(min, max); if (Math.abs(a - b) === 1) { let result = min + '|' + max; if (opts.capture) { return `(${result})`; } if (opts.wrap === false) { return result; } return `(?:${result})`; } let isPadded = hasPadding(min) || hasPadding(max); let state = { min, max, a, b }; let positives = []; let negatives = []; if (isPadded) { state.isPadded = isPadded; state.maxLen = String(state.max).length; } if (a < 0) { let newMin = b < 0 ? Math.abs(b) : 1; negatives = splitToPatterns(newMin, Math.abs(a), state, opts); a = state.a = 0; } if (b >= 0) { positives = splitToPatterns(a, b, state, opts); } state.negatives = negatives; state.positives = positives; state.result = collatePatterns(negatives, positives, opts); if (opts.capture === true) { state.result = `(${state.result})`; } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) { state.result = `(?:${state.result})`; } toRegexRange.cache[cacheKey] = state; return state.result; }; function collatePatterns(neg, pos, options) { let onlyNegative = filterPatterns(neg, pos, '-', false, options) || []; let onlyPositive = filterPatterns(pos, neg, '', false, options) || []; let intersected = filterPatterns(neg, pos, '-?', true, options) || []; let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); return subpatterns.join('|'); } function splitToRanges(min, max) { let nines = 1; let zeros = 1; let stop = countNines(min, nines); let stops = new Set([max]); while (min <= stop && stop <= max) { stops.add(stop); nines += 1; stop = countNines(min, nines); } stop = countZeros(max + 1, zeros) - 1; while (min < stop && stop <= max) { stops.add(stop); zeros += 1; stop = countZeros(max + 1, zeros) - 1; } stops = [...stops]; stops.sort(compare); return stops; } /** * Convert a range to a regex pattern * @param {Number} `start` * @param {Number} `stop` * @return {String} */ function rangeToPattern(start, stop, options) { if (start === stop) { return { pattern: start, count: [], digits: 0 }; } let zipped = zip(start, stop); let digits = zipped.length; let pattern = ''; let count = 0; for (let i = 0; i < digits; i++) { let [startDigit, stopDigit] = zipped[i]; if (startDigit === stopDigit) { pattern += startDigit; } else if (startDigit !== '0' || stopDigit !== '9') { pattern += toCharacterClass(startDigit, stopDigit, options); } else { count++; } } if (count) { pattern += options.shorthand === true ? '\\d' : '[0-9]'; } return { pattern, count: [count], digits }; } function splitToPatterns(min, max, tok, options) { let ranges = splitToRanges(min, max); let tokens = []; let start = min; let prev; for (let i = 0; i < ranges.length; i++) { let max = ranges[i]; let obj = rangeToPattern(String(start), String(max), options); let zeros = ''; if (!tok.isPadded && prev && prev.pattern === obj.pattern) { if (prev.count.length > 1) { prev.count.pop(); } prev.count.push(obj.count[0]); prev.string = prev.pattern + toQuantifier(prev.count); start = max + 1; continue; } if (tok.isPadded) { zeros = padZeros(max, tok, options); } obj.string = zeros + obj.pattern + toQuantifier(obj.count); tokens.push(obj); start = max + 1; prev = obj; } return tokens; } function filterPatterns(arr, comparison, prefix, intersection, options) { let result = []; for (let ele of arr) { let { string } = ele; // only push if _both_ are negative... if (!intersection && !contains(comparison, 'string', string)) { result.push(prefix + string); } // or _both_ are positive if (intersection && contains(comparison, 'string', string)) { result.push(prefix + string); } } return result; } /** * Zip strings */ function zip(a, b) { let arr = []; for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); return arr; } function compare(a, b) { return a > b ? 1 : b > a ? -1 : 0; } function contains(arr, key, val) { return arr.some(ele => ele[key] === val); } function countNines(min, len) { return Number(String(min).slice(0, -len) + '9'.repeat(len)); } function countZeros(integer, zeros) { return integer - (integer % Math.pow(10, zeros)); } function toQuantifier(digits) { let [start = 0, stop = ''] = digits; if (stop || start > 1) { return `{${start + (stop ? ',' + stop : '')}}`; } return ''; } function toCharacterClass(a, b, options) { return `[${a}${(b - a === 1) ? '' : '-'}${b}]`; } function hasPadding(str) { return /^-?(0+)\d/.test(str); } function padZeros(value, tok, options) { if (!tok.isPadded) { return value; } let diff = Math.abs(tok.maxLen - String(value).length); let relax = options.relaxZeros !== false; switch (diff) { case 0: return ''; case 1: return relax ? '0?' : '0'; case 2: return relax ? '0{0,2}' : '00'; default: { return relax ? `0{0,${diff}}` : `0{${diff}}`; } } } /** * Cache */ toRegexRange.cache = {}; toRegexRange.clearCache = () => (toRegexRange.cache = {}); /** * Expose `toRegexRange` */ module.exports = toRegexRange; /***/ }), /***/ 28: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var childProcess = __webpack_require__(32081); var spawn = childProcess.spawn; var exec = childProcess.exec; module.exports = function (pid, signal, callback) { if (typeof signal === 'function' && callback === undefined) { callback = signal; signal = undefined; } pid = parseInt(pid); if (Number.isNaN(pid)) { if (callback) { return callback(new Error("pid must be a number")); } else { throw new Error("pid must be a number"); } } var tree = {}; var pidsToProcess = {}; tree[pid] = []; pidsToProcess[pid] = 1; switch (process.platform) { case 'win32': exec('taskkill /pid ' + pid + ' /T /F', callback); break; case 'darwin': buildProcessTree(pid, tree, pidsToProcess, function (parentPid) { return spawn('pgrep', ['-P', parentPid]); }, function () { killAll(tree, signal, callback); }); break; // case 'sunos': // buildProcessTreeSunOS(pid, tree, pidsToProcess, function () { // killAll(tree, signal, callback); // }); // break; default: // Linux buildProcessTree(pid, tree, pidsToProcess, function (parentPid) { return spawn('ps', ['-o', 'pid', '--no-headers', '--ppid', parentPid]); }, function () { killAll(tree, signal, callback); }); break; } }; function killAll (tree, signal, callback) { var killed = {}; try { Object.keys(tree).forEach(function (pid) { tree[pid].forEach(function (pidpid) { if (!killed[pidpid]) { killPid(pidpid, signal); killed[pidpid] = 1; } }); if (!killed[pid]) { killPid(pid, signal); killed[pid] = 1; } }); } catch (err) { if (callback) { return callback(err); } else { throw err; } } if (callback) { return callback(); } } function killPid(pid, signal) { try { process.kill(parseInt(pid, 10), signal); } catch (err) { if (err.code !== 'ESRCH') throw err; } } function buildProcessTree (parentPid, tree, pidsToProcess, spawnChildProcessesList, cb) { var ps = spawnChildProcessesList(parentPid); var allData = ''; ps.stdout.on('data', function (data) { var data = data.toString('ascii'); allData += data; }); var onClose = function (code) { delete pidsToProcess[parentPid]; if (code != 0) { // no more parent processes if (Object.keys(pidsToProcess).length == 0) { cb(); } return; } allData.match(/\d+/g).forEach(function (pid) { pid = parseInt(pid, 10); tree[parentPid].push(pid); tree[pid] = []; pidsToProcess[pid] = 1; buildProcessTree(pid, tree, pidsToProcess, spawnChildProcessesList, cb); }); }; ps.on('close', onClose); } /***/ }), /***/ 99269: /***/ (function(module) { // treeify.js // Luke Plaster // https://github.com/notatestuser/treeify.js // do the universal module definition dance (function (root, factory) { if (true) { module.exports = factory(); } else {} }(this, function() { function makePrefix(key, last) { var str = (last ? '└' : '├'); if (key) { str += '─ '; } else { str += '──┐'; } return str; } function filterKeys(obj, hideFunctions) { var keys = []; for (var branch in obj) { // always exclude anything in the object's prototype if (!obj.hasOwnProperty(branch)) { continue; } // ... and hide any keys mapped to functions if we've been told to if (hideFunctions && ((typeof obj[branch])==="function")) { continue; } keys.push(branch); } return keys; } function growBranch(key, root, last, lastStates, showValues, hideFunctions, callback) { var line = '', index = 0, lastKey, circular, lastStatesCopy = lastStates.slice(0); if (lastStatesCopy.push([ root, last ]) && lastStates.length > 0) { // based on the "was last element" states of whatever we're nested within, // we need to append either blankness or a branch to our line lastStates.forEach(function(lastState, idx) { if (idx > 0) { line += (lastState[1] ? ' ' : '│') + ' '; } if ( ! circular && lastState[0] === root) { circular = true; } }); // the prefix varies based on whether the key contains something to show and // whether we're dealing with the last element in this collection line += makePrefix(key, last) + key; // append values and the circular reference indicator showValues && (typeof root !== 'object' || root instanceof Date) && (line += ': ' + root); circular && (line += ' (circular ref.)'); callback(line); } // can we descend into the next item? if ( ! circular && typeof root === 'object') { var keys = filterKeys(root, hideFunctions); keys.forEach(function(branch){ // the last key is always printed with a different prefix, so we'll need to know if we have it lastKey = ++index === keys.length; // hold your breath for recursive action growBranch(branch, root[branch], lastKey, lastStatesCopy, showValues, hideFunctions, callback); }); } }; // -------------------- var Treeify = {}; // Treeify.asLines // -------------------- // Outputs the tree line-by-line, calling the lineCallback when each one is available. Treeify.asLines = function(obj, showValues, hideFunctions, lineCallback) { /* hideFunctions and lineCallback are curried, which means we don't break apps using the older form */ var hideFunctionsArg = typeof hideFunctions !== 'function' ? hideFunctions : false; growBranch('.', obj, false, [], showValues, hideFunctionsArg, lineCallback || hideFunctions); }; // Treeify.asTree // -------------------- // Outputs the entire tree, returning it as a string with line breaks. Treeify.asTree = function(obj, showValues, hideFunctions) { var tree = ''; growBranch('.', obj, false, [], showValues, hideFunctions, function(line) { tree += line + '\n'; }); return tree; }; // -------------------- return Treeify; })); /***/ }), /***/ 70655: /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "__extends": () => (/* binding */ __extends), /* harmony export */ "__assign": () => (/* binding */ __assign), /* harmony export */ "__rest": () => (/* binding */ __rest), /* harmony export */ "__decorate": () => (/* binding */ __decorate), /* harmony export */ "__param": () => (/* binding */ __param), /* harmony export */ "__metadata": () => (/* binding */ __metadata), /* harmony export */ "__awaiter": () => (/* binding */ __awaiter), /* harmony export */ "__generator": () => (/* binding */ __generator), /* harmony export */ "__createBinding": () => (/* binding */ __createBinding), /* harmony export */ "__exportStar": () => (/* binding */ __exportStar), /* harmony export */ "__values": () => (/* binding */ __values), /* harmony export */ "__read": () => (/* binding */ __read), /* harmony export */ "__spread": () => (/* binding */ __spread), /* harmony export */ "__spreadArrays": () => (/* binding */ __spreadArrays), /* harmony export */ "__await": () => (/* binding */ __await), /* harmony export */ "__asyncGenerator": () => (/* binding */ __asyncGenerator), /* harmony export */ "__asyncDelegator": () => (/* binding */ __asyncDelegator), /* harmony export */ "__asyncValues": () => (/* binding */ __asyncValues), /* harmony export */ "__makeTemplateObject": () => (/* binding */ __makeTemplateObject), /* harmony export */ "__importStar": () => (/* binding */ __importStar), /* harmony export */ "__importDefault": () => (/* binding */ __importDefault), /* harmony export */ "__classPrivateFieldGet": () => (/* binding */ __classPrivateFieldGet), /* harmony export */ "__classPrivateFieldSet": () => (/* binding */ __classPrivateFieldSet) /* harmony export */ }); /*! ***************************************************************************** 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 */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; } return __assign.apply(this, arguments); } 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; } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __createBinding(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; } function __exportStar(m, exports) { for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p]; } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; }; function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result.default = mod; return result; } function __importDefault(mod) { return (mod && mod.__esModule) ? mod : { default: mod }; } function __classPrivateFieldGet(receiver, privateMap) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return privateMap.get(receiver); } function __classPrivateFieldSet(receiver, privateMap, value) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to set private field on non-instance"); } privateMap.set(receiver, value); return value; } /***/ }), /***/ 6149: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = __webpack_require__(55468); /***/ }), /***/ 55468: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var net = __webpack_require__(41808); var tls = __webpack_require__(24404); var http = __webpack_require__(13685); var https = __webpack_require__(95687); var events = __webpack_require__(82361); var assert = __webpack_require__(39491); var util = __webpack_require__(73837); exports.httpOverHttp = httpOverHttp; exports.httpsOverHttp = httpsOverHttp; exports.httpOverHttps = httpOverHttps; exports.httpsOverHttps = httpsOverHttps; function httpOverHttp(options) { var agent = new TunnelingAgent(options); agent.request = http.request; return agent; } function httpsOverHttp(options) { var agent = new TunnelingAgent(options); agent.request = http.request; agent.createSocket = createSecureSocket; agent.defaultPort = 443; return agent; } function httpOverHttps(options) { var agent = new TunnelingAgent(options); agent.request = https.request; return agent; } function httpsOverHttps(options) { var agent = new TunnelingAgent(options); agent.request = https.request; agent.createSocket = createSecureSocket; agent.defaultPort = 443; return agent; } function TunnelingAgent(options) { var self = this; self.options = options || {}; self.proxyOptions = self.options.proxy || {}; self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; self.requests = []; self.sockets = []; self.on('free', function onFree(socket, host, port, localAddress) { var options = toOptions(host, port, localAddress); for (var i = 0, len = self.requests.length; i < len; ++i) { var pending = self.requests[i]; if (pending.host === options.host && pending.port === options.port) { // Detect the request to connect same origin server, // reuse the connection. self.requests.splice(i, 1); pending.request.onSocket(socket); return; } } socket.destroy(); self.removeSocket(socket); }); } util.inherits(TunnelingAgent, events.EventEmitter); TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { var self = this; var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); if (self.sockets.length >= this.maxSockets) { // We are over limit so we'll add it to the queue. self.requests.push(options); return; } // If we are under maxSockets create a new one. self.createSocket(options, function(socket) { socket.on('free', onFree); socket.on('close', onCloseOrRemove); socket.on('agentRemove', onCloseOrRemove); req.onSocket(socket); function onFree() { self.emit('free', socket, options); } function onCloseOrRemove(err) { self.removeSocket(socket); socket.removeListener('free', onFree); socket.removeListener('close', onCloseOrRemove); socket.removeListener('agentRemove', onCloseOrRemove); } }); }; TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { var self = this; var placeholder = {}; self.sockets.push(placeholder); var connectOptions = mergeOptions({}, self.proxyOptions, { method: 'CONNECT', path: options.host + ':' + options.port, agent: false, headers: { host: options.host + ':' + options.port } }); if (options.localAddress) { connectOptions.localAddress = options.localAddress; } if (connectOptions.proxyAuth) { connectOptions.headers = connectOptions.headers || {}; connectOptions.headers['Proxy-Authorization'] = 'Basic ' + new Buffer(connectOptions.proxyAuth).toString('base64'); } debug('making CONNECT request'); var connectReq = self.request(connectOptions); connectReq.useChunkedEncodingByDefault = false; // for v0.6 connectReq.once('response', onResponse); // for v0.6 connectReq.once('upgrade', onUpgrade); // for v0.6 connectReq.once('connect', onConnect); // for v0.7 or later connectReq.once('error', onError); connectReq.end(); function onResponse(res) { // Very hacky. This is necessary to avoid http-parser leaks. res.upgrade = true; } function onUpgrade(res, socket, head) { // Hacky. process.nextTick(function() { onConnect(res, socket, head); }); } function onConnect(res, socket, head) { connectReq.removeAllListeners(); socket.removeAllListeners(); if (res.statusCode !== 200) { debug('tunneling socket could not be established, statusCode=%d', res.statusCode); socket.destroy(); var error = new Error('tunneling socket could not be established, ' + 'statusCode=' + res.statusCode); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); return; } if (head.length > 0) { debug('got illegal response body from proxy'); socket.destroy(); var error = new Error('got illegal response body from proxy'); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); return; } debug('tunneling connection has established'); self.sockets[self.sockets.indexOf(placeholder)] = socket; return cb(socket); } function onError(cause) { connectReq.removeAllListeners(); debug('tunneling socket could not be established, cause=%s\n', cause.message, cause.stack); var error = new Error('tunneling socket could not be established, ' + 'cause=' + cause.message); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); } }; TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { var pos = this.sockets.indexOf(socket) if (pos === -1) { return; } this.sockets.splice(pos, 1); var pending = this.requests.shift(); if (pending) { // If we have pending requests and a socket gets closed a new one // needs to be created to take over in the pool for the one that closed. this.createSocket(pending, function(socket) { pending.request.onSocket(socket); }); } }; function createSecureSocket(options, cb) { var self = this; TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { var hostHeader = options.request.getHeader('host'); var tlsOptions = mergeOptions({}, self.options, { socket: socket, servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host }); // 0 is dummy port for v0.6 var secureSocket = tls.connect(0, tlsOptions); self.sockets[self.sockets.indexOf(socket)] = secureSocket; cb(secureSocket); }); } function toOptions(host, port, localAddress) { if (typeof host === 'string') { // since v0.10 return { host: host, port: port, localAddress: localAddress }; } return host; // for v0.11 or later } function mergeOptions(target) { for (var i = 1, len = arguments.length; i < len; ++i) { var overrides = arguments[i]; if (typeof overrides === 'object') { var keys = Object.keys(overrides); for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { var k = keys[j]; if (overrides[k] !== undefined) { target[k] = overrides[k]; } } } } return target; } var debug; if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { debug = function() { var args = Array.prototype.slice.call(arguments); if (typeof args[0] === 'string') { args[0] = 'TUNNEL: ' + args[0]; } else { args.unshift('TUNNEL:'); } console.error.apply(console, args); } } else { debug = function() {}; } exports.debug = debug; // for test /***/ }), /***/ 50780: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { (function(nacl) { 'use strict'; // Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. // Public domain. // // Implementation derived from TweetNaCl version 20140427. // See for details: http://tweetnacl.cr.yp.to/ var gf = function(init) { var i, r = new Float64Array(16); if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; return r; }; // Pluggable, initialized in high-level API below. var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; var _0 = new Uint8Array(16); var _9 = new Uint8Array(32); _9[0] = 9; var gf0 = gf(), gf1 = gf([1]), _121665 = gf([0xdb41, 1]), D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); function ts64(x, i, h, l) { x[i] = (h >> 24) & 0xff; x[i+1] = (h >> 16) & 0xff; x[i+2] = (h >> 8) & 0xff; x[i+3] = h & 0xff; x[i+4] = (l >> 24) & 0xff; x[i+5] = (l >> 16) & 0xff; x[i+6] = (l >> 8) & 0xff; x[i+7] = l & 0xff; } function vn(x, xi, y, yi, n) { var i,d = 0; for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; return (1 & ((d - 1) >>> 8)) - 1; } function crypto_verify_16(x, xi, y, yi) { return vn(x,xi,y,yi,16); } function crypto_verify_32(x, xi, y, yi) { return vn(x,xi,y,yi,32); } function core_salsa20(o, p, k, c) { var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u; for (var i = 0; i < 20; i += 2) { u = x0 + x12 | 0; x4 ^= u<<7 | u>>>(32-7); u = x4 + x0 | 0; x8 ^= u<<9 | u>>>(32-9); u = x8 + x4 | 0; x12 ^= u<<13 | u>>>(32-13); u = x12 + x8 | 0; x0 ^= u<<18 | u>>>(32-18); u = x5 + x1 | 0; x9 ^= u<<7 | u>>>(32-7); u = x9 + x5 | 0; x13 ^= u<<9 | u>>>(32-9); u = x13 + x9 | 0; x1 ^= u<<13 | u>>>(32-13); u = x1 + x13 | 0; x5 ^= u<<18 | u>>>(32-18); u = x10 + x6 | 0; x14 ^= u<<7 | u>>>(32-7); u = x14 + x10 | 0; x2 ^= u<<9 | u>>>(32-9); u = x2 + x14 | 0; x6 ^= u<<13 | u>>>(32-13); u = x6 + x2 | 0; x10 ^= u<<18 | u>>>(32-18); u = x15 + x11 | 0; x3 ^= u<<7 | u>>>(32-7); u = x3 + x15 | 0; x7 ^= u<<9 | u>>>(32-9); u = x7 + x3 | 0; x11 ^= u<<13 | u>>>(32-13); u = x11 + x7 | 0; x15 ^= u<<18 | u>>>(32-18); u = x0 + x3 | 0; x1 ^= u<<7 | u>>>(32-7); u = x1 + x0 | 0; x2 ^= u<<9 | u>>>(32-9); u = x2 + x1 | 0; x3 ^= u<<13 | u>>>(32-13); u = x3 + x2 | 0; x0 ^= u<<18 | u>>>(32-18); u = x5 + x4 | 0; x6 ^= u<<7 | u>>>(32-7); u = x6 + x5 | 0; x7 ^= u<<9 | u>>>(32-9); u = x7 + x6 | 0; x4 ^= u<<13 | u>>>(32-13); u = x4 + x7 | 0; x5 ^= u<<18 | u>>>(32-18); u = x10 + x9 | 0; x11 ^= u<<7 | u>>>(32-7); u = x11 + x10 | 0; x8 ^= u<<9 | u>>>(32-9); u = x8 + x11 | 0; x9 ^= u<<13 | u>>>(32-13); u = x9 + x8 | 0; x10 ^= u<<18 | u>>>(32-18); u = x15 + x14 | 0; x12 ^= u<<7 | u>>>(32-7); u = x12 + x15 | 0; x13 ^= u<<9 | u>>>(32-9); u = x13 + x12 | 0; x14 ^= u<<13 | u>>>(32-13); u = x14 + x13 | 0; x15 ^= u<<18 | u>>>(32-18); } x0 = x0 + j0 | 0; x1 = x1 + j1 | 0; x2 = x2 + j2 | 0; x3 = x3 + j3 | 0; x4 = x4 + j4 | 0; x5 = x5 + j5 | 0; x6 = x6 + j6 | 0; x7 = x7 + j7 | 0; x8 = x8 + j8 | 0; x9 = x9 + j9 | 0; x10 = x10 + j10 | 0; x11 = x11 + j11 | 0; x12 = x12 + j12 | 0; x13 = x13 + j13 | 0; x14 = x14 + j14 | 0; x15 = x15 + j15 | 0; o[ 0] = x0 >>> 0 & 0xff; o[ 1] = x0 >>> 8 & 0xff; o[ 2] = x0 >>> 16 & 0xff; o[ 3] = x0 >>> 24 & 0xff; o[ 4] = x1 >>> 0 & 0xff; o[ 5] = x1 >>> 8 & 0xff; o[ 6] = x1 >>> 16 & 0xff; o[ 7] = x1 >>> 24 & 0xff; o[ 8] = x2 >>> 0 & 0xff; o[ 9] = x2 >>> 8 & 0xff; o[10] = x2 >>> 16 & 0xff; o[11] = x2 >>> 24 & 0xff; o[12] = x3 >>> 0 & 0xff; o[13] = x3 >>> 8 & 0xff; o[14] = x3 >>> 16 & 0xff; o[15] = x3 >>> 24 & 0xff; o[16] = x4 >>> 0 & 0xff; o[17] = x4 >>> 8 & 0xff; o[18] = x4 >>> 16 & 0xff; o[19] = x4 >>> 24 & 0xff; o[20] = x5 >>> 0 & 0xff; o[21] = x5 >>> 8 & 0xff; o[22] = x5 >>> 16 & 0xff; o[23] = x5 >>> 24 & 0xff; o[24] = x6 >>> 0 & 0xff; o[25] = x6 >>> 8 & 0xff; o[26] = x6 >>> 16 & 0xff; o[27] = x6 >>> 24 & 0xff; o[28] = x7 >>> 0 & 0xff; o[29] = x7 >>> 8 & 0xff; o[30] = x7 >>> 16 & 0xff; o[31] = x7 >>> 24 & 0xff; o[32] = x8 >>> 0 & 0xff; o[33] = x8 >>> 8 & 0xff; o[34] = x8 >>> 16 & 0xff; o[35] = x8 >>> 24 & 0xff; o[36] = x9 >>> 0 & 0xff; o[37] = x9 >>> 8 & 0xff; o[38] = x9 >>> 16 & 0xff; o[39] = x9 >>> 24 & 0xff; o[40] = x10 >>> 0 & 0xff; o[41] = x10 >>> 8 & 0xff; o[42] = x10 >>> 16 & 0xff; o[43] = x10 >>> 24 & 0xff; o[44] = x11 >>> 0 & 0xff; o[45] = x11 >>> 8 & 0xff; o[46] = x11 >>> 16 & 0xff; o[47] = x11 >>> 24 & 0xff; o[48] = x12 >>> 0 & 0xff; o[49] = x12 >>> 8 & 0xff; o[50] = x12 >>> 16 & 0xff; o[51] = x12 >>> 24 & 0xff; o[52] = x13 >>> 0 & 0xff; o[53] = x13 >>> 8 & 0xff; o[54] = x13 >>> 16 & 0xff; o[55] = x13 >>> 24 & 0xff; o[56] = x14 >>> 0 & 0xff; o[57] = x14 >>> 8 & 0xff; o[58] = x14 >>> 16 & 0xff; o[59] = x14 >>> 24 & 0xff; o[60] = x15 >>> 0 & 0xff; o[61] = x15 >>> 8 & 0xff; o[62] = x15 >>> 16 & 0xff; o[63] = x15 >>> 24 & 0xff; } function core_hsalsa20(o,p,k,c) { var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u; for (var i = 0; i < 20; i += 2) { u = x0 + x12 | 0; x4 ^= u<<7 | u>>>(32-7); u = x4 + x0 | 0; x8 ^= u<<9 | u>>>(32-9); u = x8 + x4 | 0; x12 ^= u<<13 | u>>>(32-13); u = x12 + x8 | 0; x0 ^= u<<18 | u>>>(32-18); u = x5 + x1 | 0; x9 ^= u<<7 | u>>>(32-7); u = x9 + x5 | 0; x13 ^= u<<9 | u>>>(32-9); u = x13 + x9 | 0; x1 ^= u<<13 | u>>>(32-13); u = x1 + x13 | 0; x5 ^= u<<18 | u>>>(32-18); u = x10 + x6 | 0; x14 ^= u<<7 | u>>>(32-7); u = x14 + x10 | 0; x2 ^= u<<9 | u>>>(32-9); u = x2 + x14 | 0; x6 ^= u<<13 | u>>>(32-13); u = x6 + x2 | 0; x10 ^= u<<18 | u>>>(32-18); u = x15 + x11 | 0; x3 ^= u<<7 | u>>>(32-7); u = x3 + x15 | 0; x7 ^= u<<9 | u>>>(32-9); u = x7 + x3 | 0; x11 ^= u<<13 | u>>>(32-13); u = x11 + x7 | 0; x15 ^= u<<18 | u>>>(32-18); u = x0 + x3 | 0; x1 ^= u<<7 | u>>>(32-7); u = x1 + x0 | 0; x2 ^= u<<9 | u>>>(32-9); u = x2 + x1 | 0; x3 ^= u<<13 | u>>>(32-13); u = x3 + x2 | 0; x0 ^= u<<18 | u>>>(32-18); u = x5 + x4 | 0; x6 ^= u<<7 | u>>>(32-7); u = x6 + x5 | 0; x7 ^= u<<9 | u>>>(32-9); u = x7 + x6 | 0; x4 ^= u<<13 | u>>>(32-13); u = x4 + x7 | 0; x5 ^= u<<18 | u>>>(32-18); u = x10 + x9 | 0; x11 ^= u<<7 | u>>>(32-7); u = x11 + x10 | 0; x8 ^= u<<9 | u>>>(32-9); u = x8 + x11 | 0; x9 ^= u<<13 | u>>>(32-13); u = x9 + x8 | 0; x10 ^= u<<18 | u>>>(32-18); u = x15 + x14 | 0; x12 ^= u<<7 | u>>>(32-7); u = x12 + x15 | 0; x13 ^= u<<9 | u>>>(32-9); u = x13 + x12 | 0; x14 ^= u<<13 | u>>>(32-13); u = x14 + x13 | 0; x15 ^= u<<18 | u>>>(32-18); } o[ 0] = x0 >>> 0 & 0xff; o[ 1] = x0 >>> 8 & 0xff; o[ 2] = x0 >>> 16 & 0xff; o[ 3] = x0 >>> 24 & 0xff; o[ 4] = x5 >>> 0 & 0xff; o[ 5] = x5 >>> 8 & 0xff; o[ 6] = x5 >>> 16 & 0xff; o[ 7] = x5 >>> 24 & 0xff; o[ 8] = x10 >>> 0 & 0xff; o[ 9] = x10 >>> 8 & 0xff; o[10] = x10 >>> 16 & 0xff; o[11] = x10 >>> 24 & 0xff; o[12] = x15 >>> 0 & 0xff; o[13] = x15 >>> 8 & 0xff; o[14] = x15 >>> 16 & 0xff; o[15] = x15 >>> 24 & 0xff; o[16] = x6 >>> 0 & 0xff; o[17] = x6 >>> 8 & 0xff; o[18] = x6 >>> 16 & 0xff; o[19] = x6 >>> 24 & 0xff; o[20] = x7 >>> 0 & 0xff; o[21] = x7 >>> 8 & 0xff; o[22] = x7 >>> 16 & 0xff; o[23] = x7 >>> 24 & 0xff; o[24] = x8 >>> 0 & 0xff; o[25] = x8 >>> 8 & 0xff; o[26] = x8 >>> 16 & 0xff; o[27] = x8 >>> 24 & 0xff; o[28] = x9 >>> 0 & 0xff; o[29] = x9 >>> 8 & 0xff; o[30] = x9 >>> 16 & 0xff; o[31] = x9 >>> 24 & 0xff; } function crypto_core_salsa20(out,inp,k,c) { core_salsa20(out,inp,k,c); } function crypto_core_hsalsa20(out,inp,k,c) { core_hsalsa20(out,inp,k,c); } var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); // "expand 32-byte k" function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { var z = new Uint8Array(16), x = new Uint8Array(64); var u, i; for (i = 0; i < 16; i++) z[i] = 0; for (i = 0; i < 8; i++) z[i] = n[i]; while (b >= 64) { crypto_core_salsa20(x,z,k,sigma); for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i]; u = 1; for (i = 8; i < 16; i++) { u = u + (z[i] & 0xff) | 0; z[i] = u & 0xff; u >>>= 8; } b -= 64; cpos += 64; mpos += 64; } if (b > 0) { crypto_core_salsa20(x,z,k,sigma); for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i]; } return 0; } function crypto_stream_salsa20(c,cpos,b,n,k) { var z = new Uint8Array(16), x = new Uint8Array(64); var u, i; for (i = 0; i < 16; i++) z[i] = 0; for (i = 0; i < 8; i++) z[i] = n[i]; while (b >= 64) { crypto_core_salsa20(x,z,k,sigma); for (i = 0; i < 64; i++) c[cpos+i] = x[i]; u = 1; for (i = 8; i < 16; i++) { u = u + (z[i] & 0xff) | 0; z[i] = u & 0xff; u >>>= 8; } b -= 64; cpos += 64; } if (b > 0) { crypto_core_salsa20(x,z,k,sigma); for (i = 0; i < b; i++) c[cpos+i] = x[i]; } return 0; } function crypto_stream(c,cpos,d,n,k) { var s = new Uint8Array(32); crypto_core_hsalsa20(s,n,k,sigma); var sn = new Uint8Array(8); for (var i = 0; i < 8; i++) sn[i] = n[i+16]; return crypto_stream_salsa20(c,cpos,d,sn,s); } function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { var s = new Uint8Array(32); crypto_core_hsalsa20(s,n,k,sigma); var sn = new Uint8Array(8); for (var i = 0; i < 8; i++) sn[i] = n[i+16]; return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s); } /* * Port of Andrew Moon's Poly1305-donna-16. Public domain. * https://github.com/floodyberry/poly1305-donna */ var poly1305 = function(key) { this.buffer = new Uint8Array(16); this.r = new Uint16Array(10); this.h = new Uint16Array(10); this.pad = new Uint16Array(8); this.leftover = 0; this.fin = 0; var t0, t1, t2, t3, t4, t5, t6, t7; t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff; t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; this.r[5] = ((t4 >>> 1)) & 0x1ffe; t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; this.r[9] = ((t7 >>> 5)) & 0x007f; this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8; this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8; this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8; this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8; this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8; this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8; this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8; this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8; }; poly1305.prototype.blocks = function(m, mpos, bytes) { var hibit = this.fin ? 0 : (1 << 11); var t0, t1, t2, t3, t4, t5, t6, t7, c; var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; var h0 = this.h[0], h1 = this.h[1], h2 = this.h[2], h3 = this.h[3], h4 = this.h[4], h5 = this.h[5], h6 = this.h[6], h7 = this.h[7], h8 = this.h[8], h9 = this.h[9]; var r0 = this.r[0], r1 = this.r[1], r2 = this.r[2], r3 = this.r[3], r4 = this.r[4], r5 = this.r[5], r6 = this.r[6], r7 = this.r[7], r8 = this.r[8], r9 = this.r[9]; while (bytes >= 16) { t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff; t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff; t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff; t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff; t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff; h5 += ((t4 >>> 1)) & 0x1fff; t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff; t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff; t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff; h9 += ((t7 >>> 5)) | hibit; c = 0; d0 = c; d0 += h0 * r0; d0 += h1 * (5 * r9); d0 += h2 * (5 * r8); d0 += h3 * (5 * r7); d0 += h4 * (5 * r6); c = (d0 >>> 13); d0 &= 0x1fff; d0 += h5 * (5 * r5); d0 += h6 * (5 * r4); d0 += h7 * (5 * r3); d0 += h8 * (5 * r2); d0 += h9 * (5 * r1); c += (d0 >>> 13); d0 &= 0x1fff; d1 = c; d1 += h0 * r1; d1 += h1 * r0; d1 += h2 * (5 * r9); d1 += h3 * (5 * r8); d1 += h4 * (5 * r7); c = (d1 >>> 13); d1 &= 0x1fff; d1 += h5 * (5 * r6); d1 += h6 * (5 * r5); d1 += h7 * (5 * r4); d1 += h8 * (5 * r3); d1 += h9 * (5 * r2); c += (d1 >>> 13); d1 &= 0x1fff; d2 = c; d2 += h0 * r2; d2 += h1 * r1; d2 += h2 * r0; d2 += h3 * (5 * r9); d2 += h4 * (5 * r8); c = (d2 >>> 13); d2 &= 0x1fff; d2 += h5 * (5 * r7); d2 += h6 * (5 * r6); d2 += h7 * (5 * r5); d2 += h8 * (5 * r4); d2 += h9 * (5 * r3); c += (d2 >>> 13); d2 &= 0x1fff; d3 = c; d3 += h0 * r3; d3 += h1 * r2; d3 += h2 * r1; d3 += h3 * r0; d3 += h4 * (5 * r9); c = (d3 >>> 13); d3 &= 0x1fff; d3 += h5 * (5 * r8); d3 += h6 * (5 * r7); d3 += h7 * (5 * r6); d3 += h8 * (5 * r5); d3 += h9 * (5 * r4); c += (d3 >>> 13); d3 &= 0x1fff; d4 = c; d4 += h0 * r4; d4 += h1 * r3; d4 += h2 * r2; d4 += h3 * r1; d4 += h4 * r0; c = (d4 >>> 13); d4 &= 0x1fff; d4 += h5 * (5 * r9); d4 += h6 * (5 * r8); d4 += h7 * (5 * r7); d4 += h8 * (5 * r6); d4 += h9 * (5 * r5); c += (d4 >>> 13); d4 &= 0x1fff; d5 = c; d5 += h0 * r5; d5 += h1 * r4; d5 += h2 * r3; d5 += h3 * r2; d5 += h4 * r1; c = (d5 >>> 13); d5 &= 0x1fff; d5 += h5 * r0; d5 += h6 * (5 * r9); d5 += h7 * (5 * r8); d5 += h8 * (5 * r7); d5 += h9 * (5 * r6); c += (d5 >>> 13); d5 &= 0x1fff; d6 = c; d6 += h0 * r6; d6 += h1 * r5; d6 += h2 * r4; d6 += h3 * r3; d6 += h4 * r2; c = (d6 >>> 13); d6 &= 0x1fff; d6 += h5 * r1; d6 += h6 * r0; d6 += h7 * (5 * r9); d6 += h8 * (5 * r8); d6 += h9 * (5 * r7); c += (d6 >>> 13); d6 &= 0x1fff; d7 = c; d7 += h0 * r7; d7 += h1 * r6; d7 += h2 * r5; d7 += h3 * r4; d7 += h4 * r3; c = (d7 >>> 13); d7 &= 0x1fff; d7 += h5 * r2; d7 += h6 * r1; d7 += h7 * r0; d7 += h8 * (5 * r9); d7 += h9 * (5 * r8); c += (d7 >>> 13); d7 &= 0x1fff; d8 = c; d8 += h0 * r8; d8 += h1 * r7; d8 += h2 * r6; d8 += h3 * r5; d8 += h4 * r4; c = (d8 >>> 13); d8 &= 0x1fff; d8 += h5 * r3; d8 += h6 * r2; d8 += h7 * r1; d8 += h8 * r0; d8 += h9 * (5 * r9); c += (d8 >>> 13); d8 &= 0x1fff; d9 = c; d9 += h0 * r9; d9 += h1 * r8; d9 += h2 * r7; d9 += h3 * r6; d9 += h4 * r5; c = (d9 >>> 13); d9 &= 0x1fff; d9 += h5 * r4; d9 += h6 * r3; d9 += h7 * r2; d9 += h8 * r1; d9 += h9 * r0; c += (d9 >>> 13); d9 &= 0x1fff; c = (((c << 2) + c)) | 0; c = (c + d0) | 0; d0 = c & 0x1fff; c = (c >>> 13); d1 += c; h0 = d0; h1 = d1; h2 = d2; h3 = d3; h4 = d4; h5 = d5; h6 = d6; h7 = d7; h8 = d8; h9 = d9; mpos += 16; bytes -= 16; } this.h[0] = h0; this.h[1] = h1; this.h[2] = h2; this.h[3] = h3; this.h[4] = h4; this.h[5] = h5; this.h[6] = h6; this.h[7] = h7; this.h[8] = h8; this.h[9] = h9; }; poly1305.prototype.finish = function(mac, macpos) { var g = new Uint16Array(10); var c, mask, f, i; if (this.leftover) { i = this.leftover; this.buffer[i++] = 1; for (; i < 16; i++) this.buffer[i] = 0; this.fin = 1; this.blocks(this.buffer, 0, 16); } c = this.h[1] >>> 13; this.h[1] &= 0x1fff; for (i = 2; i < 10; i++) { this.h[i] += c; c = this.h[i] >>> 13; this.h[i] &= 0x1fff; } this.h[0] += (c * 5); c = this.h[0] >>> 13; this.h[0] &= 0x1fff; this.h[1] += c; c = this.h[1] >>> 13; this.h[1] &= 0x1fff; this.h[2] += c; g[0] = this.h[0] + 5; c = g[0] >>> 13; g[0] &= 0x1fff; for (i = 1; i < 10; i++) { g[i] = this.h[i] + c; c = g[i] >>> 13; g[i] &= 0x1fff; } g[9] -= (1 << 13); mask = (c ^ 1) - 1; for (i = 0; i < 10; i++) g[i] &= mask; mask = ~mask; for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i]; this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff; this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff; this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff; this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff; this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff; this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff; this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff; this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff; f = this.h[0] + this.pad[0]; this.h[0] = f & 0xffff; for (i = 1; i < 8; i++) { f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0; this.h[i] = f & 0xffff; } mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff; mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff; mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff; mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff; mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff; mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff; mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff; mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff; mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff; mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff; mac[macpos+10] = (this.h[5] >>> 0) & 0xff; mac[macpos+11] = (this.h[5] >>> 8) & 0xff; mac[macpos+12] = (this.h[6] >>> 0) & 0xff; mac[macpos+13] = (this.h[6] >>> 8) & 0xff; mac[macpos+14] = (this.h[7] >>> 0) & 0xff; mac[macpos+15] = (this.h[7] >>> 8) & 0xff; }; poly1305.prototype.update = function(m, mpos, bytes) { var i, want; if (this.leftover) { want = (16 - this.leftover); if (want > bytes) want = bytes; for (i = 0; i < want; i++) this.buffer[this.leftover + i] = m[mpos+i]; bytes -= want; mpos += want; this.leftover += want; if (this.leftover < 16) return; this.blocks(this.buffer, 0, 16); this.leftover = 0; } if (bytes >= 16) { want = bytes - (bytes % 16); this.blocks(m, mpos, want); mpos += want; bytes -= want; } if (bytes) { for (i = 0; i < bytes; i++) this.buffer[this.leftover + i] = m[mpos+i]; this.leftover += bytes; } }; function crypto_onetimeauth(out, outpos, m, mpos, n, k) { var s = new poly1305(k); s.update(m, mpos, n); s.finish(out, outpos); return 0; } function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { var x = new Uint8Array(16); crypto_onetimeauth(x,0,m,mpos,n,k); return crypto_verify_16(h,hpos,x,0); } function crypto_secretbox(c,m,d,n,k) { var i; if (d < 32) return -1; crypto_stream_xor(c,0,m,0,d,n,k); crypto_onetimeauth(c, 16, c, 32, d - 32, c); for (i = 0; i < 16; i++) c[i] = 0; return 0; } function crypto_secretbox_open(m,c,d,n,k) { var i; var x = new Uint8Array(32); if (d < 32) return -1; crypto_stream(x,0,32,n,k); if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1; crypto_stream_xor(m,0,c,0,d,n,k); for (i = 0; i < 32; i++) m[i] = 0; return 0; } function set25519(r, a) { var i; for (i = 0; i < 16; i++) r[i] = a[i]|0; } function car25519(o) { var i, v, c = 1; for (i = 0; i < 16; i++) { v = o[i] + c + 65535; c = Math.floor(v / 65536); o[i] = v - c * 65536; } o[0] += c-1 + 37 * (c-1); } function sel25519(p, q, b) { var t, c = ~(b-1); for (var i = 0; i < 16; i++) { t = c & (p[i] ^ q[i]); p[i] ^= t; q[i] ^= t; } } function pack25519(o, n) { var i, j, b; var m = gf(), t = gf(); for (i = 0; i < 16; i++) t[i] = n[i]; car25519(t); car25519(t); car25519(t); for (j = 0; j < 2; j++) { m[0] = t[0] - 0xffed; for (i = 1; i < 15; i++) { m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); m[i-1] &= 0xffff; } m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); b = (m[15]>>16) & 1; m[14] &= 0xffff; sel25519(t, m, 1-b); } for (i = 0; i < 16; i++) { o[2*i] = t[i] & 0xff; o[2*i+1] = t[i]>>8; } } function neq25519(a, b) { var c = new Uint8Array(32), d = new Uint8Array(32); pack25519(c, a); pack25519(d, b); return crypto_verify_32(c, 0, d, 0); } function par25519(a) { var d = new Uint8Array(32); pack25519(d, a); return d[0] & 1; } function unpack25519(o, n) { var i; for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); o[15] &= 0x7fff; } function A(o, a, b) { for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; } function Z(o, a, b) { for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; } function M(o, a, b) { var v, c, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7], b8 = b[8], b9 = b[9], b10 = b[10], b11 = b[11], b12 = b[12], b13 = b[13], b14 = b[14], b15 = b[15]; v = a[0]; t0 += v * b0; t1 += v * b1; t2 += v * b2; t3 += v * b3; t4 += v * b4; t5 += v * b5; t6 += v * b6; t7 += v * b7; t8 += v * b8; t9 += v * b9; t10 += v * b10; t11 += v * b11; t12 += v * b12; t13 += v * b13; t14 += v * b14; t15 += v * b15; v = a[1]; t1 += v * b0; t2 += v * b1; t3 += v * b2; t4 += v * b3; t5 += v * b4; t6 += v * b5; t7 += v * b6; t8 += v * b7; t9 += v * b8; t10 += v * b9; t11 += v * b10; t12 += v * b11; t13 += v * b12; t14 += v * b13; t15 += v * b14; t16 += v * b15; v = a[2]; t2 += v * b0; t3 += v * b1; t4 += v * b2; t5 += v * b3; t6 += v * b4; t7 += v * b5; t8 += v * b6; t9 += v * b7; t10 += v * b8; t11 += v * b9; t12 += v * b10; t13 += v * b11; t14 += v * b12; t15 += v * b13; t16 += v * b14; t17 += v * b15; v = a[3]; t3 += v * b0; t4 += v * b1; t5 += v * b2; t6 += v * b3; t7 += v * b4; t8 += v * b5; t9 += v * b6; t10 += v * b7; t11 += v * b8; t12 += v * b9; t13 += v * b10; t14 += v * b11; t15 += v * b12; t16 += v * b13; t17 += v * b14; t18 += v * b15; v = a[4]; t4 += v * b0; t5 += v * b1; t6 += v * b2; t7 += v * b3; t8 += v * b4; t9 += v * b5; t10 += v * b6; t11 += v * b7; t12 += v * b8; t13 += v * b9; t14 += v * b10; t15 += v * b11; t16 += v * b12; t17 += v * b13; t18 += v * b14; t19 += v * b15; v = a[5]; t5 += v * b0; t6 += v * b1; t7 += v * b2; t8 += v * b3; t9 += v * b4; t10 += v * b5; t11 += v * b6; t12 += v * b7; t13 += v * b8; t14 += v * b9; t15 += v * b10; t16 += v * b11; t17 += v * b12; t18 += v * b13; t19 += v * b14; t20 += v * b15; v = a[6]; t6 += v * b0; t7 += v * b1; t8 += v * b2; t9 += v * b3; t10 += v * b4; t11 += v * b5; t12 += v * b6; t13 += v * b7; t14 += v * b8; t15 += v * b9; t16 += v * b10; t17 += v * b11; t18 += v * b12; t19 += v * b13; t20 += v * b14; t21 += v * b15; v = a[7]; t7 += v * b0; t8 += v * b1; t9 += v * b2; t10 += v * b3; t11 += v * b4; t12 += v * b5; t13 += v * b6; t14 += v * b7; t15 += v * b8; t16 += v * b9; t17 += v * b10; t18 += v * b11; t19 += v * b12; t20 += v * b13; t21 += v * b14; t22 += v * b15; v = a[8]; t8 += v * b0; t9 += v * b1; t10 += v * b2; t11 += v * b3; t12 += v * b4; t13 += v * b5; t14 += v * b6; t15 += v * b7; t16 += v * b8; t17 += v * b9; t18 += v * b10; t19 += v * b11; t20 += v * b12; t21 += v * b13; t22 += v * b14; t23 += v * b15; v = a[9]; t9 += v * b0; t10 += v * b1; t11 += v * b2; t12 += v * b3; t13 += v * b4; t14 += v * b5; t15 += v * b6; t16 += v * b7; t17 += v * b8; t18 += v * b9; t19 += v * b10; t20 += v * b11; t21 += v * b12; t22 += v * b13; t23 += v * b14; t24 += v * b15; v = a[10]; t10 += v * b0; t11 += v * b1; t12 += v * b2; t13 += v * b3; t14 += v * b4; t15 += v * b5; t16 += v * b6; t17 += v * b7; t18 += v * b8; t19 += v * b9; t20 += v * b10; t21 += v * b11; t22 += v * b12; t23 += v * b13; t24 += v * b14; t25 += v * b15; v = a[11]; t11 += v * b0; t12 += v * b1; t13 += v * b2; t14 += v * b3; t15 += v * b4; t16 += v * b5; t17 += v * b6; t18 += v * b7; t19 += v * b8; t20 += v * b9; t21 += v * b10; t22 += v * b11; t23 += v * b12; t24 += v * b13; t25 += v * b14; t26 += v * b15; v = a[12]; t12 += v * b0; t13 += v * b1; t14 += v * b2; t15 += v * b3; t16 += v * b4; t17 += v * b5; t18 += v * b6; t19 += v * b7; t20 += v * b8; t21 += v * b9; t22 += v * b10; t23 += v * b11; t24 += v * b12; t25 += v * b13; t26 += v * b14; t27 += v * b15; v = a[13]; t13 += v * b0; t14 += v * b1; t15 += v * b2; t16 += v * b3; t17 += v * b4; t18 += v * b5; t19 += v * b6; t20 += v * b7; t21 += v * b8; t22 += v * b9; t23 += v * b10; t24 += v * b11; t25 += v * b12; t26 += v * b13; t27 += v * b14; t28 += v * b15; v = a[14]; t14 += v * b0; t15 += v * b1; t16 += v * b2; t17 += v * b3; t18 += v * b4; t19 += v * b5; t20 += v * b6; t21 += v * b7; t22 += v * b8; t23 += v * b9; t24 += v * b10; t25 += v * b11; t26 += v * b12; t27 += v * b13; t28 += v * b14; t29 += v * b15; v = a[15]; t15 += v * b0; t16 += v * b1; t17 += v * b2; t18 += v * b3; t19 += v * b4; t20 += v * b5; t21 += v * b6; t22 += v * b7; t23 += v * b8; t24 += v * b9; t25 += v * b10; t26 += v * b11; t27 += v * b12; t28 += v * b13; t29 += v * b14; t30 += v * b15; t0 += 38 * t16; t1 += 38 * t17; t2 += 38 * t18; t3 += 38 * t19; t4 += 38 * t20; t5 += 38 * t21; t6 += 38 * t22; t7 += 38 * t23; t8 += 38 * t24; t9 += 38 * t25; t10 += 38 * t26; t11 += 38 * t27; t12 += 38 * t28; t13 += 38 * t29; t14 += 38 * t30; // t15 left as is // first car c = 1; v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; t0 += c-1 + 37 * (c-1); // second car c = 1; v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; t0 += c-1 + 37 * (c-1); o[ 0] = t0; o[ 1] = t1; o[ 2] = t2; o[ 3] = t3; o[ 4] = t4; o[ 5] = t5; o[ 6] = t6; o[ 7] = t7; o[ 8] = t8; o[ 9] = t9; o[10] = t10; o[11] = t11; o[12] = t12; o[13] = t13; o[14] = t14; o[15] = t15; } function S(o, a) { M(o, a, a); } function inv25519(o, i) { var c = gf(); var a; for (a = 0; a < 16; a++) c[a] = i[a]; for (a = 253; a >= 0; a--) { S(c, c); if(a !== 2 && a !== 4) M(c, c, i); } for (a = 0; a < 16; a++) o[a] = c[a]; } function pow2523(o, i) { var c = gf(); var a; for (a = 0; a < 16; a++) c[a] = i[a]; for (a = 250; a >= 0; a--) { S(c, c); if(a !== 1) M(c, c, i); } for (a = 0; a < 16; a++) o[a] = c[a]; } function crypto_scalarmult(q, n, p) { var z = new Uint8Array(32); var x = new Float64Array(80), r, i; var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(); for (i = 0; i < 31; i++) z[i] = n[i]; z[31]=(n[31]&127)|64; z[0]&=248; unpack25519(x,p); for (i = 0; i < 16; i++) { b[i]=x[i]; d[i]=a[i]=c[i]=0; } a[0]=d[0]=1; for (i=254; i>=0; --i) { r=(z[i>>>3]>>>(i&7))&1; sel25519(a,b,r); sel25519(c,d,r); A(e,a,c); Z(a,a,c); A(c,b,d); Z(b,b,d); S(d,e); S(f,a); M(a,c,a); M(c,b,e); A(e,a,c); Z(a,a,c); S(b,a); Z(c,d,f); M(a,c,_121665); A(a,a,d); M(c,c,a); M(a,d,f); M(d,b,x); S(b,e); sel25519(a,b,r); sel25519(c,d,r); } for (i = 0; i < 16; i++) { x[i+16]=a[i]; x[i+32]=c[i]; x[i+48]=b[i]; x[i+64]=d[i]; } var x32 = x.subarray(32); var x16 = x.subarray(16); inv25519(x32,x32); M(x16,x16,x32); pack25519(q,x16); return 0; } function crypto_scalarmult_base(q, n) { return crypto_scalarmult(q, n, _9); } function crypto_box_keypair(y, x) { randombytes(x, 32); return crypto_scalarmult_base(y, x); } function crypto_box_beforenm(k, y, x) { var s = new Uint8Array(32); crypto_scalarmult(s, x, y); return crypto_core_hsalsa20(k, _0, s, sigma); } var crypto_box_afternm = crypto_secretbox; var crypto_box_open_afternm = crypto_secretbox_open; function crypto_box(c, m, d, n, y, x) { var k = new Uint8Array(32); crypto_box_beforenm(k, y, x); return crypto_box_afternm(c, m, d, n, k); } function crypto_box_open(m, c, d, n, y, x) { var k = new Uint8Array(32); crypto_box_beforenm(k, y, x); return crypto_box_open_afternm(m, c, d, n, k); } var K = [ 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 ]; function crypto_hashblocks_hl(hh, hl, m, n) { var wh = new Int32Array(16), wl = new Int32Array(16), bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, th, tl, i, j, h, l, a, b, c, d; var ah0 = hh[0], ah1 = hh[1], ah2 = hh[2], ah3 = hh[3], ah4 = hh[4], ah5 = hh[5], ah6 = hh[6], ah7 = hh[7], al0 = hl[0], al1 = hl[1], al2 = hl[2], al3 = hl[3], al4 = hl[4], al5 = hl[5], al6 = hl[6], al7 = hl[7]; var pos = 0; while (n >= 128) { for (i = 0; i < 16; i++) { j = 8 * i + pos; wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3]; wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7]; } for (i = 0; i < 80; i++) { bh0 = ah0; bh1 = ah1; bh2 = ah2; bh3 = ah3; bh4 = ah4; bh5 = ah5; bh6 = ah6; bh7 = ah7; bl0 = al0; bl1 = al1; bl2 = al2; bl3 = al3; bl4 = al4; bl5 = al5; bl6 = al6; bl7 = al7; // add h = ah7; l = al7; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; // Sigma1 h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // Ch h = (ah4 & ah5) ^ (~ah4 & ah6); l = (al4 & al5) ^ (~al4 & al6); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // K h = K[i*2]; l = K[i*2+1]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // w h = wh[i%16]; l = wl[i%16]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; th = c & 0xffff | d << 16; tl = a & 0xffff | b << 16; // add h = th; l = tl; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; // Sigma0 h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // Maj h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; bh7 = (c & 0xffff) | (d << 16); bl7 = (a & 0xffff) | (b << 16); // add h = bh3; l = bl3; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = th; l = tl; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; bh3 = (c & 0xffff) | (d << 16); bl3 = (a & 0xffff) | (b << 16); ah1 = bh0; ah2 = bh1; ah3 = bh2; ah4 = bh3; ah5 = bh4; ah6 = bh5; ah7 = bh6; ah0 = bh7; al1 = bl0; al2 = bl1; al3 = bl2; al4 = bl3; al5 = bl4; al6 = bl5; al7 = bl6; al0 = bl7; if (i%16 === 15) { for (j = 0; j < 16; j++) { // add h = wh[j]; l = wl[j]; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = wh[(j+9)%16]; l = wl[(j+9)%16]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // sigma0 th = wh[(j+1)%16]; tl = wl[(j+1)%16]; h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // sigma1 th = wh[(j+14)%16]; tl = wl[(j+14)%16]; h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; wh[j] = (c & 0xffff) | (d << 16); wl[j] = (a & 0xffff) | (b << 16); } } } // add h = ah0; l = al0; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[0]; l = hl[0]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[0] = ah0 = (c & 0xffff) | (d << 16); hl[0] = al0 = (a & 0xffff) | (b << 16); h = ah1; l = al1; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[1]; l = hl[1]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[1] = ah1 = (c & 0xffff) | (d << 16); hl[1] = al1 = (a & 0xffff) | (b << 16); h = ah2; l = al2; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[2]; l = hl[2]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[2] = ah2 = (c & 0xffff) | (d << 16); hl[2] = al2 = (a & 0xffff) | (b << 16); h = ah3; l = al3; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[3]; l = hl[3]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[3] = ah3 = (c & 0xffff) | (d << 16); hl[3] = al3 = (a & 0xffff) | (b << 16); h = ah4; l = al4; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[4]; l = hl[4]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[4] = ah4 = (c & 0xffff) | (d << 16); hl[4] = al4 = (a & 0xffff) | (b << 16); h = ah5; l = al5; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[5]; l = hl[5]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[5] = ah5 = (c & 0xffff) | (d << 16); hl[5] = al5 = (a & 0xffff) | (b << 16); h = ah6; l = al6; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[6]; l = hl[6]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[6] = ah6 = (c & 0xffff) | (d << 16); hl[6] = al6 = (a & 0xffff) | (b << 16); h = ah7; l = al7; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[7]; l = hl[7]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[7] = ah7 = (c & 0xffff) | (d << 16); hl[7] = al7 = (a & 0xffff) | (b << 16); pos += 128; n -= 128; } return n; } function crypto_hash(out, m, n) { var hh = new Int32Array(8), hl = new Int32Array(8), x = new Uint8Array(256), i, b = n; hh[0] = 0x6a09e667; hh[1] = 0xbb67ae85; hh[2] = 0x3c6ef372; hh[3] = 0xa54ff53a; hh[4] = 0x510e527f; hh[5] = 0x9b05688c; hh[6] = 0x1f83d9ab; hh[7] = 0x5be0cd19; hl[0] = 0xf3bcc908; hl[1] = 0x84caa73b; hl[2] = 0xfe94f82b; hl[3] = 0x5f1d36f1; hl[4] = 0xade682d1; hl[5] = 0x2b3e6c1f; hl[6] = 0xfb41bd6b; hl[7] = 0x137e2179; crypto_hashblocks_hl(hh, hl, m, n); n %= 128; for (i = 0; i < n; i++) x[i] = m[b-n+i]; x[n] = 128; n = 256-128*(n<112?1:0); x[n-9] = 0; ts64(x, n-8, (b / 0x20000000) | 0, b << 3); crypto_hashblocks_hl(hh, hl, x, n); for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); return 0; } function add(p, q) { var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(), g = gf(), h = gf(), t = gf(); Z(a, p[1], p[0]); Z(t, q[1], q[0]); M(a, a, t); A(b, p[0], p[1]); A(t, q[0], q[1]); M(b, b, t); M(c, p[3], q[3]); M(c, c, D2); M(d, p[2], q[2]); A(d, d, d); Z(e, b, a); Z(f, d, c); A(g, d, c); A(h, b, a); M(p[0], e, f); M(p[1], h, g); M(p[2], g, f); M(p[3], e, h); } function cswap(p, q, b) { var i; for (i = 0; i < 4; i++) { sel25519(p[i], q[i], b); } } function pack(r, p) { var tx = gf(), ty = gf(), zi = gf(); inv25519(zi, p[2]); M(tx, p[0], zi); M(ty, p[1], zi); pack25519(r, ty); r[31] ^= par25519(tx) << 7; } function scalarmult(p, q, s) { var b, i; set25519(p[0], gf0); set25519(p[1], gf1); set25519(p[2], gf1); set25519(p[3], gf0); for (i = 255; i >= 0; --i) { b = (s[(i/8)|0] >> (i&7)) & 1; cswap(p, q, b); add(q, p); add(p, p); cswap(p, q, b); } } function scalarbase(p, s) { var q = [gf(), gf(), gf(), gf()]; set25519(q[0], X); set25519(q[1], Y); set25519(q[2], gf1); M(q[3], X, Y); scalarmult(p, q, s); } function crypto_sign_keypair(pk, sk, seeded) { var d = new Uint8Array(64); var p = [gf(), gf(), gf(), gf()]; var i; if (!seeded) randombytes(sk, 32); crypto_hash(d, sk, 32); d[0] &= 248; d[31] &= 127; d[31] |= 64; scalarbase(p, d); pack(pk, p); for (i = 0; i < 32; i++) sk[i+32] = pk[i]; return 0; } var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); function modL(r, x) { var carry, i, j, k; for (i = 63; i >= 32; --i) { carry = 0; for (j = i - 32, k = i - 12; j < k; ++j) { x[j] += carry - 16 * x[i] * L[j - (i - 32)]; carry = (x[j] + 128) >> 8; x[j] -= carry * 256; } x[j] += carry; x[i] = 0; } carry = 0; for (j = 0; j < 32; j++) { x[j] += carry - (x[31] >> 4) * L[j]; carry = x[j] >> 8; x[j] &= 255; } for (j = 0; j < 32; j++) x[j] -= carry * L[j]; for (i = 0; i < 32; i++) { x[i+1] += x[i] >> 8; r[i] = x[i] & 255; } } function reduce(r) { var x = new Float64Array(64), i; for (i = 0; i < 64; i++) x[i] = r[i]; for (i = 0; i < 64; i++) r[i] = 0; modL(r, x); } // Note: difference from C - smlen returned, not passed as argument. function crypto_sign(sm, m, n, sk) { var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); var i, j, x = new Float64Array(64); var p = [gf(), gf(), gf(), gf()]; crypto_hash(d, sk, 32); d[0] &= 248; d[31] &= 127; d[31] |= 64; var smlen = n + 64; for (i = 0; i < n; i++) sm[64 + i] = m[i]; for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; crypto_hash(r, sm.subarray(32), n+32); reduce(r); scalarbase(p, r); pack(sm, p); for (i = 32; i < 64; i++) sm[i] = sk[i]; crypto_hash(h, sm, n + 64); reduce(h); for (i = 0; i < 64; i++) x[i] = 0; for (i = 0; i < 32; i++) x[i] = r[i]; for (i = 0; i < 32; i++) { for (j = 0; j < 32; j++) { x[i+j] += h[i] * d[j]; } } modL(sm.subarray(32), x); return smlen; } function unpackneg(r, p) { var t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf(); set25519(r[2], gf1); unpack25519(r[1], p); S(num, r[1]); M(den, num, D); Z(num, num, r[2]); A(den, r[2], den); S(den2, den); S(den4, den2); M(den6, den4, den2); M(t, den6, num); M(t, t, den); pow2523(t, t); M(t, t, num); M(t, t, den); M(t, t, den); M(r[0], t, den); S(chk, r[0]); M(chk, chk, den); if (neq25519(chk, num)) M(r[0], r[0], I); S(chk, r[0]); M(chk, chk, den); if (neq25519(chk, num)) return -1; if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); M(r[3], r[0], r[1]); return 0; } function crypto_sign_open(m, sm, n, pk) { var i, mlen; var t = new Uint8Array(32), h = new Uint8Array(64); var p = [gf(), gf(), gf(), gf()], q = [gf(), gf(), gf(), gf()]; mlen = -1; if (n < 64) return -1; if (unpackneg(q, pk)) return -1; for (i = 0; i < n; i++) m[i] = sm[i]; for (i = 0; i < 32; i++) m[i+32] = pk[i]; crypto_hash(h, m, n); reduce(h); scalarmult(p, q, h); scalarbase(q, sm.subarray(32)); add(p, q); pack(t, p); n -= 64; if (crypto_verify_32(sm, 0, t, 0)) { for (i = 0; i < n; i++) m[i] = 0; return -1; } for (i = 0; i < n; i++) m[i] = sm[i + 64]; mlen = n; return mlen; } var crypto_secretbox_KEYBYTES = 32, crypto_secretbox_NONCEBYTES = 24, crypto_secretbox_ZEROBYTES = 32, crypto_secretbox_BOXZEROBYTES = 16, crypto_scalarmult_BYTES = 32, crypto_scalarmult_SCALARBYTES = 32, crypto_box_PUBLICKEYBYTES = 32, crypto_box_SECRETKEYBYTES = 32, crypto_box_BEFORENMBYTES = 32, crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, crypto_sign_BYTES = 64, crypto_sign_PUBLICKEYBYTES = 32, crypto_sign_SECRETKEYBYTES = 64, crypto_sign_SEEDBYTES = 32, crypto_hash_BYTES = 64; nacl.lowlevel = { crypto_core_hsalsa20: crypto_core_hsalsa20, crypto_stream_xor: crypto_stream_xor, crypto_stream: crypto_stream, crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, crypto_stream_salsa20: crypto_stream_salsa20, crypto_onetimeauth: crypto_onetimeauth, crypto_onetimeauth_verify: crypto_onetimeauth_verify, crypto_verify_16: crypto_verify_16, crypto_verify_32: crypto_verify_32, crypto_secretbox: crypto_secretbox, crypto_secretbox_open: crypto_secretbox_open, crypto_scalarmult: crypto_scalarmult, crypto_scalarmult_base: crypto_scalarmult_base, crypto_box_beforenm: crypto_box_beforenm, crypto_box_afternm: crypto_box_afternm, crypto_box: crypto_box, crypto_box_open: crypto_box_open, crypto_box_keypair: crypto_box_keypair, crypto_hash: crypto_hash, crypto_sign: crypto_sign, crypto_sign_keypair: crypto_sign_keypair, crypto_sign_open: crypto_sign_open, crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, crypto_sign_BYTES: crypto_sign_BYTES, crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, crypto_hash_BYTES: crypto_hash_BYTES }; /* High-level API */ function checkLengths(k, n) { if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); } function checkBoxLengths(pk, sk) { if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); } function checkArrayTypes() { var t, i; for (i = 0; i < arguments.length; i++) { if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]') throw new TypeError('unexpected type ' + t + ', use Uint8Array'); } } function cleanup(arr) { for (var i = 0; i < arr.length; i++) arr[i] = 0; } // TODO: Completely remove this in v0.15. if (!nacl.util) { nacl.util = {}; nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function() { throw new Error('nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js'); }; } nacl.randomBytes = function(n) { var b = new Uint8Array(n); randombytes(b, n); return b; }; nacl.secretbox = function(msg, nonce, key) { checkArrayTypes(msg, nonce, key); checkLengths(key, nonce); var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); var c = new Uint8Array(m.length); for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i]; crypto_secretbox(c, m, m.length, nonce, key); return c.subarray(crypto_secretbox_BOXZEROBYTES); }; nacl.secretbox.open = function(box, nonce, key) { checkArrayTypes(box, nonce, key); checkLengths(key, nonce); var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); var m = new Uint8Array(c.length); for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; if (c.length < 32) return false; if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false; return m.subarray(crypto_secretbox_ZEROBYTES); }; nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; nacl.scalarMult = function(n, p) { checkArrayTypes(n, p); if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); var q = new Uint8Array(crypto_scalarmult_BYTES); crypto_scalarmult(q, n, p); return q; }; nacl.scalarMult.base = function(n) { checkArrayTypes(n); if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); var q = new Uint8Array(crypto_scalarmult_BYTES); crypto_scalarmult_base(q, n); return q; }; nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; nacl.box = function(msg, nonce, publicKey, secretKey) { var k = nacl.box.before(publicKey, secretKey); return nacl.secretbox(msg, nonce, k); }; nacl.box.before = function(publicKey, secretKey) { checkArrayTypes(publicKey, secretKey); checkBoxLengths(publicKey, secretKey); var k = new Uint8Array(crypto_box_BEFORENMBYTES); crypto_box_beforenm(k, publicKey, secretKey); return k; }; nacl.box.after = nacl.secretbox; nacl.box.open = function(msg, nonce, publicKey, secretKey) { var k = nacl.box.before(publicKey, secretKey); return nacl.secretbox.open(msg, nonce, k); }; nacl.box.open.after = nacl.secretbox.open; nacl.box.keyPair = function() { var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); crypto_box_keypair(pk, sk); return {publicKey: pk, secretKey: sk}; }; nacl.box.keyPair.fromSecretKey = function(secretKey) { checkArrayTypes(secretKey); if (secretKey.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); crypto_scalarmult_base(pk, secretKey); return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; }; nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; nacl.box.nonceLength = crypto_box_NONCEBYTES; nacl.box.overheadLength = nacl.secretbox.overheadLength; nacl.sign = function(msg, secretKey) { checkArrayTypes(msg, secretKey); if (secretKey.length !== crypto_sign_SECRETKEYBYTES) throw new Error('bad secret key size'); var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); crypto_sign(signedMsg, msg, msg.length, secretKey); return signedMsg; }; nacl.sign.open = function(signedMsg, publicKey) { if (arguments.length !== 2) throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?'); checkArrayTypes(signedMsg, publicKey); if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) throw new Error('bad public key size'); var tmp = new Uint8Array(signedMsg.length); var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); if (mlen < 0) return null; var m = new Uint8Array(mlen); for (var i = 0; i < m.length; i++) m[i] = tmp[i]; return m; }; nacl.sign.detached = function(msg, secretKey) { var signedMsg = nacl.sign(msg, secretKey); var sig = new Uint8Array(crypto_sign_BYTES); for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; return sig; }; nacl.sign.detached.verify = function(msg, sig, publicKey) { checkArrayTypes(msg, sig, publicKey); if (sig.length !== crypto_sign_BYTES) throw new Error('bad signature size'); if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) throw new Error('bad public key size'); var sm = new Uint8Array(crypto_sign_BYTES + msg.length); var m = new Uint8Array(crypto_sign_BYTES + msg.length); var i; for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); }; nacl.sign.keyPair = function() { var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); crypto_sign_keypair(pk, sk); return {publicKey: pk, secretKey: sk}; }; nacl.sign.keyPair.fromSecretKey = function(secretKey) { checkArrayTypes(secretKey); if (secretKey.length !== crypto_sign_SECRETKEYBYTES) throw new Error('bad secret key size'); var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; }; nacl.sign.keyPair.fromSeed = function(seed) { checkArrayTypes(seed); if (seed.length !== crypto_sign_SEEDBYTES) throw new Error('bad seed size'); var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); for (var i = 0; i < 32; i++) sk[i] = seed[i]; crypto_sign_keypair(pk, sk, true); return {publicKey: pk, secretKey: sk}; }; nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; nacl.sign.seedLength = crypto_sign_SEEDBYTES; nacl.sign.signatureLength = crypto_sign_BYTES; nacl.hash = function(msg) { checkArrayTypes(msg); var h = new Uint8Array(crypto_hash_BYTES); crypto_hash(h, msg, msg.length); return h; }; nacl.hash.hashLength = crypto_hash_BYTES; nacl.verify = function(x, y) { checkArrayTypes(x, y); // Zero length arguments are considered not equal. if (x.length === 0 || y.length === 0) return false; if (x.length !== y.length) return false; return (vn(x, 0, y, 0, x.length) === 0) ? true : false; }; nacl.setPRNG = function(fn) { randombytes = fn; }; (function() { // Initialize PRNG if environment provides CSPRNG. // If not, methods calling randombytes will throw. var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; if (crypto && crypto.getRandomValues) { // Browsers. var QUOTA = 65536; nacl.setPRNG(function(x, n) { var i, v = new Uint8Array(n); for (i = 0; i < n; i += QUOTA) { crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); } for (i = 0; i < n; i++) x[i] = v[i]; cleanup(v); }); } else if (true) { // Node.js. crypto = __webpack_require__(6113); if (crypto && crypto.randomBytes) { nacl.setPRNG(function(x, n) { var i, v = crypto.randomBytes(n); for (i = 0; i < n; i++) x[i] = v[i]; cleanup(v); }); } } })(); })( true && module.exports ? module.exports : (self.nacl = self.nacl || {})); /***/ }), /***/ 85287: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { /** * upath http://github.com/anodynos/upath/ * * A proxy to `path`, replacing `\` with `/` for all results (supports UNC paths) & new methods to normalize & join keeping leading `./` and add, change, default, trim file extensions. * Version 2.0.1 - Compiled on 2020-11-07 16:59:47 * Repository git://github.com/anodynos/upath * Copyright(c) 2020 Angelos Pikoulas * License MIT */ // Generated by uRequire v0.7.0-beta.33 target: 'lib' template: 'nodejs' var VERSION = '2.0.1'; // injected by urequire-rc-inject-version var extraFn, extraFunctions, isFunction, isString, isValidExt, name, path, propName, propValue, toUnix, upath, slice = [].slice, indexOf = [].indexOf || function (item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }, hasProp = {}.hasOwnProperty; path = __webpack_require__(71017); isFunction = function (val) { return typeof val === "function"; }; isString = function (val) { return typeof val === "string" || !!val && typeof val === "object" && Object.prototype.toString.call(val) === "[object String]"; }; upath = exports; upath.VERSION = typeof VERSION !== "undefined" && VERSION !== null ? VERSION : "NO-VERSION"; toUnix = function (p) { p = p.replace(/\\/g, "/"); p = p.replace(/(? 0) { p0 = toUnix(p[0]); if (p0.startsWith("./") && !result.startsWith("./") && !result.startsWith("..")) { result = "./" + result; } else if (p0.startsWith("//") && !result.startsWith("//")) { if (p0.startsWith("//./")) { result = "//." + result; } else { result = "/" + result; } } } return result; }, addExt: function (file, ext) { if (!ext) { return file; } else { if (ext[0] !== ".") { ext = "." + ext; } return file + (file.endsWith(ext) ? "" : ext); } }, trimExt: function (filename, ignoreExts, maxSize) { var oldExt; if (maxSize == null) { maxSize = 7; } oldExt = upath.extname(filename); if (isValidExt(oldExt, ignoreExts, maxSize)) { return filename.slice(0, +(filename.length - oldExt.length - 1) + 1 || 9000000000); } else { return filename; } }, removeExt: function (filename, ext) { if (!ext) { return filename; } else { ext = ext[0] === "." ? ext : "." + ext; if (upath.extname(filename) === ext) { return upath.trimExt(filename, [], ext.length); } else { return filename; } } }, changeExt: function (filename, ext, ignoreExts, maxSize) { if (maxSize == null) { maxSize = 7; } return upath.trimExt(filename, ignoreExts, maxSize) + (!ext ? "" : ext[0] === "." ? ext : "." + ext); }, defaultExt: function (filename, ext, ignoreExts, maxSize) { var oldExt; if (maxSize == null) { maxSize = 7; } oldExt = upath.extname(filename); if (isValidExt(oldExt, ignoreExts, maxSize)) { return filename; } else { return upath.addExt(filename, ext); } } }; isValidExt = function (ext, ignoreExts, maxSize) { if (ignoreExts == null) { ignoreExts = []; } return ext && ext.length <= maxSize && indexOf.call(ignoreExts.map(function (e) { return (e && e[0] !== "." ? "." : "") + e; }), ext) < 0; }; for (name in extraFunctions) { if (!hasProp.call(extraFunctions, name)) continue; extraFn = extraFunctions[name]; if (upath[name] !== void 0) { throw new Error("path." + name + " already exists."); } else { upath[name] = extraFn; } } ; /***/ }), /***/ 26988: /***/ ((module) => { module.exports = read var MSB = 0x80 , REST = 0x7F function read(buf, offset) { var res = 0 , offset = offset || 0 , shift = 0 , counter = offset , b , l = buf.length do { if (counter >= l || shift > 49) { read.bytes = 0 throw new RangeError('Could not decode varint') } b = buf[counter++] res += shift < 28 ? (b & REST) << shift : (b & REST) * Math.pow(2, shift) shift += 7 } while (b >= MSB) read.bytes = counter - offset return res } /***/ }), /***/ 1312: /***/ ((module) => { module.exports = encode var MSB = 0x80 , REST = 0x7F , MSBALL = ~REST , INT = Math.pow(2, 31) function encode(num, out, offset) { if (Number.MAX_SAFE_INTEGER && num > Number.MAX_SAFE_INTEGER) { encode.bytes = 0 throw new RangeError('Could not encode varint') } out = out || [] offset = offset || 0 var oldOffset = offset while(num >= INT) { out[offset++] = (num & 0xFF) | MSB num /= 128 } while(num & MSBALL) { out[offset++] = (num & 0xFF) | MSB num >>>= 7 } out[offset] = num | 0 encode.bytes = offset - oldOffset + 1 return out } /***/ }), /***/ 94676: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = { encode: __webpack_require__(1312) , decode: __webpack_require__(26988) , encodingLength: __webpack_require__(10082) } /***/ }), /***/ 10082: /***/ ((module) => { var N1 = Math.pow(2, 7) var N2 = Math.pow(2, 14) var N3 = Math.pow(2, 21) var N4 = Math.pow(2, 28) var N5 = Math.pow(2, 35) var N6 = Math.pow(2, 42) var N7 = Math.pow(2, 49) var N8 = Math.pow(2, 56) var N9 = Math.pow(2, 63) module.exports = function (value) { return ( value < N1 ? 1 : value < N2 ? 2 : value < N3 ? 3 : value < N4 ? 4 : value < N5 ? 5 : value < N6 ? 6 : value < N7 ? 7 : value < N8 ? 8 : value < N9 ? 9 : 10 ) } /***/ }), /***/ 46613: /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; (function (factory) { if ( true && typeof module.exports === "object") { var v = factory(__webpack_require__(72469), exports); if (v !== undefined) module.exports = v; } else if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__, exports], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } })(function (require, exports) { /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.TextDocument = void 0; var FullTextDocument = /** @class */ (function () { function FullTextDocument(uri, languageId, version, content) { this._uri = uri; this._languageId = languageId; this._version = version; this._content = content; this._lineOffsets = undefined; } Object.defineProperty(FullTextDocument.prototype, "uri", { get: function () { return this._uri; }, enumerable: false, configurable: true }); Object.defineProperty(FullTextDocument.prototype, "languageId", { get: function () { return this._languageId; }, enumerable: false, configurable: true }); Object.defineProperty(FullTextDocument.prototype, "version", { get: function () { return this._version; }, enumerable: false, configurable: true }); FullTextDocument.prototype.getText = function (range) { if (range) { var start = this.offsetAt(range.start); var end = this.offsetAt(range.end); return this._content.substring(start, end); } return this._content; }; FullTextDocument.prototype.update = function (changes, version) { for (var _i = 0, changes_1 = changes; _i < changes_1.length; _i++) { var change = changes_1[_i]; if (FullTextDocument.isIncremental(change)) { // makes sure start is before end var range = getWellformedRange(change.range); // update content var startOffset = this.offsetAt(range.start); var endOffset = this.offsetAt(range.end); this._content = this._content.substring(0, startOffset) + change.text + this._content.substring(endOffset, this._content.length); // update the offsets var startLine = Math.max(range.start.line, 0); var endLine = Math.max(range.end.line, 0); var lineOffsets = this._lineOffsets; var addedLineOffsets = computeLineOffsets(change.text, false, startOffset); if (endLine - startLine === addedLineOffsets.length) { for (var i = 0, len = addedLineOffsets.length; i < len; i++) { lineOffsets[i + startLine + 1] = addedLineOffsets[i]; } } else { if (addedLineOffsets.length < 10000) { lineOffsets.splice.apply(lineOffsets, __spreadArray([startLine + 1, endLine - startLine], addedLineOffsets, false)); } else { // avoid too many arguments for splice this._lineOffsets = lineOffsets = lineOffsets.slice(0, startLine + 1).concat(addedLineOffsets, lineOffsets.slice(endLine + 1)); } } var diff = change.text.length - (endOffset - startOffset); if (diff !== 0) { for (var i = startLine + 1 + addedLineOffsets.length, len = lineOffsets.length; i < len; i++) { lineOffsets[i] = lineOffsets[i] + diff; } } } else if (FullTextDocument.isFull(change)) { this._content = change.text; this._lineOffsets = undefined; } else { throw new Error('Unknown change event received'); } } this._version = version; }; FullTextDocument.prototype.getLineOffsets = function () { if (this._lineOffsets === undefined) { this._lineOffsets = computeLineOffsets(this._content, true); } return this._lineOffsets; }; FullTextDocument.prototype.positionAt = function (offset) { offset = Math.max(Math.min(offset, this._content.length), 0); var lineOffsets = this.getLineOffsets(); var low = 0, high = lineOffsets.length; if (high === 0) { return { line: 0, character: offset }; } while (low < high) { var mid = Math.floor((low + high) / 2); if (lineOffsets[mid] > offset) { high = mid; } else { low = mid + 1; } } // low is the least x for which the line offset is larger than the current offset // or array.length if no line offset is larger than the current offset var line = low - 1; return { line: line, character: offset - lineOffsets[line] }; }; FullTextDocument.prototype.offsetAt = function (position) { var lineOffsets = this.getLineOffsets(); if (position.line >= lineOffsets.length) { return this._content.length; } else if (position.line < 0) { return 0; } var lineOffset = lineOffsets[position.line]; var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length; return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset); }; Object.defineProperty(FullTextDocument.prototype, "lineCount", { get: function () { return this.getLineOffsets().length; }, enumerable: false, configurable: true }); FullTextDocument.isIncremental = function (event) { var candidate = event; return candidate !== undefined && candidate !== null && typeof candidate.text === 'string' && candidate.range !== undefined && (candidate.rangeLength === undefined || typeof candidate.rangeLength === 'number'); }; FullTextDocument.isFull = function (event) { var candidate = event; return candidate !== undefined && candidate !== null && typeof candidate.text === 'string' && candidate.range === undefined && candidate.rangeLength === undefined; }; return FullTextDocument; }()); var TextDocument; (function (TextDocument) { /** * Creates a new text document. * * @param uri The document's uri. * @param languageId The document's language Id. * @param version The document's initial version number. * @param content The document's content. */ function create(uri, languageId, version, content) { return new FullTextDocument(uri, languageId, version, content); } TextDocument.create = create; /** * Updates a TextDocument by modifying its content. * * @param document the document to update. Only documents created by TextDocument.create are valid inputs. * @param changes the changes to apply to the document. * @param version the changes version for the document. * @returns The updated TextDocument. Note: That's the same document instance passed in as first parameter. * */ function update(document, changes, version) { if (document instanceof FullTextDocument) { document.update(changes, version); return document; } else { throw new Error('TextDocument.update: document must be created by TextDocument.create'); } } TextDocument.update = update; function applyEdits(document, edits) { var text = document.getText(); var sortedEdits = mergeSort(edits.map(getWellformedEdit), function (a, b) { var diff = a.range.start.line - b.range.start.line; if (diff === 0) { return a.range.start.character - b.range.start.character; } return diff; }); var lastModifiedOffset = 0; var spans = []; for (var _i = 0, sortedEdits_1 = sortedEdits; _i < sortedEdits_1.length; _i++) { var e = sortedEdits_1[_i]; var startOffset = document.offsetAt(e.range.start); if (startOffset < lastModifiedOffset) { throw new Error('Overlapping edit'); } else if (startOffset > lastModifiedOffset) { spans.push(text.substring(lastModifiedOffset, startOffset)); } if (e.newText.length) { spans.push(e.newText); } lastModifiedOffset = document.offsetAt(e.range.end); } spans.push(text.substr(lastModifiedOffset)); return spans.join(''); } TextDocument.applyEdits = applyEdits; })(TextDocument || (exports.TextDocument = TextDocument = {})); function mergeSort(data, compare) { if (data.length <= 1) { // sorted return data; } var p = (data.length / 2) | 0; var left = data.slice(0, p); var right = data.slice(p); mergeSort(left, compare); mergeSort(right, compare); var leftIdx = 0; var rightIdx = 0; var i = 0; while (leftIdx < left.length && rightIdx < right.length) { var ret = compare(left[leftIdx], right[rightIdx]); if (ret <= 0) { // smaller_equal -> take left to preserve order data[i++] = left[leftIdx++]; } else { // greater -> take right data[i++] = right[rightIdx++]; } } while (leftIdx < left.length) { data[i++] = left[leftIdx++]; } while (rightIdx < right.length) { data[i++] = right[rightIdx++]; } return data; } function computeLineOffsets(text, isAtLineStart, textOffset) { if (textOffset === void 0) { textOffset = 0; } var result = isAtLineStart ? [textOffset] : []; for (var i = 0; i < text.length; i++) { var ch = text.charCodeAt(i); if (ch === 13 /* CharCode.CarriageReturn */ || ch === 10 /* CharCode.LineFeed */) { if (ch === 13 /* CharCode.CarriageReturn */ && i + 1 < text.length && text.charCodeAt(i + 1) === 10 /* CharCode.LineFeed */) { i++; } result.push(textOffset + i + 1); } } return result; } function getWellformedRange(range) { var start = range.start; var end = range.end; if (start.line > end.line || (start.line === end.line && start.character > end.character)) { return { start: end, end: start }; } return range; } function getWellformedEdit(textEdit) { var range = getWellformedRange(textEdit.range); if (range !== textEdit.range) { return { newText: textEdit.newText, range: range }; } return textEdit; } }); /***/ }), /***/ 8089: /***/ ((module, exports, __webpack_require__) => { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (factory) { if ( true && typeof module.exports === "object") { var v = factory(__webpack_require__(7492), exports); if (v !== undefined) module.exports = v; } else if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__, exports], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } })(function (require, exports) { /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.TextDocument = exports.EOL = exports.WorkspaceFolder = exports.InlineCompletionContext = exports.SelectedCompletionInfo = exports.InlineCompletionTriggerKind = exports.InlineCompletionList = exports.InlineCompletionItem = exports.StringValue = exports.InlayHint = exports.InlayHintLabelPart = exports.InlayHintKind = exports.InlineValueContext = exports.InlineValueEvaluatableExpression = exports.InlineValueVariableLookup = exports.InlineValueText = exports.SemanticTokens = exports.SemanticTokenModifiers = exports.SemanticTokenTypes = exports.SelectionRange = exports.DocumentLink = exports.FormattingOptions = exports.CodeLens = exports.CodeAction = exports.CodeActionContext = exports.CodeActionTriggerKind = exports.CodeActionKind = exports.DocumentSymbol = exports.WorkspaceSymbol = exports.SymbolInformation = exports.SymbolTag = exports.SymbolKind = exports.DocumentHighlight = exports.DocumentHighlightKind = exports.SignatureInformation = exports.ParameterInformation = exports.Hover = exports.MarkedString = exports.CompletionList = exports.CompletionItem = exports.CompletionItemLabelDetails = exports.InsertTextMode = exports.InsertReplaceEdit = exports.CompletionItemTag = exports.InsertTextFormat = exports.CompletionItemKind = exports.MarkupContent = exports.MarkupKind = exports.TextDocumentItem = exports.OptionalVersionedTextDocumentIdentifier = exports.VersionedTextDocumentIdentifier = exports.TextDocumentIdentifier = exports.WorkspaceChange = exports.WorkspaceEdit = exports.DeleteFile = exports.RenameFile = exports.CreateFile = exports.TextDocumentEdit = exports.AnnotatedTextEdit = exports.ChangeAnnotationIdentifier = exports.ChangeAnnotation = exports.TextEdit = exports.Command = exports.Diagnostic = exports.CodeDescription = exports.DiagnosticTag = exports.DiagnosticSeverity = exports.DiagnosticRelatedInformation = exports.FoldingRange = exports.FoldingRangeKind = exports.ColorPresentation = exports.ColorInformation = exports.Color = exports.LocationLink = exports.Location = exports.Range = exports.Position = exports.uinteger = exports.integer = exports.URI = exports.DocumentUri = void 0; var DocumentUri; (function (DocumentUri) { function is(value) { return typeof value === 'string'; } DocumentUri.is = is; })(DocumentUri || (exports.DocumentUri = DocumentUri = {})); var URI; (function (URI) { function is(value) { return typeof value === 'string'; } URI.is = is; })(URI || (exports.URI = URI = {})); var integer; (function (integer) { integer.MIN_VALUE = -2147483648; integer.MAX_VALUE = 2147483647; function is(value) { return typeof value === 'number' && integer.MIN_VALUE <= value && value <= integer.MAX_VALUE; } integer.is = is; })(integer || (exports.integer = integer = {})); var uinteger; (function (uinteger) { uinteger.MIN_VALUE = 0; uinteger.MAX_VALUE = 2147483647; function is(value) { return typeof value === 'number' && uinteger.MIN_VALUE <= value && value <= uinteger.MAX_VALUE; } uinteger.is = is; })(uinteger || (exports.uinteger = uinteger = {})); /** * The Position namespace provides helper functions to work with * {@link Position} literals. */ var Position; (function (Position) { /** * Creates a new Position literal from the given line and character. * @param line The position's line. * @param character The position's character. */ function create(line, character) { if (line === Number.MAX_VALUE) { line = uinteger.MAX_VALUE; } if (character === Number.MAX_VALUE) { character = uinteger.MAX_VALUE; } return { line: line, character: character }; } Position.create = create; /** * Checks whether the given literal conforms to the {@link Position} interface. */ function is(value) { var candidate = value; return Is.objectLiteral(candidate) && Is.uinteger(candidate.line) && Is.uinteger(candidate.character); } Position.is = is; })(Position || (exports.Position = Position = {})); /** * The Range namespace provides helper functions to work with * {@link Range} literals. */ var Range; (function (Range) { function create(one, two, three, four) { if (Is.uinteger(one) && Is.uinteger(two) && Is.uinteger(three) && Is.uinteger(four)) { return { start: Position.create(one, two), end: Position.create(three, four) }; } else if (Position.is(one) && Position.is(two)) { return { start: one, end: two }; } else { throw new Error("Range#create called with invalid arguments[".concat(one, ", ").concat(two, ", ").concat(three, ", ").concat(four, "]")); } } Range.create = create; /** * Checks whether the given literal conforms to the {@link Range} interface. */ function is(value) { var candidate = value; return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end); } Range.is = is; })(Range || (exports.Range = Range = {})); /** * The Location namespace provides helper functions to work with * {@link Location} literals. */ var Location; (function (Location) { /** * Creates a Location literal. * @param uri The location's uri. * @param range The location's range. */ function create(uri, range) { return { uri: uri, range: range }; } Location.create = create; /** * Checks whether the given literal conforms to the {@link Location} interface. */ function is(value) { var candidate = value; return Is.objectLiteral(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri)); } Location.is = is; })(Location || (exports.Location = Location = {})); /** * The LocationLink namespace provides helper functions to work with * {@link LocationLink} literals. */ var LocationLink; (function (LocationLink) { /** * Creates a LocationLink literal. * @param targetUri The definition's uri. * @param targetRange The full range of the definition. * @param targetSelectionRange The span of the symbol definition at the target. * @param originSelectionRange The span of the symbol being defined in the originating source file. */ function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) { return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange }; } LocationLink.create = create; /** * Checks whether the given literal conforms to the {@link LocationLink} interface. */ function is(value) { var candidate = value; return Is.objectLiteral(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri) && Range.is(candidate.targetSelectionRange) && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange)); } LocationLink.is = is; })(LocationLink || (exports.LocationLink = LocationLink = {})); /** * The Color namespace provides helper functions to work with * {@link Color} literals. */ var Color; (function (Color) { /** * Creates a new Color literal. */ function create(red, green, blue, alpha) { return { red: red, green: green, blue: blue, alpha: alpha, }; } Color.create = create; /** * Checks whether the given literal conforms to the {@link Color} interface. */ function is(value) { var candidate = value; return Is.objectLiteral(candidate) && Is.numberRange(candidate.red, 0, 1) && Is.numberRange(candidate.green, 0, 1) && Is.numberRange(candidate.blue, 0, 1) && Is.numberRange(candidate.alpha, 0, 1); } Color.is = is; })(Color || (exports.Color = Color = {})); /** * The ColorInformation namespace provides helper functions to work with * {@link ColorInformation} literals. */ var ColorInformation; (function (ColorInformation) { /** * Creates a new ColorInformation literal. */ function create(range, color) { return { range: range, color: color, }; } ColorInformation.create = create; /** * Checks whether the given literal conforms to the {@link ColorInformation} interface. */ function is(value) { var candidate = value; return Is.objectLiteral(candidate) && Range.is(candidate.range) && Color.is(candidate.color); } ColorInformation.is = is; })(ColorInformation || (exports.ColorInformation = ColorInformation = {})); /** * The Color namespace provides helper functions to work with * {@link ColorPresentation} literals. */ var ColorPresentation; (function (ColorPresentation) { /** * Creates a new ColorInformation literal. */ function create(label, textEdit, additionalTextEdits) { return { label: label, textEdit: textEdit, additionalTextEdits: additionalTextEdits, }; } ColorPresentation.create = create; /** * Checks whether the given literal conforms to the {@link ColorInformation} interface. */ function is(value) { var candidate = value; return Is.objectLiteral(candidate) && Is.string(candidate.label) && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate)) && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is)); } ColorPresentation.is = is; })(ColorPresentation || (exports.ColorPresentation = ColorPresentation = {})); /** * A set of predefined range kinds. */ var FoldingRangeKind; (function (FoldingRangeKind) { /** * Folding range for a comment */ FoldingRangeKind.Comment = 'comment'; /** * Folding range for an import or include */ FoldingRangeKind.Imports = 'imports'; /** * Folding range for a region (e.g. `#region`) */ FoldingRangeKind.Region = 'region'; })(FoldingRangeKind || (exports.FoldingRangeKind = FoldingRangeKind = {})); /** * The folding range namespace provides helper functions to work with * {@link FoldingRange} literals. */ var FoldingRange; (function (FoldingRange) { /** * Creates a new FoldingRange literal. */ function create(startLine, endLine, startCharacter, endCharacter, kind, collapsedText) { var result = { startLine: startLine, endLine: endLine }; if (Is.defined(startCharacter)) { result.startCharacter = startCharacter; } if (Is.defined(endCharacter)) { result.endCharacter = endCharacter; } if (Is.defined(kind)) { result.kind = kind; } if (Is.defined(collapsedText)) { result.collapsedText = collapsedText; } return result; } FoldingRange.create = create; /** * Checks whether the given literal conforms to the {@link FoldingRange} interface. */ function is(value) { var candidate = value; return Is.objectLiteral(candidate) && Is.uinteger(candidate.startLine) && Is.uinteger(candidate.startLine) && (Is.undefined(candidate.startCharacter) || Is.uinteger(candidate.startCharacter)) && (Is.undefined(candidate.endCharacter) || Is.uinteger(candidate.endCharacter)) && (Is.undefined(candidate.kind) || Is.string(candidate.kind)); } FoldingRange.is = is; })(FoldingRange || (exports.FoldingRange = FoldingRange = {})); /** * The DiagnosticRelatedInformation namespace provides helper functions to work with * {@link DiagnosticRelatedInformation} literals. */ var DiagnosticRelatedInformation; (function (DiagnosticRelatedInformation) { /** * Creates a new DiagnosticRelatedInformation literal. */ function create(location, message) { return { location: location, message: message }; } DiagnosticRelatedInformation.create = create; /** * Checks whether the given literal conforms to the {@link DiagnosticRelatedInformation} interface. */ function is(value) { var candidate = value; return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message); } DiagnosticRelatedInformation.is = is; })(DiagnosticRelatedInformation || (exports.DiagnosticRelatedInformation = DiagnosticRelatedInformation = {})); /** * The diagnostic's severity. */ var DiagnosticSeverity; (function (DiagnosticSeverity) { /** * Reports an error. */ DiagnosticSeverity.Error = 1; /** * Reports a warning. */ DiagnosticSeverity.Warning = 2; /** * Reports an information. */ DiagnosticSeverity.Information = 3; /** * Reports a hint. */ DiagnosticSeverity.Hint = 4; })(DiagnosticSeverity || (exports.DiagnosticSeverity = DiagnosticSeverity = {})); /** * The diagnostic tags. * * @since 3.15.0 */ var DiagnosticTag; (function (DiagnosticTag) { /** * Unused or unnecessary code. * * Clients are allowed to render diagnostics with this tag faded out instead of having * an error squiggle. */ DiagnosticTag.Unnecessary = 1; /** * Deprecated or obsolete code. * * Clients are allowed to rendered diagnostics with this tag strike through. */ DiagnosticTag.Deprecated = 2; })(DiagnosticTag || (exports.DiagnosticTag = DiagnosticTag = {})); /** * The CodeDescription namespace provides functions to deal with descriptions for diagnostic codes. * * @since 3.16.0 */ var CodeDescription; (function (CodeDescription) { function is(value) { var candidate = value; return Is.objectLiteral(candidate) && Is.string(candidate.href); } CodeDescription.is = is; })(CodeDescription || (exports.CodeDescription = CodeDescription = {})); /** * The Diagnostic namespace provides helper functions to work with * {@link Diagnostic} literals. */ var Diagnostic; (function (Diagnostic) { /** * Creates a new Diagnostic literal. */ function create(range, message, severity, code, source, relatedInformation) { var result = { range: range, message: message }; if (Is.defined(severity)) { result.severity = severity; } if (Is.defined(code)) { result.code = code; } if (Is.defined(source)) { result.source = source; } if (Is.defined(relatedInformation)) { result.relatedInformation = relatedInformation; } return result; } Diagnostic.create = create; /** * Checks whether the given literal conforms to the {@link Diagnostic} interface. */ function is(value) { var _a; var candidate = value; return Is.defined(candidate) && Range.is(candidate.range) && Is.string(candidate.message) && (Is.number(candidate.severity) || Is.undefined(candidate.severity)) && (Is.integer(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code)) && (Is.undefined(candidate.codeDescription) || (Is.string((_a = candidate.codeDescription) === null || _a === void 0 ? void 0 : _a.href))) && (Is.string(candidate.source) || Is.undefined(candidate.source)) && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is)); } Diagnostic.is = is; })(Diagnostic || (exports.Diagnostic = Diagnostic = {})); /** * The Command namespace provides helper functions to work with * {@link Command} literals. */ var Command; (function (Command) { /** * Creates a new Command literal. */ function create(title, command) { var args = []; for (var _i = 2; _i < arguments.length; _i++) { args[_i - 2] = arguments[_i]; } var result = { title: title, command: command }; if (Is.defined(args) && args.length > 0) { result.arguments = args; } return result; } Command.create = create; /** * Checks whether the given literal conforms to the {@link Command} interface. */ function is(value) { var candidate = value; return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command); } Command.is = is; })(Command || (exports.Command = Command = {})); /** * The TextEdit namespace provides helper function to create replace, * insert and delete edits more easily. */ var TextEdit; (function (TextEdit) { /** * Creates a replace text edit. * @param range The range of text to be replaced. * @param newText The new text. */ function replace(range, newText) { return { range: range, newText: newText }; } TextEdit.replace = replace; /** * Creates an insert text edit. * @param position The position to insert the text at. * @param newText The text to be inserted. */ function insert(position, newText) { return { range: { start: position, end: position }, newText: newText }; } TextEdit.insert = insert; /** * Creates a delete text edit. * @param range The range of text to be deleted. */ function del(range) { return { range: range, newText: '' }; } TextEdit.del = del; function is(value) { var candidate = value; return Is.objectLiteral(candidate) && Is.string(candidate.newText) && Range.is(candidate.range); } TextEdit.is = is; })(TextEdit || (exports.TextEdit = TextEdit = {})); var ChangeAnnotation; (function (ChangeAnnotation) { function create(label, needsConfirmation, description) { var result = { label: label }; if (needsConfirmation !== undefined) { result.needsConfirmation = needsConfirmation; } if (description !== undefined) { result.description = description; } return result; } ChangeAnnotation.create = create; function is(value) { var candidate = value; return Is.objectLiteral(candidate) && Is.string(candidate.label) && (Is.boolean(candidate.needsConfirmation) || candidate.needsConfirmation === undefined) && (Is.string(candidate.description) || candidate.description === undefined); } ChangeAnnotation.is = is; })(ChangeAnnotation || (exports.ChangeAnnotation = ChangeAnnotation = {})); var ChangeAnnotationIdentifier; (function (ChangeAnnotationIdentifier) { function is(value) { var candidate = value; return Is.string(candidate); } ChangeAnnotationIdentifier.is = is; })(ChangeAnnotationIdentifier || (exports.ChangeAnnotationIdentifier = ChangeAnnotationIdentifier = {})); var AnnotatedTextEdit; (function (AnnotatedTextEdit) { /** * Creates an annotated replace text edit. * * @param range The range of text to be replaced. * @param newText The new text. * @param annotation The annotation. */ function replace(range, newText, annotation) { return { range: range, newText: newText, annotationId: annotation }; } AnnotatedTextEdit.replace = replace; /** * Creates an annotated insert text edit. * * @param position The position to insert the text at. * @param newText The text to be inserted. * @param annotation The annotation. */ function insert(position, newText, annotation) { return { range: { start: position, end: position }, newText: newText, annotationId: annotation }; } AnnotatedTextEdit.insert = insert; /** * Creates an annotated delete text edit. * * @param range The range of text to be deleted. * @param annotation The annotation. */ function del(range, annotation) { return { range: range, newText: '', annotationId: annotation }; } AnnotatedTextEdit.del = del; function is(value) { var candidate = value; return TextEdit.is(candidate) && (ChangeAnnotation.is(candidate.annotationId) || ChangeAnnotationIdentifier.is(candidate.annotationId)); } AnnotatedTextEdit.is = is; })(AnnotatedTextEdit || (exports.AnnotatedTextEdit = AnnotatedTextEdit = {})); /** * The TextDocumentEdit namespace provides helper function to create * an edit that manipulates a text document. */ var TextDocumentEdit; (function (TextDocumentEdit) { /** * Creates a new `TextDocumentEdit` */ function create(textDocument, edits) { return { textDocument: textDocument, edits: edits }; } TextDocumentEdit.create = create; function is(value) { var candidate = value; return Is.defined(candidate) && OptionalVersionedTextDocumentIdentifier.is(candidate.textDocument) && Array.isArray(candidate.edits); } TextDocumentEdit.is = is; })(TextDocumentEdit || (exports.TextDocumentEdit = TextDocumentEdit = {})); var CreateFile; (function (CreateFile) { function create(uri, options, annotation) { var result = { kind: 'create', uri: uri }; if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) { result.options = options; } if (annotation !== undefined) { result.annotationId = annotation; } return result; } CreateFile.create = create; function is(value) { var candidate = value; return candidate && candidate.kind === 'create' && Is.string(candidate.uri) && (candidate.options === undefined || ((candidate.options.overwrite === undefined || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is.boolean(candidate.options.ignoreIfExists)))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId)); } CreateFile.is = is; })(CreateFile || (exports.CreateFile = CreateFile = {})); var RenameFile; (function (RenameFile) { function create(oldUri, newUri, options, annotation) { var result = { kind: 'rename', oldUri: oldUri, newUri: newUri }; if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) { result.options = options; } if (annotation !== undefined) { result.annotationId = annotation; } return result; } RenameFile.create = create; function is(value) { var candidate = value; return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) && (candidate.options === undefined || ((candidate.options.overwrite === undefined || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is.boolean(candidate.options.ignoreIfExists)))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId)); } RenameFile.is = is; })(RenameFile || (exports.RenameFile = RenameFile = {})); var DeleteFile; (function (DeleteFile) { function create(uri, options, annotation) { var result = { kind: 'delete', uri: uri }; if (options !== undefined && (options.recursive !== undefined || options.ignoreIfNotExists !== undefined)) { result.options = options; } if (annotation !== undefined) { result.annotationId = annotation; } return result; } DeleteFile.create = create; function is(value) { var candidate = value; return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) && (candidate.options === undefined || ((candidate.options.recursive === undefined || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === undefined || Is.boolean(candidate.options.ignoreIfNotExists)))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId)); } DeleteFile.is = is; })(DeleteFile || (exports.DeleteFile = DeleteFile = {})); var WorkspaceEdit; (function (WorkspaceEdit) { function is(value) { var candidate = value; return candidate && (candidate.changes !== undefined || candidate.documentChanges !== undefined) && (candidate.documentChanges === undefined || candidate.documentChanges.every(function (change) { if (Is.string(change.kind)) { return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change); } else { return TextDocumentEdit.is(change); } })); } WorkspaceEdit.is = is; })(WorkspaceEdit || (exports.WorkspaceEdit = WorkspaceEdit = {})); var TextEditChangeImpl = /** @class */ (function () { function TextEditChangeImpl(edits, changeAnnotations) { this.edits = edits; this.changeAnnotations = changeAnnotations; } TextEditChangeImpl.prototype.insert = function (position, newText, annotation) { var edit; var id; if (annotation === undefined) { edit = TextEdit.insert(position, newText); } else if (ChangeAnnotationIdentifier.is(annotation)) { id = annotation; edit = AnnotatedTextEdit.insert(position, newText, annotation); } else { this.assertChangeAnnotations(this.changeAnnotations); id = this.changeAnnotations.manage(annotation); edit = AnnotatedTextEdit.insert(position, newText, id); } this.edits.push(edit); if (id !== undefined) { return id; } }; TextEditChangeImpl.prototype.replace = function (range, newText, annotation) { var edit; var id; if (annotation === undefined) { edit = TextEdit.replace(range, newText); } else if (ChangeAnnotationIdentifier.is(annotation)) { id = annotation; edit = AnnotatedTextEdit.replace(range, newText, annotation); } else { this.assertChangeAnnotations(this.changeAnnotations); id = this.changeAnnotations.manage(annotation); edit = AnnotatedTextEdit.replace(range, newText, id); } this.edits.push(edit); if (id !== undefined) { return id; } }; TextEditChangeImpl.prototype.delete = function (range, annotation) { var edit; var id; if (annotation === undefined) { edit = TextEdit.del(range); } else if (ChangeAnnotationIdentifier.is(annotation)) { id = annotation; edit = AnnotatedTextEdit.del(range, annotation); } else { this.assertChangeAnnotations(this.changeAnnotations); id = this.changeAnnotations.manage(annotation); edit = AnnotatedTextEdit.del(range, id); } this.edits.push(edit); if (id !== undefined) { return id; } }; TextEditChangeImpl.prototype.add = function (edit) { this.edits.push(edit); }; TextEditChangeImpl.prototype.all = function () { return this.edits; }; TextEditChangeImpl.prototype.clear = function () { this.edits.splice(0, this.edits.length); }; TextEditChangeImpl.prototype.assertChangeAnnotations = function (value) { if (value === undefined) { throw new Error("Text edit change is not configured to manage change annotations."); } }; return TextEditChangeImpl; }()); /** * A helper class */ var ChangeAnnotations = /** @class */ (function () { function ChangeAnnotations(annotations) { this._annotations = annotations === undefined ? Object.create(null) : annotations; this._counter = 0; this._size = 0; } ChangeAnnotations.prototype.all = function () { return this._annotations; }; Object.defineProperty(ChangeAnnotations.prototype, "size", { get: function () { return this._size; }, enumerable: false, configurable: true }); ChangeAnnotations.prototype.manage = function (idOrAnnotation, annotation) { var id; if (ChangeAnnotationIdentifier.is(idOrAnnotation)) { id = idOrAnnotation; } else { id = this.nextId(); annotation = idOrAnnotation; } if (this._annotations[id] !== undefined) { throw new Error("Id ".concat(id, " is already in use.")); } if (annotation === undefined) { throw new Error("No annotation provided for id ".concat(id)); } this._annotations[id] = annotation; this._size++; return id; }; ChangeAnnotations.prototype.nextId = function () { this._counter++; return this._counter.toString(); }; return ChangeAnnotations; }()); /** * A workspace change helps constructing changes to a workspace. */ var WorkspaceChange = /** @class */ (function () { function WorkspaceChange(workspaceEdit) { var _this = this; this._textEditChanges = Object.create(null); if (workspaceEdit !== undefined) { this._workspaceEdit = workspaceEdit; if (workspaceEdit.documentChanges) { this._changeAnnotations = new ChangeAnnotations(workspaceEdit.changeAnnotations); workspaceEdit.changeAnnotations = this._changeAnnotations.all(); workspaceEdit.documentChanges.forEach(function (change) { if (TextDocumentEdit.is(change)) { var textEditChange = new TextEditChangeImpl(change.edits, _this._changeAnnotations); _this._textEditChanges[change.textDocument.uri] = textEditChange; } }); } else if (workspaceEdit.changes) { Object.keys(workspaceEdit.changes).forEach(function (key) { var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]); _this._textEditChanges[key] = textEditChange; }); } } else { this._workspaceEdit = {}; } } Object.defineProperty(WorkspaceChange.prototype, "edit", { /** * Returns the underlying {@link WorkspaceEdit} literal * use to be returned from a workspace edit operation like rename. */ get: function () { this.initDocumentChanges(); if (this._changeAnnotations !== undefined) { if (this._changeAnnotations.size === 0) { this._workspaceEdit.changeAnnotations = undefined; } else { this._workspaceEdit.changeAnnotations = this._changeAnnotations.all(); } } return this._workspaceEdit; }, enumerable: false, configurable: true }); WorkspaceChange.prototype.getTextEditChange = function (key) { if (OptionalVersionedTextDocumentIdentifier.is(key)) { this.initDocumentChanges(); if (this._workspaceEdit.documentChanges === undefined) { throw new Error('Workspace edit is not configured for document changes.'); } var textDocument = { uri: key.uri, version: key.version }; var result = this._textEditChanges[textDocument.uri]; if (!result) { var edits = []; var textDocumentEdit = { textDocument: textDocument, edits: edits }; this._workspaceEdit.documentChanges.push(textDocumentEdit); result = new TextEditChangeImpl(edits, this._changeAnnotations); this._textEditChanges[textDocument.uri] = result; } return result; } else { this.initChanges(); if (this._workspaceEdit.changes === undefined) { throw new Error('Workspace edit is not configured for normal text edit changes.'); } var result = this._textEditChanges[key]; if (!result) { var edits = []; this._workspaceEdit.changes[key] = edits; result = new TextEditChangeImpl(edits); this._textEditChanges[key] = result; } return result; } }; WorkspaceChange.prototype.initDocumentChanges = function () { if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) { this._changeAnnotations = new ChangeAnnotations(); this._workspaceEdit.documentChanges = []; this._workspaceEdit.changeAnnotations = this._changeAnnotations.all(); } }; WorkspaceChange.prototype.initChanges = function () { if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) { this._workspaceEdit.changes = Object.create(null); } }; WorkspaceChange.prototype.createFile = function (uri, optionsOrAnnotation, options) { this.initDocumentChanges(); if (this._workspaceEdit.documentChanges === undefined) { throw new Error('Workspace edit is not configured for document changes.'); } var annotation; if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { annotation = optionsOrAnnotation; } else { options = optionsOrAnnotation; } var operation; var id; if (annotation === undefined) { operation = CreateFile.create(uri, options); } else { id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation); operation = CreateFile.create(uri, options, id); } this._workspaceEdit.documentChanges.push(operation); if (id !== undefined) { return id; } }; WorkspaceChange.prototype.renameFile = function (oldUri, newUri, optionsOrAnnotation, options) { this.initDocumentChanges(); if (this._workspaceEdit.documentChanges === undefined) { throw new Error('Workspace edit is not configured for document changes.'); } var annotation; if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { annotation = optionsOrAnnotation; } else { options = optionsOrAnnotation; } var operation; var id; if (annotation === undefined) { operation = RenameFile.create(oldUri, newUri, options); } else { id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation); operation = RenameFile.create(oldUri, newUri, options, id); } this._workspaceEdit.documentChanges.push(operation); if (id !== undefined) { return id; } }; WorkspaceChange.prototype.deleteFile = function (uri, optionsOrAnnotation, options) { this.initDocumentChanges(); if (this._workspaceEdit.documentChanges === undefined) { throw new Error('Workspace edit is not configured for document changes.'); } var annotation; if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { annotation = optionsOrAnnotation; } else { options = optionsOrAnnotation; } var operation; var id; if (annotation === undefined) { operation = DeleteFile.create(uri, options); } else { id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation); operation = DeleteFile.create(uri, options, id); } this._workspaceEdit.documentChanges.push(operation); if (id !== undefined) { return id; } }; return WorkspaceChange; }()); exports.WorkspaceChange = WorkspaceChange; /** * The TextDocumentIdentifier namespace provides helper functions to work with * {@link TextDocumentIdentifier} literals. */ var TextDocumentIdentifier; (function (TextDocumentIdentifier) { /** * Creates a new TextDocumentIdentifier literal. * @param uri The document's uri. */ function create(uri) { return { uri: uri }; } TextDocumentIdentifier.create = create; /** * Checks whether the given literal conforms to the {@link TextDocumentIdentifier} interface. */ function is(value) { var candidate = value; return Is.defined(candidate) && Is.string(candidate.uri); } TextDocumentIdentifier.is = is; })(TextDocumentIdentifier || (exports.TextDocumentIdentifier = TextDocumentIdentifier = {})); /** * The VersionedTextDocumentIdentifier namespace provides helper functions to work with * {@link VersionedTextDocumentIdentifier} literals. */ var VersionedTextDocumentIdentifier; (function (VersionedTextDocumentIdentifier) { /** * Creates a new VersionedTextDocumentIdentifier literal. * @param uri The document's uri. * @param version The document's version. */ function create(uri, version) { return { uri: uri, version: version }; } VersionedTextDocumentIdentifier.create = create; /** * Checks whether the given literal conforms to the {@link VersionedTextDocumentIdentifier} interface. */ function is(value) { var candidate = value; return Is.defined(candidate) && Is.string(candidate.uri) && Is.integer(candidate.version); } VersionedTextDocumentIdentifier.is = is; })(VersionedTextDocumentIdentifier || (exports.VersionedTextDocumentIdentifier = VersionedTextDocumentIdentifier = {})); /** * The OptionalVersionedTextDocumentIdentifier namespace provides helper functions to work with * {@link OptionalVersionedTextDocumentIdentifier} literals. */ var OptionalVersionedTextDocumentIdentifier; (function (OptionalVersionedTextDocumentIdentifier) { /** * Creates a new OptionalVersionedTextDocumentIdentifier literal. * @param uri The document's uri. * @param version The document's version. */ function create(uri, version) { return { uri: uri, version: version }; } OptionalVersionedTextDocumentIdentifier.create = create; /** * Checks whether the given literal conforms to the {@link OptionalVersionedTextDocumentIdentifier} interface. */ function is(value) { var candidate = value; return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.integer(candidate.version)); } OptionalVersionedTextDocumentIdentifier.is = is; })(OptionalVersionedTextDocumentIdentifier || (exports.OptionalVersionedTextDocumentIdentifier = OptionalVersionedTextDocumentIdentifier = {})); /** * The TextDocumentItem namespace provides helper functions to work with * {@link TextDocumentItem} literals. */ var TextDocumentItem; (function (TextDocumentItem) { /** * Creates a new TextDocumentItem literal. * @param uri The document's uri. * @param languageId The document's language identifier. * @param version The document's version number. * @param text The document's text. */ function create(uri, languageId, version, text) { return { uri: uri, languageId: languageId, version: version, text: text }; } TextDocumentItem.create = create; /** * Checks whether the given literal conforms to the {@link TextDocumentItem} interface. */ function is(value) { var candidate = value; return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.integer(candidate.version) && Is.string(candidate.text); } TextDocumentItem.is = is; })(TextDocumentItem || (exports.TextDocumentItem = TextDocumentItem = {})); /** * Describes the content type that a client supports in various * result literals like `Hover`, `ParameterInfo` or `CompletionItem`. * * Please note that `MarkupKinds` must not start with a `$`. This kinds * are reserved for internal usage. */ var MarkupKind; (function (MarkupKind) { /** * Plain text is supported as a content format */ MarkupKind.PlainText = 'plaintext'; /** * Markdown is supported as a content format */ MarkupKind.Markdown = 'markdown'; /** * Checks whether the given value is a value of the {@link MarkupKind} type. */ function is(value) { var candidate = value; return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown; } MarkupKind.is = is; })(MarkupKind || (exports.MarkupKind = MarkupKind = {})); var MarkupContent; (function (MarkupContent) { /** * Checks whether the given value conforms to the {@link MarkupContent} interface. */ function is(value) { var candidate = value; return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value); } MarkupContent.is = is; })(MarkupContent || (exports.MarkupContent = MarkupContent = {})); /** * The kind of a completion entry. */ var CompletionItemKind; (function (CompletionItemKind) { CompletionItemKind.Text = 1; CompletionItemKind.Method = 2; CompletionItemKind.Function = 3; CompletionItemKind.Constructor = 4; CompletionItemKind.Field = 5; CompletionItemKind.Variable = 6; CompletionItemKind.Class = 7; CompletionItemKind.Interface = 8; CompletionItemKind.Module = 9; CompletionItemKind.Property = 10; CompletionItemKind.Unit = 11; CompletionItemKind.Value = 12; CompletionItemKind.Enum = 13; CompletionItemKind.Keyword = 14; CompletionItemKind.Snippet = 15; CompletionItemKind.Color = 16; CompletionItemKind.File = 17; CompletionItemKind.Reference = 18; CompletionItemKind.Folder = 19; CompletionItemKind.EnumMember = 20; CompletionItemKind.Constant = 21; CompletionItemKind.Struct = 22; CompletionItemKind.Event = 23; CompletionItemKind.Operator = 24; CompletionItemKind.TypeParameter = 25; })(CompletionItemKind || (exports.CompletionItemKind = CompletionItemKind = {})); /** * Defines whether the insert text in a completion item should be interpreted as * plain text or a snippet. */ var InsertTextFormat; (function (InsertTextFormat) { /** * The primary text to be inserted is treated as a plain string. */ InsertTextFormat.PlainText = 1; /** * The primary text to be inserted is treated as a snippet. * * A snippet can define tab stops and placeholders with `$1`, `$2` * and `${3:foo}`. `$0` defines the final tab stop, it defaults to * the end of the snippet. Placeholders with equal identifiers are linked, * that is typing in one will update others too. * * See also: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#snippet_syntax */ InsertTextFormat.Snippet = 2; })(InsertTextFormat || (exports.InsertTextFormat = InsertTextFormat = {})); /** * Completion item tags are extra annotations that tweak the rendering of a completion * item. * * @since 3.15.0 */ var CompletionItemTag; (function (CompletionItemTag) { /** * Render a completion as obsolete, usually using a strike-out. */ CompletionItemTag.Deprecated = 1; })(CompletionItemTag || (exports.CompletionItemTag = CompletionItemTag = {})); /** * The InsertReplaceEdit namespace provides functions to deal with insert / replace edits. * * @since 3.16.0 */ var InsertReplaceEdit; (function (InsertReplaceEdit) { /** * Creates a new insert / replace edit */ function create(newText, insert, replace) { return { newText: newText, insert: insert, replace: replace }; } InsertReplaceEdit.create = create; /** * Checks whether the given literal conforms to the {@link InsertReplaceEdit} interface. */ function is(value) { var candidate = value; return candidate && Is.string(candidate.newText) && Range.is(candidate.insert) && Range.is(candidate.replace); } InsertReplaceEdit.is = is; })(InsertReplaceEdit || (exports.InsertReplaceEdit = InsertReplaceEdit = {})); /** * How whitespace and indentation is handled during completion * item insertion. * * @since 3.16.0 */ var InsertTextMode; (function (InsertTextMode) { /** * The insertion or replace strings is taken as it is. If the * value is multi line the lines below the cursor will be * inserted using the indentation defined in the string value. * The client will not apply any kind of adjustments to the * string. */ InsertTextMode.asIs = 1; /** * The editor adjusts leading whitespace of new lines so that * they match the indentation up to the cursor of the line for * which the item is accepted. * * Consider a line like this: <2tabs><3tabs>foo. Accepting a * multi line completion item is indented using 2 tabs and all * following lines inserted will be indented using 2 tabs as well. */ InsertTextMode.adjustIndentation = 2; })(InsertTextMode || (exports.InsertTextMode = InsertTextMode = {})); var CompletionItemLabelDetails; (function (CompletionItemLabelDetails) { function is(value) { var candidate = value; return candidate && (Is.string(candidate.detail) || candidate.detail === undefined) && (Is.string(candidate.description) || candidate.description === undefined); } CompletionItemLabelDetails.is = is; })(CompletionItemLabelDetails || (exports.CompletionItemLabelDetails = CompletionItemLabelDetails = {})); /** * The CompletionItem namespace provides functions to deal with * completion items. */ var CompletionItem; (function (CompletionItem) { /** * Create a completion item and seed it with a label. * @param label The completion item's label */ function create(label) { return { label: label }; } CompletionItem.create = create; })(CompletionItem || (exports.CompletionItem = CompletionItem = {})); /** * The CompletionList namespace provides functions to deal with * completion lists. */ var CompletionList; (function (CompletionList) { /** * Creates a new completion list. * * @param items The completion items. * @param isIncomplete The list is not complete. */ function create(items, isIncomplete) { return { items: items ? items : [], isIncomplete: !!isIncomplete }; } CompletionList.create = create; })(CompletionList || (exports.CompletionList = CompletionList = {})); var MarkedString; (function (MarkedString) { /** * Creates a marked string from plain text. * * @param plainText The plain text. */ function fromPlainText(plainText) { return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash } MarkedString.fromPlainText = fromPlainText; /** * Checks whether the given value conforms to the {@link MarkedString} type. */ function is(value) { var candidate = value; return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value)); } MarkedString.is = is; })(MarkedString || (exports.MarkedString = MarkedString = {})); var Hover; (function (Hover) { /** * Checks whether the given value conforms to the {@link Hover} interface. */ function is(value) { var candidate = value; return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) || MarkedString.is(candidate.contents) || Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === undefined || Range.is(value.range)); } Hover.is = is; })(Hover || (exports.Hover = Hover = {})); /** * The ParameterInformation namespace provides helper functions to work with * {@link ParameterInformation} literals. */ var ParameterInformation; (function (ParameterInformation) { /** * Creates a new parameter information literal. * * @param label A label string. * @param documentation A doc string. */ function create(label, documentation) { return documentation ? { label: label, documentation: documentation } : { label: label }; } ParameterInformation.create = create; })(ParameterInformation || (exports.ParameterInformation = ParameterInformation = {})); /** * The SignatureInformation namespace provides helper functions to work with * {@link SignatureInformation} literals. */ var SignatureInformation; (function (SignatureInformation) { function create(label, documentation) { var parameters = []; for (var _i = 2; _i < arguments.length; _i++) { parameters[_i - 2] = arguments[_i]; } var result = { label: label }; if (Is.defined(documentation)) { result.documentation = documentation; } if (Is.defined(parameters)) { result.parameters = parameters; } else { result.parameters = []; } return result; } SignatureInformation.create = create; })(SignatureInformation || (exports.SignatureInformation = SignatureInformation = {})); /** * A document highlight kind. */ var DocumentHighlightKind; (function (DocumentHighlightKind) { /** * A textual occurrence. */ DocumentHighlightKind.Text = 1; /** * Read-access of a symbol, like reading a variable. */ DocumentHighlightKind.Read = 2; /** * Write-access of a symbol, like writing to a variable. */ DocumentHighlightKind.Write = 3; })(DocumentHighlightKind || (exports.DocumentHighlightKind = DocumentHighlightKind = {})); /** * DocumentHighlight namespace to provide helper functions to work with * {@link DocumentHighlight} literals. */ var DocumentHighlight; (function (DocumentHighlight) { /** * Create a DocumentHighlight object. * @param range The range the highlight applies to. * @param kind The highlight kind */ function create(range, kind) { var result = { range: range }; if (Is.number(kind)) { result.kind = kind; } return result; } DocumentHighlight.create = create; })(DocumentHighlight || (exports.DocumentHighlight = DocumentHighlight = {})); /** * A symbol kind. */ var SymbolKind; (function (SymbolKind) { SymbolKind.File = 1; SymbolKind.Module = 2; SymbolKind.Namespace = 3; SymbolKind.Package = 4; SymbolKind.Class = 5; SymbolKind.Method = 6; SymbolKind.Property = 7; SymbolKind.Field = 8; SymbolKind.Constructor = 9; SymbolKind.Enum = 10; SymbolKind.Interface = 11; SymbolKind.Function = 12; SymbolKind.Variable = 13; SymbolKind.Constant = 14; SymbolKind.String = 15; SymbolKind.Number = 16; SymbolKind.Boolean = 17; SymbolKind.Array = 18; SymbolKind.Object = 19; SymbolKind.Key = 20; SymbolKind.Null = 21; SymbolKind.EnumMember = 22; SymbolKind.Struct = 23; SymbolKind.Event = 24; SymbolKind.Operator = 25; SymbolKind.TypeParameter = 26; })(SymbolKind || (exports.SymbolKind = SymbolKind = {})); /** * Symbol tags are extra annotations that tweak the rendering of a symbol. * * @since 3.16 */ var SymbolTag; (function (SymbolTag) { /** * Render a symbol as obsolete, usually using a strike-out. */ SymbolTag.Deprecated = 1; })(SymbolTag || (exports.SymbolTag = SymbolTag = {})); var SymbolInformation; (function (SymbolInformation) { /** * Creates a new symbol information literal. * * @param name The name of the symbol. * @param kind The kind of the symbol. * @param range The range of the location of the symbol. * @param uri The resource of the location of symbol. * @param containerName The name of the symbol containing the symbol. */ function create(name, kind, range, uri, containerName) { var result = { name: name, kind: kind, location: { uri: uri, range: range } }; if (containerName) { result.containerName = containerName; } return result; } SymbolInformation.create = create; })(SymbolInformation || (exports.SymbolInformation = SymbolInformation = {})); var WorkspaceSymbol; (function (WorkspaceSymbol) { /** * Create a new workspace symbol. * * @param name The name of the symbol. * @param kind The kind of the symbol. * @param uri The resource of the location of the symbol. * @param range An options range of the location. * @returns A WorkspaceSymbol. */ function create(name, kind, uri, range) { return range !== undefined ? { name: name, kind: kind, location: { uri: uri, range: range } } : { name: name, kind: kind, location: { uri: uri } }; } WorkspaceSymbol.create = create; })(WorkspaceSymbol || (exports.WorkspaceSymbol = WorkspaceSymbol = {})); var DocumentSymbol; (function (DocumentSymbol) { /** * Creates a new symbol information literal. * * @param name The name of the symbol. * @param detail The detail of the symbol. * @param kind The kind of the symbol. * @param range The range of the symbol. * @param selectionRange The selectionRange of the symbol. * @param children Children of the symbol. */ function create(name, detail, kind, range, selectionRange, children) { var result = { name: name, detail: detail, kind: kind, range: range, selectionRange: selectionRange }; if (children !== undefined) { result.children = children; } return result; } DocumentSymbol.create = create; /** * Checks whether the given literal conforms to the {@link DocumentSymbol} interface. */ function is(value) { var candidate = value; return candidate && Is.string(candidate.name) && Is.number(candidate.kind) && Range.is(candidate.range) && Range.is(candidate.selectionRange) && (candidate.detail === undefined || Is.string(candidate.detail)) && (candidate.deprecated === undefined || Is.boolean(candidate.deprecated)) && (candidate.children === undefined || Array.isArray(candidate.children)) && (candidate.tags === undefined || Array.isArray(candidate.tags)); } DocumentSymbol.is = is; })(DocumentSymbol || (exports.DocumentSymbol = DocumentSymbol = {})); /** * A set of predefined code action kinds */ var CodeActionKind; (function (CodeActionKind) { /** * Empty kind. */ CodeActionKind.Empty = ''; /** * Base kind for quickfix actions: 'quickfix' */ CodeActionKind.QuickFix = 'quickfix'; /** * Base kind for refactoring actions: 'refactor' */ CodeActionKind.Refactor = 'refactor'; /** * Base kind for refactoring extraction actions: 'refactor.extract' * * Example extract actions: * * - Extract method * - Extract function * - Extract variable * - Extract interface from class * - ... */ CodeActionKind.RefactorExtract = 'refactor.extract'; /** * Base kind for refactoring inline actions: 'refactor.inline' * * Example inline actions: * * - Inline function * - Inline variable * - Inline constant * - ... */ CodeActionKind.RefactorInline = 'refactor.inline'; /** * Base kind for refactoring rewrite actions: 'refactor.rewrite' * * Example rewrite actions: * * - Convert JavaScript function to class * - Add or remove parameter * - Encapsulate field * - Make method static * - Move method to base class * - ... */ CodeActionKind.RefactorRewrite = 'refactor.rewrite'; /** * Base kind for source actions: `source` * * Source code actions apply to the entire file. */ CodeActionKind.Source = 'source'; /** * Base kind for an organize imports source action: `source.organizeImports` */ CodeActionKind.SourceOrganizeImports = 'source.organizeImports'; /** * Base kind for auto-fix source actions: `source.fixAll`. * * Fix all actions automatically fix errors that have a clear fix that do not require user input. * They should not suppress errors or perform unsafe fixes such as generating new types or classes. * * @since 3.15.0 */ CodeActionKind.SourceFixAll = 'source.fixAll'; })(CodeActionKind || (exports.CodeActionKind = CodeActionKind = {})); /** * The reason why code actions were requested. * * @since 3.17.0 */ var CodeActionTriggerKind; (function (CodeActionTriggerKind) { /** * Code actions were explicitly requested by the user or by an extension. */ CodeActionTriggerKind.Invoked = 1; /** * Code actions were requested automatically. * * This typically happens when current selection in a file changes, but can * also be triggered when file content changes. */ CodeActionTriggerKind.Automatic = 2; })(CodeActionTriggerKind || (exports.CodeActionTriggerKind = CodeActionTriggerKind = {})); /** * The CodeActionContext namespace provides helper functions to work with * {@link CodeActionContext} literals. */ var CodeActionContext; (function (CodeActionContext) { /** * Creates a new CodeActionContext literal. */ function create(diagnostics, only, triggerKind) { var result = { diagnostics: diagnostics }; if (only !== undefined && only !== null) { result.only = only; } if (triggerKind !== undefined && triggerKind !== null) { result.triggerKind = triggerKind; } return result; } CodeActionContext.create = create; /** * Checks whether the given literal conforms to the {@link CodeActionContext} interface. */ function is(value) { var candidate = value; return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === undefined || Is.typedArray(candidate.only, Is.string)) && (candidate.triggerKind === undefined || candidate.triggerKind === CodeActionTriggerKind.Invoked || candidate.triggerKind === CodeActionTriggerKind.Automatic); } CodeActionContext.is = is; })(CodeActionContext || (exports.CodeActionContext = CodeActionContext = {})); var CodeAction; (function (CodeAction) { function create(title, kindOrCommandOrEdit, kind) { var result = { title: title }; var checkKind = true; if (typeof kindOrCommandOrEdit === 'string') { checkKind = false; result.kind = kindOrCommandOrEdit; } else if (Command.is(kindOrCommandOrEdit)) { result.command = kindOrCommandOrEdit; } else { result.edit = kindOrCommandOrEdit; } if (checkKind && kind !== undefined) { result.kind = kind; } return result; } CodeAction.create = create; function is(value) { var candidate = value; return candidate && Is.string(candidate.title) && (candidate.diagnostics === undefined || Is.typedArray(candidate.diagnostics, Diagnostic.is)) && (candidate.kind === undefined || Is.string(candidate.kind)) && (candidate.edit !== undefined || candidate.command !== undefined) && (candidate.command === undefined || Command.is(candidate.command)) && (candidate.isPreferred === undefined || Is.boolean(candidate.isPreferred)) && (candidate.edit === undefined || WorkspaceEdit.is(candidate.edit)); } CodeAction.is = is; })(CodeAction || (exports.CodeAction = CodeAction = {})); /** * The CodeLens namespace provides helper functions to work with * {@link CodeLens} literals. */ var CodeLens; (function (CodeLens) { /** * Creates a new CodeLens literal. */ function create(range, data) { var result = { range: range }; if (Is.defined(data)) { result.data = data; } return result; } CodeLens.create = create; /** * Checks whether the given literal conforms to the {@link CodeLens} interface. */ function is(value) { var candidate = value; return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command)); } CodeLens.is = is; })(CodeLens || (exports.CodeLens = CodeLens = {})); /** * The FormattingOptions namespace provides helper functions to work with * {@link FormattingOptions} literals. */ var FormattingOptions; (function (FormattingOptions) { /** * Creates a new FormattingOptions literal. */ function create(tabSize, insertSpaces) { return { tabSize: tabSize, insertSpaces: insertSpaces }; } FormattingOptions.create = create; /** * Checks whether the given literal conforms to the {@link FormattingOptions} interface. */ function is(value) { var candidate = value; return Is.defined(candidate) && Is.uinteger(candidate.tabSize) && Is.boolean(candidate.insertSpaces); } FormattingOptions.is = is; })(FormattingOptions || (exports.FormattingOptions = FormattingOptions = {})); /** * The DocumentLink namespace provides helper functions to work with * {@link DocumentLink} literals. */ var DocumentLink; (function (DocumentLink) { /** * Creates a new DocumentLink literal. */ function create(range, target, data) { return { range: range, target: target, data: data }; } DocumentLink.create = create; /** * Checks whether the given literal conforms to the {@link DocumentLink} interface. */ function is(value) { var candidate = value; return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target)); } DocumentLink.is = is; })(DocumentLink || (exports.DocumentLink = DocumentLink = {})); /** * The SelectionRange namespace provides helper function to work with * SelectionRange literals. */ var SelectionRange; (function (SelectionRange) { /** * Creates a new SelectionRange * @param range the range. * @param parent an optional parent. */ function create(range, parent) { return { range: range, parent: parent }; } SelectionRange.create = create; function is(value) { var candidate = value; return Is.objectLiteral(candidate) && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent)); } SelectionRange.is = is; })(SelectionRange || (exports.SelectionRange = SelectionRange = {})); /** * A set of predefined token types. This set is not fixed * an clients can specify additional token types via the * corresponding client capabilities. * * @since 3.16.0 */ var SemanticTokenTypes; (function (SemanticTokenTypes) { SemanticTokenTypes["namespace"] = "namespace"; /** * Represents a generic type. Acts as a fallback for types which can't be mapped to * a specific type like class or enum. */ SemanticTokenTypes["type"] = "type"; SemanticTokenTypes["class"] = "class"; SemanticTokenTypes["enum"] = "enum"; SemanticTokenTypes["interface"] = "interface"; SemanticTokenTypes["struct"] = "struct"; SemanticTokenTypes["typeParameter"] = "typeParameter"; SemanticTokenTypes["parameter"] = "parameter"; SemanticTokenTypes["variable"] = "variable"; SemanticTokenTypes["property"] = "property"; SemanticTokenTypes["enumMember"] = "enumMember"; SemanticTokenTypes["event"] = "event"; SemanticTokenTypes["function"] = "function"; SemanticTokenTypes["method"] = "method"; SemanticTokenTypes["macro"] = "macro"; SemanticTokenTypes["keyword"] = "keyword"; SemanticTokenTypes["modifier"] = "modifier"; SemanticTokenTypes["comment"] = "comment"; SemanticTokenTypes["string"] = "string"; SemanticTokenTypes["number"] = "number"; SemanticTokenTypes["regexp"] = "regexp"; SemanticTokenTypes["operator"] = "operator"; /** * @since 3.17.0 */ SemanticTokenTypes["decorator"] = "decorator"; })(SemanticTokenTypes || (exports.SemanticTokenTypes = SemanticTokenTypes = {})); /** * A set of predefined token modifiers. This set is not fixed * an clients can specify additional token types via the * corresponding client capabilities. * * @since 3.16.0 */ var SemanticTokenModifiers; (function (SemanticTokenModifiers) { SemanticTokenModifiers["declaration"] = "declaration"; SemanticTokenModifiers["definition"] = "definition"; SemanticTokenModifiers["readonly"] = "readonly"; SemanticTokenModifiers["static"] = "static"; SemanticTokenModifiers["deprecated"] = "deprecated"; SemanticTokenModifiers["abstract"] = "abstract"; SemanticTokenModifiers["async"] = "async"; SemanticTokenModifiers["modification"] = "modification"; SemanticTokenModifiers["documentation"] = "documentation"; SemanticTokenModifiers["defaultLibrary"] = "defaultLibrary"; })(SemanticTokenModifiers || (exports.SemanticTokenModifiers = SemanticTokenModifiers = {})); /** * @since 3.16.0 */ var SemanticTokens; (function (SemanticTokens) { function is(value) { var candidate = value; return Is.objectLiteral(candidate) && (candidate.resultId === undefined || typeof candidate.resultId === 'string') && Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === 'number'); } SemanticTokens.is = is; })(SemanticTokens || (exports.SemanticTokens = SemanticTokens = {})); /** * The InlineValueText namespace provides functions to deal with InlineValueTexts. * * @since 3.17.0 */ var InlineValueText; (function (InlineValueText) { /** * Creates a new InlineValueText literal. */ function create(range, text) { return { range: range, text: text }; } InlineValueText.create = create; function is(value) { var candidate = value; return candidate !== undefined && candidate !== null && Range.is(candidate.range) && Is.string(candidate.text); } InlineValueText.is = is; })(InlineValueText || (exports.InlineValueText = InlineValueText = {})); /** * The InlineValueVariableLookup namespace provides functions to deal with InlineValueVariableLookups. * * @since 3.17.0 */ var InlineValueVariableLookup; (function (InlineValueVariableLookup) { /** * Creates a new InlineValueText literal. */ function create(range, variableName, caseSensitiveLookup) { return { range: range, variableName: variableName, caseSensitiveLookup: caseSensitiveLookup }; } InlineValueVariableLookup.create = create; function is(value) { var candidate = value; return candidate !== undefined && candidate !== null && Range.is(candidate.range) && Is.boolean(candidate.caseSensitiveLookup) && (Is.string(candidate.variableName) || candidate.variableName === undefined); } InlineValueVariableLookup.is = is; })(InlineValueVariableLookup || (exports.InlineValueVariableLookup = InlineValueVariableLookup = {})); /** * The InlineValueEvaluatableExpression namespace provides functions to deal with InlineValueEvaluatableExpression. * * @since 3.17.0 */ var InlineValueEvaluatableExpression; (function (InlineValueEvaluatableExpression) { /** * Creates a new InlineValueEvaluatableExpression literal. */ function create(range, expression) { return { range: range, expression: expression }; } InlineValueEvaluatableExpression.create = create; function is(value) { var candidate = value; return candidate !== undefined && candidate !== null && Range.is(candidate.range) && (Is.string(candidate.expression) || candidate.expression === undefined); } InlineValueEvaluatableExpression.is = is; })(InlineValueEvaluatableExpression || (exports.InlineValueEvaluatableExpression = InlineValueEvaluatableExpression = {})); /** * The InlineValueContext namespace provides helper functions to work with * {@link InlineValueContext} literals. * * @since 3.17.0 */ var InlineValueContext; (function (InlineValueContext) { /** * Creates a new InlineValueContext literal. */ function create(frameId, stoppedLocation) { return { frameId: frameId, stoppedLocation: stoppedLocation }; } InlineValueContext.create = create; /** * Checks whether the given literal conforms to the {@link InlineValueContext} interface. */ function is(value) { var candidate = value; return Is.defined(candidate) && Range.is(value.stoppedLocation); } InlineValueContext.is = is; })(InlineValueContext || (exports.InlineValueContext = InlineValueContext = {})); /** * Inlay hint kinds. * * @since 3.17.0 */ var InlayHintKind; (function (InlayHintKind) { /** * An inlay hint that for a type annotation. */ InlayHintKind.Type = 1; /** * An inlay hint that is for a parameter. */ InlayHintKind.Parameter = 2; function is(value) { return value === 1 || value === 2; } InlayHintKind.is = is; })(InlayHintKind || (exports.InlayHintKind = InlayHintKind = {})); var InlayHintLabelPart; (function (InlayHintLabelPart) { function create(value) { return { value: value }; } InlayHintLabelPart.create = create; function is(value) { var candidate = value; return Is.objectLiteral(candidate) && (candidate.tooltip === undefined || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip)) && (candidate.location === undefined || Location.is(candidate.location)) && (candidate.command === undefined || Command.is(candidate.command)); } InlayHintLabelPart.is = is; })(InlayHintLabelPart || (exports.InlayHintLabelPart = InlayHintLabelPart = {})); var InlayHint; (function (InlayHint) { function create(position, label, kind) { var result = { position: position, label: label }; if (kind !== undefined) { result.kind = kind; } return result; } InlayHint.create = create; function is(value) { var candidate = value; return Is.objectLiteral(candidate) && Position.is(candidate.position) && (Is.string(candidate.label) || Is.typedArray(candidate.label, InlayHintLabelPart.is)) && (candidate.kind === undefined || InlayHintKind.is(candidate.kind)) && (candidate.textEdits === undefined) || Is.typedArray(candidate.textEdits, TextEdit.is) && (candidate.tooltip === undefined || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip)) && (candidate.paddingLeft === undefined || Is.boolean(candidate.paddingLeft)) && (candidate.paddingRight === undefined || Is.boolean(candidate.paddingRight)); } InlayHint.is = is; })(InlayHint || (exports.InlayHint = InlayHint = {})); var StringValue; (function (StringValue) { function createSnippet(value) { return { kind: 'snippet', value: value }; } StringValue.createSnippet = createSnippet; })(StringValue || (exports.StringValue = StringValue = {})); var InlineCompletionItem; (function (InlineCompletionItem) { function create(insertText, filterText, range, command) { return { insertText: insertText, filterText: filterText, range: range, command: command }; } InlineCompletionItem.create = create; })(InlineCompletionItem || (exports.InlineCompletionItem = InlineCompletionItem = {})); var InlineCompletionList; (function (InlineCompletionList) { function create(items) { return { items: items }; } InlineCompletionList.create = create; })(InlineCompletionList || (exports.InlineCompletionList = InlineCompletionList = {})); /** * Describes how an {@link InlineCompletionItemProvider inline completion provider} was triggered. * * @since 3.18.0 * @proposed */ var InlineCompletionTriggerKind; (function (InlineCompletionTriggerKind) { /** * Completion was triggered explicitly by a user gesture. */ InlineCompletionTriggerKind.Invoked = 0; /** * Completion was triggered automatically while editing. */ InlineCompletionTriggerKind.Automatic = 1; })(InlineCompletionTriggerKind || (exports.InlineCompletionTriggerKind = InlineCompletionTriggerKind = {})); var SelectedCompletionInfo; (function (SelectedCompletionInfo) { function create(range, text) { return { range: range, text: text }; } SelectedCompletionInfo.create = create; })(SelectedCompletionInfo || (exports.SelectedCompletionInfo = SelectedCompletionInfo = {})); var InlineCompletionContext; (function (InlineCompletionContext) { function create(triggerKind, selectedCompletionInfo) { return { triggerKind: triggerKind, selectedCompletionInfo: selectedCompletionInfo }; } InlineCompletionContext.create = create; })(InlineCompletionContext || (exports.InlineCompletionContext = InlineCompletionContext = {})); var WorkspaceFolder; (function (WorkspaceFolder) { function is(value) { var candidate = value; return Is.objectLiteral(candidate) && URI.is(candidate.uri) && Is.string(candidate.name); } WorkspaceFolder.is = is; })(WorkspaceFolder || (exports.WorkspaceFolder = WorkspaceFolder = {})); exports.EOL = ['\n', '\r\n', '\r']; /** * @deprecated Use the text document from the new vscode-languageserver-textdocument package. */ var TextDocument; (function (TextDocument) { /** * Creates a new ITextDocument literal from the given uri and content. * @param uri The document's uri. * @param languageId The document's language Id. * @param version The document's version. * @param content The document's content. */ function create(uri, languageId, version, content) { return new FullTextDocument(uri, languageId, version, content); } TextDocument.create = create; /** * Checks whether the given literal conforms to the {@link ITextDocument} interface. */ function is(value) { var candidate = value; return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.uinteger(candidate.lineCount) && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false; } TextDocument.is = is; function applyEdits(document, edits) { var text = document.getText(); var sortedEdits = mergeSort(edits, function (a, b) { var diff = a.range.start.line - b.range.start.line; if (diff === 0) { return a.range.start.character - b.range.start.character; } return diff; }); var lastModifiedOffset = text.length; for (var i = sortedEdits.length - 1; i >= 0; i--) { var e = sortedEdits[i]; var startOffset = document.offsetAt(e.range.start); var endOffset = document.offsetAt(e.range.end); if (endOffset <= lastModifiedOffset) { text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length); } else { throw new Error('Overlapping edit'); } lastModifiedOffset = startOffset; } return text; } TextDocument.applyEdits = applyEdits; function mergeSort(data, compare) { if (data.length <= 1) { // sorted return data; } var p = (data.length / 2) | 0; var left = data.slice(0, p); var right = data.slice(p); mergeSort(left, compare); mergeSort(right, compare); var leftIdx = 0; var rightIdx = 0; var i = 0; while (leftIdx < left.length && rightIdx < right.length) { var ret = compare(left[leftIdx], right[rightIdx]); if (ret <= 0) { // smaller_equal -> take left to preserve order data[i++] = left[leftIdx++]; } else { // greater -> take right data[i++] = right[rightIdx++]; } } while (leftIdx < left.length) { data[i++] = left[leftIdx++]; } while (rightIdx < right.length) { data[i++] = right[rightIdx++]; } return data; } })(TextDocument || (exports.TextDocument = TextDocument = {})); /** * @deprecated Use the text document from the new vscode-languageserver-textdocument package. */ var FullTextDocument = /** @class */ (function () { function FullTextDocument(uri, languageId, version, content) { this._uri = uri; this._languageId = languageId; this._version = version; this._content = content; this._lineOffsets = undefined; } Object.defineProperty(FullTextDocument.prototype, "uri", { get: function () { return this._uri; }, enumerable: false, configurable: true }); Object.defineProperty(FullTextDocument.prototype, "languageId", { get: function () { return this._languageId; }, enumerable: false, configurable: true }); Object.defineProperty(FullTextDocument.prototype, "version", { get: function () { return this._version; }, enumerable: false, configurable: true }); FullTextDocument.prototype.getText = function (range) { if (range) { var start = this.offsetAt(range.start); var end = this.offsetAt(range.end); return this._content.substring(start, end); } return this._content; }; FullTextDocument.prototype.update = function (event, version) { this._content = event.text; this._version = version; this._lineOffsets = undefined; }; FullTextDocument.prototype.getLineOffsets = function () { if (this._lineOffsets === undefined) { var lineOffsets = []; var text = this._content; var isLineStart = true; for (var i = 0; i < text.length; i++) { if (isLineStart) { lineOffsets.push(i); isLineStart = false; } var ch = text.charAt(i); isLineStart = (ch === '\r' || ch === '\n'); if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') { i++; } } if (isLineStart && text.length > 0) { lineOffsets.push(text.length); } this._lineOffsets = lineOffsets; } return this._lineOffsets; }; FullTextDocument.prototype.positionAt = function (offset) { offset = Math.max(Math.min(offset, this._content.length), 0); var lineOffsets = this.getLineOffsets(); var low = 0, high = lineOffsets.length; if (high === 0) { return Position.create(0, offset); } while (low < high) { var mid = Math.floor((low + high) / 2); if (lineOffsets[mid] > offset) { high = mid; } else { low = mid + 1; } } // low is the least x for which the line offset is larger than the current offset // or array.length if no line offset is larger than the current offset var line = low - 1; return Position.create(line, offset - lineOffsets[line]); }; FullTextDocument.prototype.offsetAt = function (position) { var lineOffsets = this.getLineOffsets(); if (position.line >= lineOffsets.length) { return this._content.length; } else if (position.line < 0) { return 0; } var lineOffset = lineOffsets[position.line]; var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length; return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset); }; Object.defineProperty(FullTextDocument.prototype, "lineCount", { get: function () { return this.getLineOffsets().length; }, enumerable: false, configurable: true }); return FullTextDocument; }()); var Is; (function (Is) { var toString = Object.prototype.toString; function defined(value) { return typeof value !== 'undefined'; } Is.defined = defined; function undefined(value) { return typeof value === 'undefined'; } Is.undefined = undefined; function boolean(value) { return value === true || value === false; } Is.boolean = boolean; function string(value) { return toString.call(value) === '[object String]'; } Is.string = string; function number(value) { return toString.call(value) === '[object Number]'; } Is.number = number; function numberRange(value, min, max) { return toString.call(value) === '[object Number]' && min <= value && value <= max; } Is.numberRange = numberRange; function integer(value) { return toString.call(value) === '[object Number]' && -2147483648 <= value && value <= 2147483647; } Is.integer = integer; function uinteger(value) { return toString.call(value) === '[object Number]' && 0 <= value && value <= 2147483647; } Is.uinteger = uinteger; function func(value) { return toString.call(value) === '[object Function]'; } Is.func = func; function objectLiteral(value) { // Strictly speaking class instances pass this check as well. Since the LSP // doesn't use classes we ignore this for now. If we do we need to add something // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null` return value !== null && typeof value === 'object'; } Is.objectLiteral = objectLiteral; function typedArray(value, check) { return Array.isArray(value) && value.every(check); } Is.typedArray = typedArray; })(Is || (Is = {})); }); /***/ }), /***/ 88152: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const stringWidth = __webpack_require__(26457); const stripAnsi = __webpack_require__(44368); const ansiStyles = __webpack_require__(26434); const ESCAPES = new Set([ '\u001B', '\u009B' ]); const END_CODE = 39; const wrapAnsi = code => `${ESCAPES.values().next().value}[${code}m`; // Calculate the length of words split on ' ', ignoring // the extra characters added by ansi escape codes const wordLengths = string => string.split(' ').map(character => stringWidth(character)); // Wrap a long word across multiple rows // Ansi escape codes do not count towards length const wrapWord = (rows, word, columns) => { const characters = [...word]; let insideEscape = false; let visible = stringWidth(stripAnsi(rows[rows.length - 1])); for (const [index, character] of characters.entries()) { const characterLength = stringWidth(character); if (visible + characterLength <= columns) { rows[rows.length - 1] += character; } else { rows.push(character); visible = 0; } if (ESCAPES.has(character)) { insideEscape = true; } else if (insideEscape && character === 'm') { insideEscape = false; continue; } if (insideEscape) { continue; } visible += characterLength; if (visible === columns && index < characters.length - 1) { rows.push(''); visible = 0; } } // It's possible that the last row we copy over is only // ansi escape characters, handle this edge-case if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) { rows[rows.length - 2] += rows.pop(); } }; // Trims spaces from a string ignoring invisible sequences const stringVisibleTrimSpacesRight = str => { const words = str.split(' '); let last = words.length; while (last > 0) { if (stringWidth(words[last - 1]) > 0) { break; } last--; } if (last === words.length) { return str; } return words.slice(0, last).join(' ') + words.slice(last).join(''); }; // The wrap-ansi module can be invoked // in either 'hard' or 'soft' wrap mode // // 'hard' will never allow a string to take up more // than columns characters // // 'soft' allows long words to expand past the column length const exec = (string, columns, options = {}) => { if (options.trim !== false && string.trim() === '') { return ''; } let pre = ''; let ret = ''; let escapeCode; const lengths = wordLengths(string); let rows = ['']; for (const [index, word] of string.split(' ').entries()) { if (options.trim !== false) { rows[rows.length - 1] = rows[rows.length - 1].trimLeft(); } let rowLength = stringWidth(rows[rows.length - 1]); if (index !== 0) { if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) { // If we start with a new word but the current row length equals the length of the columns, add a new row rows.push(''); rowLength = 0; } if (rowLength > 0 || options.trim === false) { rows[rows.length - 1] += ' '; rowLength++; } } // In 'hard' wrap mode, the length of a line is // never allowed to extend past 'columns' if (options.hard && lengths[index] > columns) { const remainingColumns = (columns - rowLength); const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns); const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns); if (breaksStartingNextLine < breaksStartingThisLine) { rows.push(''); } wrapWord(rows, word, columns); continue; } if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) { if (options.wordWrap === false && rowLength < columns) { wrapWord(rows, word, columns); continue; } rows.push(''); } if (rowLength + lengths[index] > columns && options.wordWrap === false) { wrapWord(rows, word, columns); continue; } rows[rows.length - 1] += word; } if (options.trim !== false) { rows = rows.map(stringVisibleTrimSpacesRight); } pre = rows.join('\n'); for (const [index, character] of [...pre].entries()) { ret += character; if (ESCAPES.has(character)) { const code = parseFloat(/\d[^m]*/.exec(pre.slice(index, index + 4))); escapeCode = code === END_CODE ? null : code; } const code = ansiStyles.codes.get(Number(escapeCode)); if (escapeCode && code) { if (pre[index + 1] === '\n') { ret += wrapAnsi(code); } else if (character === '\n') { ret += wrapAnsi(escapeCode); } } } return ret; }; // For each newline, invoke the method separately module.exports = (string, columns, options) => { return String(string) .normalize() .split('\n') .map(line => exec(line, columns, options)) .join('\n'); }; /***/ }), /***/ 50120: /***/ ((module) => { "use strict"; module.exports = options => { options = Object.assign({ onlyFirst: false }, options); const pattern = [ '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' ].join('|'); return new RegExp(pattern, options.onlyFirst ? undefined : 'g'); }; /***/ }), /***/ 33458: /***/ ((module) => { "use strict"; module.exports = function () { // https://mths.be/emoji return /\uD83C\uDFF4(?:\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74)\uDB40\uDC7F|\u200D\u2620\uFE0F)|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC68(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|(?:\uD83C[\uDFFB-\uDFFF])\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3]))|\uD83D\uDC69\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|\uD83D\uDC68(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83D\uDC69\u200D[\u2695\u2696\u2708])\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC68(?:\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDD1-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDEEB\uDEEC\uDEF4-\uDEF9]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD70\uDD73-\uDD76\uDD7A\uDD7C-\uDDA2\uDDB0-\uDDB9\uDDC0-\uDDC2\uDDD0-\uDDFF])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEF9]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD70\uDD73-\uDD76\uDD7A\uDD7C-\uDDA2\uDDB0-\uDDB9\uDDC0-\uDDC2\uDDD0-\uDDFF])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC69\uDC6E\uDC70-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD26\uDD30-\uDD39\uDD3D\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDD1-\uDDDD])/g; }; /***/ }), /***/ 22055: /***/ ((module) => { "use strict"; /* eslint-disable yoda */ module.exports = x => { if (Number.isNaN(x)) { return false; } // code points are derived from: // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt if ( x >= 0x1100 && ( x <= 0x115f || // Hangul Jamo x === 0x2329 || // LEFT-POINTING ANGLE BRACKET x === 0x232a || // RIGHT-POINTING ANGLE BRACKET // CJK Radicals Supplement .. Enclosed CJK Letters and Months (0x2e80 <= x && x <= 0x3247 && x !== 0x303f) || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A (0x3250 <= x && x <= 0x4dbf) || // CJK Unified Ideographs .. Yi Radicals (0x4e00 <= x && x <= 0xa4c6) || // Hangul Jamo Extended-A (0xa960 <= x && x <= 0xa97c) || // Hangul Syllables (0xac00 <= x && x <= 0xd7a3) || // CJK Compatibility Ideographs (0xf900 <= x && x <= 0xfaff) || // Vertical Forms (0xfe10 <= x && x <= 0xfe19) || // CJK Compatibility Forms .. Small Form Variants (0xfe30 <= x && x <= 0xfe6b) || // Halfwidth and Fullwidth Forms (0xff01 <= x && x <= 0xff60) || (0xffe0 <= x && x <= 0xffe6) || // Kana Supplement (0x1b000 <= x && x <= 0x1b001) || // Enclosed Ideographic Supplement (0x1f200 <= x && x <= 0x1f251) || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane (0x20000 <= x && x <= 0x3fffd) ) ) { return true; } return false; }; /***/ }), /***/ 26457: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const stripAnsi = __webpack_require__(44368); const isFullwidthCodePoint = __webpack_require__(22055); const emojiRegex = __webpack_require__(33458)(); module.exports = input => { input = input.replace(emojiRegex, ' '); if (typeof input !== 'string' || input.length === 0) { return 0; } input = stripAnsi(input); let width = 0; for (let i = 0; i < input.length; i++) { const code = input.codePointAt(i); // Ignore control characters if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { continue; } // Ignore combining characters if (code >= 0x300 && code <= 0x36F) { continue; } // Surrogates if (code > 0xFFFF) { i++; } width += isFullwidthCodePoint(code) ? 2 : 1; } return width; }; /***/ }), /***/ 44368: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const ansiRegex = __webpack_require__(50120); const stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; module.exports = stripAnsi; module.exports["default"] = stripAnsi; /***/ }), /***/ 50306: /***/ (function(__unused_webpack_module, exports) { // Generated by CoffeeScript 1.12.7 (function() { "use strict"; exports.stripBOM = function(str) { if (str[0] === '\uFEFF') { return str.substring(1); } else { return str; } }; }).call(this); /***/ }), /***/ 34096: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { "use strict"; var builder, defaults, escapeCDATA, requiresCDATA, wrapCDATA, hasProp = {}.hasOwnProperty; builder = __webpack_require__(5532); defaults = __webpack_require__(38381).defaults; requiresCDATA = function(entry) { return typeof entry === "string" && (entry.indexOf('&') >= 0 || entry.indexOf('>') >= 0 || entry.indexOf('<') >= 0); }; wrapCDATA = function(entry) { return ""; }; escapeCDATA = function(entry) { return entry.replace(']]>', ']]]]>'); }; exports.Builder = (function() { function Builder(opts) { var key, ref, value; this.options = {}; ref = defaults["0.2"]; for (key in ref) { if (!hasProp.call(ref, key)) continue; value = ref[key]; this.options[key] = value; } for (key in opts) { if (!hasProp.call(opts, key)) continue; value = opts[key]; this.options[key] = value; } } Builder.prototype.buildObject = function(rootObj) { var attrkey, charkey, render, rootElement, rootName; attrkey = this.options.attrkey; charkey = this.options.charkey; if ((Object.keys(rootObj).length === 1) && (this.options.rootName === defaults['0.2'].rootName)) { rootName = Object.keys(rootObj)[0]; rootObj = rootObj[rootName]; } else { rootName = this.options.rootName; } render = (function(_this) { return function(element, obj) { var attr, child, entry, index, key, value; if (typeof obj !== 'object') { if (_this.options.cdata && requiresCDATA(obj)) { element.raw(wrapCDATA(obj)); } else { element.txt(obj); } } else if (Array.isArray(obj)) { for (index in obj) { if (!hasProp.call(obj, index)) continue; child = obj[index]; for (key in child) { entry = child[key]; element = render(element.ele(key), entry).up(); } } } else { for (key in obj) { if (!hasProp.call(obj, key)) continue; child = obj[key]; if (key === attrkey) { if (typeof child === "object") { for (attr in child) { value = child[attr]; element = element.att(attr, value); } } } else if (key === charkey) { if (_this.options.cdata && requiresCDATA(child)) { element = element.raw(wrapCDATA(child)); } else { element = element.txt(child); } } else if (Array.isArray(child)) { for (index in child) { if (!hasProp.call(child, index)) continue; entry = child[index]; if (typeof entry === 'string') { if (_this.options.cdata && requiresCDATA(entry)) { element = element.ele(key).raw(wrapCDATA(entry)).up(); } else { element = element.ele(key, entry).up(); } } else { element = render(element.ele(key), entry).up(); } } } else if (typeof child === "object") { element = render(element.ele(key), child).up(); } else { if (typeof child === 'string' && _this.options.cdata && requiresCDATA(child)) { element = element.ele(key).raw(wrapCDATA(child)).up(); } else { if (child == null) { child = ''; } element = element.ele(key, child.toString()).up(); } } } } return element; }; })(this); rootElement = builder.create(rootName, this.options.xmldec, this.options.doctype, { headless: this.options.headless, allowSurrogateChars: this.options.allowSurrogateChars }); return render(rootElement, rootObj).end(this.options.renderOpts); }; return Builder; })(); }).call(this); /***/ }), /***/ 38381: /***/ (function(__unused_webpack_module, exports) { // Generated by CoffeeScript 1.12.7 (function() { exports.defaults = { "0.1": { explicitCharkey: false, trim: true, normalize: true, normalizeTags: false, attrkey: "@", charkey: "#", explicitArray: false, ignoreAttrs: false, mergeAttrs: false, explicitRoot: false, validator: null, xmlns: false, explicitChildren: false, childkey: '@@', charsAsChildren: false, includeWhiteChars: false, async: false, strict: true, attrNameProcessors: null, attrValueProcessors: null, tagNameProcessors: null, valueProcessors: null, emptyTag: '' }, "0.2": { explicitCharkey: false, trim: false, normalize: false, normalizeTags: false, attrkey: "$", charkey: "_", explicitArray: true, ignoreAttrs: false, mergeAttrs: false, explicitRoot: true, validator: null, xmlns: false, explicitChildren: false, preserveChildrenOrder: false, childkey: '$$', charsAsChildren: false, includeWhiteChars: false, async: false, strict: true, attrNameProcessors: null, attrValueProcessors: null, tagNameProcessors: null, valueProcessors: null, rootName: 'root', xmldec: { 'version': '1.0', 'encoding': 'UTF-8', 'standalone': true }, doctype: null, renderOpts: { 'pretty': true, 'indent': ' ', 'newline': '\n' }, headless: false, chunkSize: 10000, emptyTag: '', cdata: false } }; }).call(this); /***/ }), /***/ 99082: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { "use strict"; var bom, defaults, defineProperty, events, isEmpty, processItem, processors, sax, setImmediate, bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; sax = __webpack_require__(36099); events = __webpack_require__(82361); bom = __webpack_require__(50306); processors = __webpack_require__(7526); setImmediate = __webpack_require__(39512).setImmediate; defaults = __webpack_require__(38381).defaults; isEmpty = function(thing) { return typeof thing === "object" && (thing != null) && Object.keys(thing).length === 0; }; processItem = function(processors, item, key) { var i, len, process; for (i = 0, len = processors.length; i < len; i++) { process = processors[i]; item = process(item, key); } return item; }; defineProperty = function(obj, key, value) { var descriptor; descriptor = Object.create(null); descriptor.value = value; descriptor.writable = true; descriptor.enumerable = true; descriptor.configurable = true; return Object.defineProperty(obj, key, descriptor); }; exports.Parser = (function(superClass) { extend(Parser, superClass); function Parser(opts) { this.parseStringPromise = bind(this.parseStringPromise, this); this.parseString = bind(this.parseString, this); this.reset = bind(this.reset, this); this.assignOrPush = bind(this.assignOrPush, this); this.processAsync = bind(this.processAsync, this); var key, ref, value; if (!(this instanceof exports.Parser)) { return new exports.Parser(opts); } this.options = {}; ref = defaults["0.2"]; for (key in ref) { if (!hasProp.call(ref, key)) continue; value = ref[key]; this.options[key] = value; } for (key in opts) { if (!hasProp.call(opts, key)) continue; value = opts[key]; this.options[key] = value; } if (this.options.xmlns) { this.options.xmlnskey = this.options.attrkey + "ns"; } if (this.options.normalizeTags) { if (!this.options.tagNameProcessors) { this.options.tagNameProcessors = []; } this.options.tagNameProcessors.unshift(processors.normalize); } this.reset(); } Parser.prototype.processAsync = function() { var chunk, err; try { if (this.remaining.length <= this.options.chunkSize) { chunk = this.remaining; this.remaining = ''; this.saxParser = this.saxParser.write(chunk); return this.saxParser.close(); } else { chunk = this.remaining.substr(0, this.options.chunkSize); this.remaining = this.remaining.substr(this.options.chunkSize, this.remaining.length); this.saxParser = this.saxParser.write(chunk); return setImmediate(this.processAsync); } } catch (error1) { err = error1; if (!this.saxParser.errThrown) { this.saxParser.errThrown = true; return this.emit(err); } } }; Parser.prototype.assignOrPush = function(obj, key, newValue) { if (!(key in obj)) { if (!this.options.explicitArray) { return defineProperty(obj, key, newValue); } else { return defineProperty(obj, key, [newValue]); } } else { if (!(obj[key] instanceof Array)) { defineProperty(obj, key, [obj[key]]); } return obj[key].push(newValue); } }; Parser.prototype.reset = function() { var attrkey, charkey, ontext, stack; this.removeAllListeners(); this.saxParser = sax.parser(this.options.strict, { trim: false, normalize: false, xmlns: this.options.xmlns }); this.saxParser.errThrown = false; this.saxParser.onerror = (function(_this) { return function(error) { _this.saxParser.resume(); if (!_this.saxParser.errThrown) { _this.saxParser.errThrown = true; return _this.emit("error", error); } }; })(this); this.saxParser.onend = (function(_this) { return function() { if (!_this.saxParser.ended) { _this.saxParser.ended = true; return _this.emit("end", _this.resultObject); } }; })(this); this.saxParser.ended = false; this.EXPLICIT_CHARKEY = this.options.explicitCharkey; this.resultObject = null; stack = []; attrkey = this.options.attrkey; charkey = this.options.charkey; this.saxParser.onopentag = (function(_this) { return function(node) { var key, newValue, obj, processedKey, ref; obj = {}; obj[charkey] = ""; if (!_this.options.ignoreAttrs) { ref = node.attributes; for (key in ref) { if (!hasProp.call(ref, key)) continue; if (!(attrkey in obj) && !_this.options.mergeAttrs) { obj[attrkey] = {}; } newValue = _this.options.attrValueProcessors ? processItem(_this.options.attrValueProcessors, node.attributes[key], key) : node.attributes[key]; processedKey = _this.options.attrNameProcessors ? processItem(_this.options.attrNameProcessors, key) : key; if (_this.options.mergeAttrs) { _this.assignOrPush(obj, processedKey, newValue); } else { defineProperty(obj[attrkey], processedKey, newValue); } } } obj["#name"] = _this.options.tagNameProcessors ? processItem(_this.options.tagNameProcessors, node.name) : node.name; if (_this.options.xmlns) { obj[_this.options.xmlnskey] = { uri: node.uri, local: node.local }; } return stack.push(obj); }; })(this); this.saxParser.onclosetag = (function(_this) { return function() { var cdata, emptyStr, key, node, nodeName, obj, objClone, old, s, xpath; obj = stack.pop(); nodeName = obj["#name"]; if (!_this.options.explicitChildren || !_this.options.preserveChildrenOrder) { delete obj["#name"]; } if (obj.cdata === true) { cdata = obj.cdata; delete obj.cdata; } s = stack[stack.length - 1]; if (obj[charkey].match(/^\s*$/) && !cdata) { emptyStr = obj[charkey]; delete obj[charkey]; } else { if (_this.options.trim) { obj[charkey] = obj[charkey].trim(); } if (_this.options.normalize) { obj[charkey] = obj[charkey].replace(/\s{2,}/g, " ").trim(); } obj[charkey] = _this.options.valueProcessors ? processItem(_this.options.valueProcessors, obj[charkey], nodeName) : obj[charkey]; if (Object.keys(obj).length === 1 && charkey in obj && !_this.EXPLICIT_CHARKEY) { obj = obj[charkey]; } } if (isEmpty(obj)) { if (typeof _this.options.emptyTag === 'function') { obj = _this.options.emptyTag(); } else { obj = _this.options.emptyTag !== '' ? _this.options.emptyTag : emptyStr; } } if (_this.options.validator != null) { xpath = "/" + ((function() { var i, len, results; results = []; for (i = 0, len = stack.length; i < len; i++) { node = stack[i]; results.push(node["#name"]); } return results; })()).concat(nodeName).join("/"); (function() { var err; try { return obj = _this.options.validator(xpath, s && s[nodeName], obj); } catch (error1) { err = error1; return _this.emit("error", err); } })(); } if (_this.options.explicitChildren && !_this.options.mergeAttrs && typeof obj === 'object') { if (!_this.options.preserveChildrenOrder) { node = {}; if (_this.options.attrkey in obj) { node[_this.options.attrkey] = obj[_this.options.attrkey]; delete obj[_this.options.attrkey]; } if (!_this.options.charsAsChildren && _this.options.charkey in obj) { node[_this.options.charkey] = obj[_this.options.charkey]; delete obj[_this.options.charkey]; } if (Object.getOwnPropertyNames(obj).length > 0) { node[_this.options.childkey] = obj; } obj = node; } else if (s) { s[_this.options.childkey] = s[_this.options.childkey] || []; objClone = {}; for (key in obj) { if (!hasProp.call(obj, key)) continue; defineProperty(objClone, key, obj[key]); } s[_this.options.childkey].push(objClone); delete obj["#name"]; if (Object.keys(obj).length === 1 && charkey in obj && !_this.EXPLICIT_CHARKEY) { obj = obj[charkey]; } } } if (stack.length > 0) { return _this.assignOrPush(s, nodeName, obj); } else { if (_this.options.explicitRoot) { old = obj; obj = {}; defineProperty(obj, nodeName, old); } _this.resultObject = obj; _this.saxParser.ended = true; return _this.emit("end", _this.resultObject); } }; })(this); ontext = (function(_this) { return function(text) { var charChild, s; s = stack[stack.length - 1]; if (s) { s[charkey] += text; if (_this.options.explicitChildren && _this.options.preserveChildrenOrder && _this.options.charsAsChildren && (_this.options.includeWhiteChars || text.replace(/\\n/g, '').trim() !== '')) { s[_this.options.childkey] = s[_this.options.childkey] || []; charChild = { '#name': '__text__' }; charChild[charkey] = text; if (_this.options.normalize) { charChild[charkey] = charChild[charkey].replace(/\s{2,}/g, " ").trim(); } s[_this.options.childkey].push(charChild); } return s; } }; })(this); this.saxParser.ontext = ontext; return this.saxParser.oncdata = (function(_this) { return function(text) { var s; s = ontext(text); if (s) { return s.cdata = true; } }; })(this); }; Parser.prototype.parseString = function(str, cb) { var err; if ((cb != null) && typeof cb === "function") { this.on("end", function(result) { this.reset(); return cb(null, result); }); this.on("error", function(err) { this.reset(); return cb(err); }); } try { str = str.toString(); if (str.trim() === '') { this.emit("end", null); return true; } str = bom.stripBOM(str); if (this.options.async) { this.remaining = str; setImmediate(this.processAsync); return this.saxParser; } return this.saxParser.write(str).close(); } catch (error1) { err = error1; if (!(this.saxParser.errThrown || this.saxParser.ended)) { this.emit('error', err); return this.saxParser.errThrown = true; } else if (this.saxParser.ended) { throw err; } } }; Parser.prototype.parseStringPromise = function(str) { return new Promise((function(_this) { return function(resolve, reject) { return _this.parseString(str, function(err, value) { if (err) { return reject(err); } else { return resolve(value); } }); }; })(this)); }; return Parser; })(events); exports.parseString = function(str, a, b) { var cb, options, parser; if (b != null) { if (typeof b === 'function') { cb = b; } if (typeof a === 'object') { options = a; } } else { if (typeof a === 'function') { cb = a; } options = {}; } parser = new exports.Parser(options); return parser.parseString(str, cb); }; exports.parseStringPromise = function(str, a) { var options, parser; if (typeof a === 'object') { options = a; } parser = new exports.Parser(options); return parser.parseStringPromise(str); }; }).call(this); /***/ }), /***/ 7526: /***/ (function(__unused_webpack_module, exports) { // Generated by CoffeeScript 1.12.7 (function() { "use strict"; var prefixMatch; prefixMatch = new RegExp(/(?!xmlns)^.*:/); exports.normalize = function(str) { return str.toLowerCase(); }; exports.firstCharLowerCase = function(str) { return str.charAt(0).toLowerCase() + str.slice(1); }; exports.stripPrefix = function(str) { return str.replace(prefixMatch, ''); }; exports.parseNumbers = function(str) { if (!isNaN(str)) { str = str % 1 === 0 ? parseInt(str, 10) : parseFloat(str); } return str; }; exports.parseBooleans = function(str) { if (/^(?:true|false)$/i.test(str)) { str = str.toLowerCase() === 'true'; } return str; }; }).call(this); /***/ }), /***/ 5055: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { "use strict"; var builder, defaults, parser, processors, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; defaults = __webpack_require__(38381); builder = __webpack_require__(34096); parser = __webpack_require__(99082); processors = __webpack_require__(7526); exports.defaults = defaults.defaults; exports.processors = processors; exports.ValidationError = (function(superClass) { extend(ValidationError, superClass); function ValidationError(message) { this.message = message; } return ValidationError; })(Error); exports.Builder = builder.Builder; exports.Parser = parser.Parser; exports.parseString = parser.parseString; exports.parseStringPromise = parser.parseStringPromise; }).call(this); /***/ }), /***/ 17557: /***/ (function(module) { // Generated by CoffeeScript 1.12.7 (function() { module.exports = { Disconnected: 1, Preceding: 2, Following: 4, Contains: 8, ContainedBy: 16, ImplementationSpecific: 32 }; }).call(this); /***/ }), /***/ 39335: /***/ (function(module) { // Generated by CoffeeScript 1.12.7 (function() { module.exports = { Element: 1, Attribute: 2, Text: 3, CData: 4, EntityReference: 5, EntityDeclaration: 6, ProcessingInstruction: 7, Comment: 8, Document: 9, DocType: 10, DocumentFragment: 11, NotationDeclaration: 12, Declaration: 201, Raw: 202, AttributeDeclaration: 203, ElementDeclaration: 204, Dummy: 205 }; }).call(this); /***/ }), /***/ 78369: /***/ (function(module) { // Generated by CoffeeScript 1.12.7 (function() { var assign, getValue, isArray, isEmpty, isFunction, isObject, isPlainObject, slice = [].slice, hasProp = {}.hasOwnProperty; assign = function() { var i, key, len, source, sources, target; target = arguments[0], sources = 2 <= arguments.length ? slice.call(arguments, 1) : []; if (isFunction(Object.assign)) { Object.assign.apply(null, arguments); } else { for (i = 0, len = sources.length; i < len; i++) { source = sources[i]; if (source != null) { for (key in source) { if (!hasProp.call(source, key)) continue; target[key] = source[key]; } } } } return target; }; isFunction = function(val) { return !!val && Object.prototype.toString.call(val) === '[object Function]'; }; isObject = function(val) { var ref; return !!val && ((ref = typeof val) === 'function' || ref === 'object'); }; isArray = function(val) { if (isFunction(Array.isArray)) { return Array.isArray(val); } else { return Object.prototype.toString.call(val) === '[object Array]'; } }; isEmpty = function(val) { var key; if (isArray(val)) { return !val.length; } else { for (key in val) { if (!hasProp.call(val, key)) continue; return false; } return true; } }; isPlainObject = function(val) { var ctor, proto; return isObject(val) && (proto = Object.getPrototypeOf(val)) && (ctor = proto.constructor) && (typeof ctor === 'function') && (ctor instanceof ctor) && (Function.prototype.toString.call(ctor) === Function.prototype.toString.call(Object)); }; getValue = function(obj) { if (isFunction(obj.valueOf)) { return obj.valueOf(); } else { return obj; } }; module.exports.assign = assign; module.exports.isFunction = isFunction; module.exports.isObject = isObject; module.exports.isArray = isArray; module.exports.isEmpty = isEmpty; module.exports.isPlainObject = isPlainObject; module.exports.getValue = getValue; }).call(this); /***/ }), /***/ 30594: /***/ (function(module) { // Generated by CoffeeScript 1.12.7 (function() { module.exports = { None: 0, OpenTag: 1, InsideTag: 2, CloseTag: 3 }; }).call(this); /***/ }), /***/ 72750: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var NodeType, XMLAttribute, XMLNode; NodeType = __webpack_require__(39335); XMLNode = __webpack_require__(32026); module.exports = XMLAttribute = (function() { function XMLAttribute(parent, name, value) { this.parent = parent; if (this.parent) { this.options = this.parent.options; this.stringify = this.parent.stringify; } if (name == null) { throw new Error("Missing attribute name. " + this.debugInfo(name)); } this.name = this.stringify.name(name); this.value = this.stringify.attValue(value); this.type = NodeType.Attribute; this.isId = false; this.schemaTypeInfo = null; } Object.defineProperty(XMLAttribute.prototype, 'nodeType', { get: function() { return this.type; } }); Object.defineProperty(XMLAttribute.prototype, 'ownerElement', { get: function() { return this.parent; } }); Object.defineProperty(XMLAttribute.prototype, 'textContent', { get: function() { return this.value; }, set: function(value) { return this.value = value || ''; } }); Object.defineProperty(XMLAttribute.prototype, 'namespaceURI', { get: function() { return ''; } }); Object.defineProperty(XMLAttribute.prototype, 'prefix', { get: function() { return ''; } }); Object.defineProperty(XMLAttribute.prototype, 'localName', { get: function() { return this.name; } }); Object.defineProperty(XMLAttribute.prototype, 'specified', { get: function() { return true; } }); XMLAttribute.prototype.clone = function() { return Object.create(this); }; XMLAttribute.prototype.toString = function(options) { return this.options.writer.attribute(this, this.options.writer.filterOptions(options)); }; XMLAttribute.prototype.debugInfo = function(name) { name = name || this.name; if (name == null) { return "parent: <" + this.parent.name + ">"; } else { return "attribute: {" + name + "}, parent: <" + this.parent.name + ">"; } }; XMLAttribute.prototype.isEqualNode = function(node) { if (node.namespaceURI !== this.namespaceURI) { return false; } if (node.prefix !== this.prefix) { return false; } if (node.localName !== this.localName) { return false; } if (node.value !== this.value) { return false; } return true; }; return XMLAttribute; })(); }).call(this); /***/ }), /***/ 66170: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var NodeType, XMLCData, XMLCharacterData, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; NodeType = __webpack_require__(39335); XMLCharacterData = __webpack_require__(6488); module.exports = XMLCData = (function(superClass) { extend(XMLCData, superClass); function XMLCData(parent, text) { XMLCData.__super__.constructor.call(this, parent); if (text == null) { throw new Error("Missing CDATA text. " + this.debugInfo()); } this.name = "#cdata-section"; this.type = NodeType.CData; this.value = this.stringify.cdata(text); } XMLCData.prototype.clone = function() { return Object.create(this); }; XMLCData.prototype.toString = function(options) { return this.options.writer.cdata(this, this.options.writer.filterOptions(options)); }; return XMLCData; })(XMLCharacterData); }).call(this); /***/ }), /***/ 6488: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var XMLCharacterData, XMLNode, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; XMLNode = __webpack_require__(32026); module.exports = XMLCharacterData = (function(superClass) { extend(XMLCharacterData, superClass); function XMLCharacterData(parent) { XMLCharacterData.__super__.constructor.call(this, parent); this.value = ''; } Object.defineProperty(XMLCharacterData.prototype, 'data', { get: function() { return this.value; }, set: function(value) { return this.value = value || ''; } }); Object.defineProperty(XMLCharacterData.prototype, 'length', { get: function() { return this.value.length; } }); Object.defineProperty(XMLCharacterData.prototype, 'textContent', { get: function() { return this.value; }, set: function(value) { return this.value = value || ''; } }); XMLCharacterData.prototype.clone = function() { return Object.create(this); }; XMLCharacterData.prototype.substringData = function(offset, count) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLCharacterData.prototype.appendData = function(arg) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLCharacterData.prototype.insertData = function(offset, arg) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLCharacterData.prototype.deleteData = function(offset, count) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLCharacterData.prototype.replaceData = function(offset, count, arg) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLCharacterData.prototype.isEqualNode = function(node) { if (!XMLCharacterData.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) { return false; } if (node.data !== this.data) { return false; } return true; }; return XMLCharacterData; })(XMLNode); }).call(this); /***/ }), /***/ 62096: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var NodeType, XMLCharacterData, XMLComment, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; NodeType = __webpack_require__(39335); XMLCharacterData = __webpack_require__(6488); module.exports = XMLComment = (function(superClass) { extend(XMLComment, superClass); function XMLComment(parent, text) { XMLComment.__super__.constructor.call(this, parent); if (text == null) { throw new Error("Missing comment text. " + this.debugInfo()); } this.name = "#comment"; this.type = NodeType.Comment; this.value = this.stringify.comment(text); } XMLComment.prototype.clone = function() { return Object.create(this); }; XMLComment.prototype.toString = function(options) { return this.options.writer.comment(this, this.options.writer.filterOptions(options)); }; return XMLComment; })(XMLCharacterData); }).call(this); /***/ }), /***/ 30383: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var XMLDOMConfiguration, XMLDOMErrorHandler, XMLDOMStringList; XMLDOMErrorHandler = __webpack_require__(93933); XMLDOMStringList = __webpack_require__(66210); module.exports = XMLDOMConfiguration = (function() { function XMLDOMConfiguration() { var clonedSelf; this.defaultParams = { "canonical-form": false, "cdata-sections": false, "comments": false, "datatype-normalization": false, "element-content-whitespace": true, "entities": true, "error-handler": new XMLDOMErrorHandler(), "infoset": true, "validate-if-schema": false, "namespaces": true, "namespace-declarations": true, "normalize-characters": false, "schema-location": '', "schema-type": '', "split-cdata-sections": true, "validate": false, "well-formed": true }; this.params = clonedSelf = Object.create(this.defaultParams); } Object.defineProperty(XMLDOMConfiguration.prototype, 'parameterNames', { get: function() { return new XMLDOMStringList(Object.keys(this.defaultParams)); } }); XMLDOMConfiguration.prototype.getParameter = function(name) { if (this.params.hasOwnProperty(name)) { return this.params[name]; } else { return null; } }; XMLDOMConfiguration.prototype.canSetParameter = function(name, value) { return true; }; XMLDOMConfiguration.prototype.setParameter = function(name, value) { if (value != null) { return this.params[name] = value; } else { return delete this.params[name]; } }; return XMLDOMConfiguration; })(); }).call(this); /***/ }), /***/ 93933: /***/ (function(module) { // Generated by CoffeeScript 1.12.7 (function() { var XMLDOMErrorHandler; module.exports = XMLDOMErrorHandler = (function() { function XMLDOMErrorHandler() {} XMLDOMErrorHandler.prototype.handleError = function(error) { throw new Error(error); }; return XMLDOMErrorHandler; })(); }).call(this); /***/ }), /***/ 91770: /***/ (function(module) { // Generated by CoffeeScript 1.12.7 (function() { var XMLDOMImplementation; module.exports = XMLDOMImplementation = (function() { function XMLDOMImplementation() {} XMLDOMImplementation.prototype.hasFeature = function(feature, version) { return true; }; XMLDOMImplementation.prototype.createDocumentType = function(qualifiedName, publicId, systemId) { throw new Error("This DOM method is not implemented."); }; XMLDOMImplementation.prototype.createDocument = function(namespaceURI, qualifiedName, doctype) { throw new Error("This DOM method is not implemented."); }; XMLDOMImplementation.prototype.createHTMLDocument = function(title) { throw new Error("This DOM method is not implemented."); }; XMLDOMImplementation.prototype.getFeature = function(feature, version) { throw new Error("This DOM method is not implemented."); }; return XMLDOMImplementation; })(); }).call(this); /***/ }), /***/ 66210: /***/ (function(module) { // Generated by CoffeeScript 1.12.7 (function() { var XMLDOMStringList; module.exports = XMLDOMStringList = (function() { function XMLDOMStringList(arr) { this.arr = arr || []; } Object.defineProperty(XMLDOMStringList.prototype, 'length', { get: function() { return this.arr.length; } }); XMLDOMStringList.prototype.item = function(index) { return this.arr[index] || null; }; XMLDOMStringList.prototype.contains = function(str) { return this.arr.indexOf(str) !== -1; }; return XMLDOMStringList; })(); }).call(this); /***/ }), /***/ 51179: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var NodeType, XMLDTDAttList, XMLNode, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; XMLNode = __webpack_require__(32026); NodeType = __webpack_require__(39335); module.exports = XMLDTDAttList = (function(superClass) { extend(XMLDTDAttList, superClass); function XMLDTDAttList(parent, elementName, attributeName, attributeType, defaultValueType, defaultValue) { XMLDTDAttList.__super__.constructor.call(this, parent); if (elementName == null) { throw new Error("Missing DTD element name. " + this.debugInfo()); } if (attributeName == null) { throw new Error("Missing DTD attribute name. " + this.debugInfo(elementName)); } if (!attributeType) { throw new Error("Missing DTD attribute type. " + this.debugInfo(elementName)); } if (!defaultValueType) { throw new Error("Missing DTD attribute default. " + this.debugInfo(elementName)); } if (defaultValueType.indexOf('#') !== 0) { defaultValueType = '#' + defaultValueType; } if (!defaultValueType.match(/^(#REQUIRED|#IMPLIED|#FIXED|#DEFAULT)$/)) { throw new Error("Invalid default value type; expected: #REQUIRED, #IMPLIED, #FIXED or #DEFAULT. " + this.debugInfo(elementName)); } if (defaultValue && !defaultValueType.match(/^(#FIXED|#DEFAULT)$/)) { throw new Error("Default value only applies to #FIXED or #DEFAULT. " + this.debugInfo(elementName)); } this.elementName = this.stringify.name(elementName); this.type = NodeType.AttributeDeclaration; this.attributeName = this.stringify.name(attributeName); this.attributeType = this.stringify.dtdAttType(attributeType); if (defaultValue) { this.defaultValue = this.stringify.dtdAttDefault(defaultValue); } this.defaultValueType = defaultValueType; } XMLDTDAttList.prototype.toString = function(options) { return this.options.writer.dtdAttList(this, this.options.writer.filterOptions(options)); }; return XMLDTDAttList; })(XMLNode); }).call(this); /***/ }), /***/ 36347: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var NodeType, XMLDTDElement, XMLNode, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; XMLNode = __webpack_require__(32026); NodeType = __webpack_require__(39335); module.exports = XMLDTDElement = (function(superClass) { extend(XMLDTDElement, superClass); function XMLDTDElement(parent, name, value) { XMLDTDElement.__super__.constructor.call(this, parent); if (name == null) { throw new Error("Missing DTD element name. " + this.debugInfo()); } if (!value) { value = '(#PCDATA)'; } if (Array.isArray(value)) { value = '(' + value.join(',') + ')'; } this.name = this.stringify.name(name); this.type = NodeType.ElementDeclaration; this.value = this.stringify.dtdElementValue(value); } XMLDTDElement.prototype.toString = function(options) { return this.options.writer.dtdElement(this, this.options.writer.filterOptions(options)); }; return XMLDTDElement; })(XMLNode); }).call(this); /***/ }), /***/ 99078: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var NodeType, XMLDTDEntity, XMLNode, isObject, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; isObject = __webpack_require__(78369).isObject; XMLNode = __webpack_require__(32026); NodeType = __webpack_require__(39335); module.exports = XMLDTDEntity = (function(superClass) { extend(XMLDTDEntity, superClass); function XMLDTDEntity(parent, pe, name, value) { XMLDTDEntity.__super__.constructor.call(this, parent); if (name == null) { throw new Error("Missing DTD entity name. " + this.debugInfo(name)); } if (value == null) { throw new Error("Missing DTD entity value. " + this.debugInfo(name)); } this.pe = !!pe; this.name = this.stringify.name(name); this.type = NodeType.EntityDeclaration; if (!isObject(value)) { this.value = this.stringify.dtdEntityValue(value); this.internal = true; } else { if (!value.pubID && !value.sysID) { throw new Error("Public and/or system identifiers are required for an external entity. " + this.debugInfo(name)); } if (value.pubID && !value.sysID) { throw new Error("System identifier is required for a public external entity. " + this.debugInfo(name)); } this.internal = false; if (value.pubID != null) { this.pubID = this.stringify.dtdPubID(value.pubID); } if (value.sysID != null) { this.sysID = this.stringify.dtdSysID(value.sysID); } if (value.nData != null) { this.nData = this.stringify.dtdNData(value.nData); } if (this.pe && this.nData) { throw new Error("Notation declaration is not allowed in a parameter entity. " + this.debugInfo(name)); } } } Object.defineProperty(XMLDTDEntity.prototype, 'publicId', { get: function() { return this.pubID; } }); Object.defineProperty(XMLDTDEntity.prototype, 'systemId', { get: function() { return this.sysID; } }); Object.defineProperty(XMLDTDEntity.prototype, 'notationName', { get: function() { return this.nData || null; } }); Object.defineProperty(XMLDTDEntity.prototype, 'inputEncoding', { get: function() { return null; } }); Object.defineProperty(XMLDTDEntity.prototype, 'xmlEncoding', { get: function() { return null; } }); Object.defineProperty(XMLDTDEntity.prototype, 'xmlVersion', { get: function() { return null; } }); XMLDTDEntity.prototype.toString = function(options) { return this.options.writer.dtdEntity(this, this.options.writer.filterOptions(options)); }; return XMLDTDEntity; })(XMLNode); }).call(this); /***/ }), /***/ 44777: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var NodeType, XMLDTDNotation, XMLNode, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; XMLNode = __webpack_require__(32026); NodeType = __webpack_require__(39335); module.exports = XMLDTDNotation = (function(superClass) { extend(XMLDTDNotation, superClass); function XMLDTDNotation(parent, name, value) { XMLDTDNotation.__super__.constructor.call(this, parent); if (name == null) { throw new Error("Missing DTD notation name. " + this.debugInfo(name)); } if (!value.pubID && !value.sysID) { throw new Error("Public or system identifiers are required for an external entity. " + this.debugInfo(name)); } this.name = this.stringify.name(name); this.type = NodeType.NotationDeclaration; if (value.pubID != null) { this.pubID = this.stringify.dtdPubID(value.pubID); } if (value.sysID != null) { this.sysID = this.stringify.dtdSysID(value.sysID); } } Object.defineProperty(XMLDTDNotation.prototype, 'publicId', { get: function() { return this.pubID; } }); Object.defineProperty(XMLDTDNotation.prototype, 'systemId', { get: function() { return this.sysID; } }); XMLDTDNotation.prototype.toString = function(options) { return this.options.writer.dtdNotation(this, this.options.writer.filterOptions(options)); }; return XMLDTDNotation; })(XMLNode); }).call(this); /***/ }), /***/ 59077: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var NodeType, XMLDeclaration, XMLNode, isObject, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; isObject = __webpack_require__(78369).isObject; XMLNode = __webpack_require__(32026); NodeType = __webpack_require__(39335); module.exports = XMLDeclaration = (function(superClass) { extend(XMLDeclaration, superClass); function XMLDeclaration(parent, version, encoding, standalone) { var ref; XMLDeclaration.__super__.constructor.call(this, parent); if (isObject(version)) { ref = version, version = ref.version, encoding = ref.encoding, standalone = ref.standalone; } if (!version) { version = '1.0'; } this.type = NodeType.Declaration; this.version = this.stringify.xmlVersion(version); if (encoding != null) { this.encoding = this.stringify.xmlEncoding(encoding); } if (standalone != null) { this.standalone = this.stringify.xmlStandalone(standalone); } } XMLDeclaration.prototype.toString = function(options) { return this.options.writer.declaration(this, this.options.writer.filterOptions(options)); }; return XMLDeclaration; })(XMLNode); }).call(this); /***/ }), /***/ 86544: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var NodeType, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDocType, XMLNamedNodeMap, XMLNode, isObject, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; isObject = __webpack_require__(78369).isObject; XMLNode = __webpack_require__(32026); NodeType = __webpack_require__(39335); XMLDTDAttList = __webpack_require__(51179); XMLDTDEntity = __webpack_require__(99078); XMLDTDElement = __webpack_require__(36347); XMLDTDNotation = __webpack_require__(44777); XMLNamedNodeMap = __webpack_require__(40663); module.exports = XMLDocType = (function(superClass) { extend(XMLDocType, superClass); function XMLDocType(parent, pubID, sysID) { var child, i, len, ref, ref1, ref2; XMLDocType.__super__.constructor.call(this, parent); this.type = NodeType.DocType; if (parent.children) { ref = parent.children; for (i = 0, len = ref.length; i < len; i++) { child = ref[i]; if (child.type === NodeType.Element) { this.name = child.name; break; } } } this.documentObject = parent; if (isObject(pubID)) { ref1 = pubID, pubID = ref1.pubID, sysID = ref1.sysID; } if (sysID == null) { ref2 = [pubID, sysID], sysID = ref2[0], pubID = ref2[1]; } if (pubID != null) { this.pubID = this.stringify.dtdPubID(pubID); } if (sysID != null) { this.sysID = this.stringify.dtdSysID(sysID); } } Object.defineProperty(XMLDocType.prototype, 'entities', { get: function() { var child, i, len, nodes, ref; nodes = {}; ref = this.children; for (i = 0, len = ref.length; i < len; i++) { child = ref[i]; if ((child.type === NodeType.EntityDeclaration) && !child.pe) { nodes[child.name] = child; } } return new XMLNamedNodeMap(nodes); } }); Object.defineProperty(XMLDocType.prototype, 'notations', { get: function() { var child, i, len, nodes, ref; nodes = {}; ref = this.children; for (i = 0, len = ref.length; i < len; i++) { child = ref[i]; if (child.type === NodeType.NotationDeclaration) { nodes[child.name] = child; } } return new XMLNamedNodeMap(nodes); } }); Object.defineProperty(XMLDocType.prototype, 'publicId', { get: function() { return this.pubID; } }); Object.defineProperty(XMLDocType.prototype, 'systemId', { get: function() { return this.sysID; } }); Object.defineProperty(XMLDocType.prototype, 'internalSubset', { get: function() { throw new Error("This DOM method is not implemented." + this.debugInfo()); } }); XMLDocType.prototype.element = function(name, value) { var child; child = new XMLDTDElement(this, name, value); this.children.push(child); return this; }; XMLDocType.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) { var child; child = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue); this.children.push(child); return this; }; XMLDocType.prototype.entity = function(name, value) { var child; child = new XMLDTDEntity(this, false, name, value); this.children.push(child); return this; }; XMLDocType.prototype.pEntity = function(name, value) { var child; child = new XMLDTDEntity(this, true, name, value); this.children.push(child); return this; }; XMLDocType.prototype.notation = function(name, value) { var child; child = new XMLDTDNotation(this, name, value); this.children.push(child); return this; }; XMLDocType.prototype.toString = function(options) { return this.options.writer.docType(this, this.options.writer.filterOptions(options)); }; XMLDocType.prototype.ele = function(name, value) { return this.element(name, value); }; XMLDocType.prototype.att = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) { return this.attList(elementName, attributeName, attributeType, defaultValueType, defaultValue); }; XMLDocType.prototype.ent = function(name, value) { return this.entity(name, value); }; XMLDocType.prototype.pent = function(name, value) { return this.pEntity(name, value); }; XMLDocType.prototype.not = function(name, value) { return this.notation(name, value); }; XMLDocType.prototype.up = function() { return this.root() || this.documentObject; }; XMLDocType.prototype.isEqualNode = function(node) { if (!XMLDocType.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) { return false; } if (node.name !== this.name) { return false; } if (node.publicId !== this.publicId) { return false; } if (node.systemId !== this.systemId) { return false; } return true; }; return XMLDocType; })(XMLNode); }).call(this); /***/ }), /***/ 66934: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var NodeType, XMLDOMConfiguration, XMLDOMImplementation, XMLDocument, XMLNode, XMLStringWriter, XMLStringifier, isPlainObject, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; isPlainObject = __webpack_require__(78369).isPlainObject; XMLDOMImplementation = __webpack_require__(91770); XMLDOMConfiguration = __webpack_require__(30383); XMLNode = __webpack_require__(32026); NodeType = __webpack_require__(39335); XMLStringifier = __webpack_require__(95549); XMLStringWriter = __webpack_require__(20437); module.exports = XMLDocument = (function(superClass) { extend(XMLDocument, superClass); function XMLDocument(options) { XMLDocument.__super__.constructor.call(this, null); this.name = "#document"; this.type = NodeType.Document; this.documentURI = null; this.domConfig = new XMLDOMConfiguration(); options || (options = {}); if (!options.writer) { options.writer = new XMLStringWriter(); } this.options = options; this.stringify = new XMLStringifier(options); } Object.defineProperty(XMLDocument.prototype, 'implementation', { value: new XMLDOMImplementation() }); Object.defineProperty(XMLDocument.prototype, 'doctype', { get: function() { var child, i, len, ref; ref = this.children; for (i = 0, len = ref.length; i < len; i++) { child = ref[i]; if (child.type === NodeType.DocType) { return child; } } return null; } }); Object.defineProperty(XMLDocument.prototype, 'documentElement', { get: function() { return this.rootObject || null; } }); Object.defineProperty(XMLDocument.prototype, 'inputEncoding', { get: function() { return null; } }); Object.defineProperty(XMLDocument.prototype, 'strictErrorChecking', { get: function() { return false; } }); Object.defineProperty(XMLDocument.prototype, 'xmlEncoding', { get: function() { if (this.children.length !== 0 && this.children[0].type === NodeType.Declaration) { return this.children[0].encoding; } else { return null; } } }); Object.defineProperty(XMLDocument.prototype, 'xmlStandalone', { get: function() { if (this.children.length !== 0 && this.children[0].type === NodeType.Declaration) { return this.children[0].standalone === 'yes'; } else { return false; } } }); Object.defineProperty(XMLDocument.prototype, 'xmlVersion', { get: function() { if (this.children.length !== 0 && this.children[0].type === NodeType.Declaration) { return this.children[0].version; } else { return "1.0"; } } }); Object.defineProperty(XMLDocument.prototype, 'URL', { get: function() { return this.documentURI; } }); Object.defineProperty(XMLDocument.prototype, 'origin', { get: function() { return null; } }); Object.defineProperty(XMLDocument.prototype, 'compatMode', { get: function() { return null; } }); Object.defineProperty(XMLDocument.prototype, 'characterSet', { get: function() { return null; } }); Object.defineProperty(XMLDocument.prototype, 'contentType', { get: function() { return null; } }); XMLDocument.prototype.end = function(writer) { var writerOptions; writerOptions = {}; if (!writer) { writer = this.options.writer; } else if (isPlainObject(writer)) { writerOptions = writer; writer = this.options.writer; } return writer.document(this, writer.filterOptions(writerOptions)); }; XMLDocument.prototype.toString = function(options) { return this.options.writer.document(this, this.options.writer.filterOptions(options)); }; XMLDocument.prototype.createElement = function(tagName) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument.prototype.createDocumentFragment = function() { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument.prototype.createTextNode = function(data) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument.prototype.createComment = function(data) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument.prototype.createCDATASection = function(data) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument.prototype.createProcessingInstruction = function(target, data) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument.prototype.createAttribute = function(name) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument.prototype.createEntityReference = function(name) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument.prototype.getElementsByTagName = function(tagname) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument.prototype.importNode = function(importedNode, deep) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument.prototype.createElementNS = function(namespaceURI, qualifiedName) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument.prototype.createAttributeNS = function(namespaceURI, qualifiedName) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument.prototype.getElementsByTagNameNS = function(namespaceURI, localName) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument.prototype.getElementById = function(elementId) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument.prototype.adoptNode = function(source) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument.prototype.normalizeDocument = function() { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument.prototype.renameNode = function(node, namespaceURI, qualifiedName) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument.prototype.getElementsByClassName = function(classNames) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument.prototype.createEvent = function(eventInterface) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument.prototype.createRange = function() { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument.prototype.createNodeIterator = function(root, whatToShow, filter) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument.prototype.createTreeWalker = function(root, whatToShow, filter) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; return XMLDocument; })(XMLNode); }).call(this); /***/ }), /***/ 79227: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var NodeType, WriterState, XMLAttribute, XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDeclaration, XMLDocType, XMLDocument, XMLDocumentCB, XMLElement, XMLProcessingInstruction, XMLRaw, XMLStringWriter, XMLStringifier, XMLText, getValue, isFunction, isObject, isPlainObject, ref, hasProp = {}.hasOwnProperty; ref = __webpack_require__(78369), isObject = ref.isObject, isFunction = ref.isFunction, isPlainObject = ref.isPlainObject, getValue = ref.getValue; NodeType = __webpack_require__(39335); XMLDocument = __webpack_require__(66934); XMLElement = __webpack_require__(32161); XMLCData = __webpack_require__(66170); XMLComment = __webpack_require__(62096); XMLRaw = __webpack_require__(79406); XMLText = __webpack_require__(43595); XMLProcessingInstruction = __webpack_require__(19181); XMLDeclaration = __webpack_require__(59077); XMLDocType = __webpack_require__(86544); XMLDTDAttList = __webpack_require__(51179); XMLDTDEntity = __webpack_require__(99078); XMLDTDElement = __webpack_require__(36347); XMLDTDNotation = __webpack_require__(44777); XMLAttribute = __webpack_require__(72750); XMLStringifier = __webpack_require__(95549); XMLStringWriter = __webpack_require__(20437); WriterState = __webpack_require__(30594); module.exports = XMLDocumentCB = (function() { function XMLDocumentCB(options, onData, onEnd) { var writerOptions; this.name = "?xml"; this.type = NodeType.Document; options || (options = {}); writerOptions = {}; if (!options.writer) { options.writer = new XMLStringWriter(); } else if (isPlainObject(options.writer)) { writerOptions = options.writer; options.writer = new XMLStringWriter(); } this.options = options; this.writer = options.writer; this.writerOptions = this.writer.filterOptions(writerOptions); this.stringify = new XMLStringifier(options); this.onDataCallback = onData || function() {}; this.onEndCallback = onEnd || function() {}; this.currentNode = null; this.currentLevel = -1; this.openTags = {}; this.documentStarted = false; this.documentCompleted = false; this.root = null; } XMLDocumentCB.prototype.createChildNode = function(node) { var att, attName, attributes, child, i, len, ref1, ref2; switch (node.type) { case NodeType.CData: this.cdata(node.value); break; case NodeType.Comment: this.comment(node.value); break; case NodeType.Element: attributes = {}; ref1 = node.attribs; for (attName in ref1) { if (!hasProp.call(ref1, attName)) continue; att = ref1[attName]; attributes[attName] = att.value; } this.node(node.name, attributes); break; case NodeType.Dummy: this.dummy(); break; case NodeType.Raw: this.raw(node.value); break; case NodeType.Text: this.text(node.value); break; case NodeType.ProcessingInstruction: this.instruction(node.target, node.value); break; default: throw new Error("This XML node type is not supported in a JS object: " + node.constructor.name); } ref2 = node.children; for (i = 0, len = ref2.length; i < len; i++) { child = ref2[i]; this.createChildNode(child); if (child.type === NodeType.Element) { this.up(); } } return this; }; XMLDocumentCB.prototype.dummy = function() { return this; }; XMLDocumentCB.prototype.node = function(name, attributes, text) { var ref1; if (name == null) { throw new Error("Missing node name."); } if (this.root && this.currentLevel === -1) { throw new Error("Document can only have one root node. " + this.debugInfo(name)); } this.openCurrent(); name = getValue(name); if (attributes == null) { attributes = {}; } attributes = getValue(attributes); if (!isObject(attributes)) { ref1 = [attributes, text], text = ref1[0], attributes = ref1[1]; } this.currentNode = new XMLElement(this, name, attributes); this.currentNode.children = false; this.currentLevel++; this.openTags[this.currentLevel] = this.currentNode; if (text != null) { this.text(text); } return this; }; XMLDocumentCB.prototype.element = function(name, attributes, text) { var child, i, len, oldValidationFlag, ref1, root; if (this.currentNode && this.currentNode.type === NodeType.DocType) { this.dtdElement.apply(this, arguments); } else { if (Array.isArray(name) || isObject(name) || isFunction(name)) { oldValidationFlag = this.options.noValidation; this.options.noValidation = true; root = new XMLDocument(this.options).element('TEMP_ROOT'); root.element(name); this.options.noValidation = oldValidationFlag; ref1 = root.children; for (i = 0, len = ref1.length; i < len; i++) { child = ref1[i]; this.createChildNode(child); if (child.type === NodeType.Element) { this.up(); } } } else { this.node(name, attributes, text); } } return this; }; XMLDocumentCB.prototype.attribute = function(name, value) { var attName, attValue; if (!this.currentNode || this.currentNode.children) { throw new Error("att() can only be used immediately after an ele() call in callback mode. " + this.debugInfo(name)); } if (name != null) { name = getValue(name); } if (isObject(name)) { for (attName in name) { if (!hasProp.call(name, attName)) continue; attValue = name[attName]; this.attribute(attName, attValue); } } else { if (isFunction(value)) { value = value.apply(); } if (this.options.keepNullAttributes && (value == null)) { this.currentNode.attribs[name] = new XMLAttribute(this, name, ""); } else if (value != null) { this.currentNode.attribs[name] = new XMLAttribute(this, name, value); } } return this; }; XMLDocumentCB.prototype.text = function(value) { var node; this.openCurrent(); node = new XMLText(this, value); this.onData(this.writer.text(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB.prototype.cdata = function(value) { var node; this.openCurrent(); node = new XMLCData(this, value); this.onData(this.writer.cdata(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB.prototype.comment = function(value) { var node; this.openCurrent(); node = new XMLComment(this, value); this.onData(this.writer.comment(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB.prototype.raw = function(value) { var node; this.openCurrent(); node = new XMLRaw(this, value); this.onData(this.writer.raw(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB.prototype.instruction = function(target, value) { var i, insTarget, insValue, len, node; this.openCurrent(); if (target != null) { target = getValue(target); } if (value != null) { value = getValue(value); } if (Array.isArray(target)) { for (i = 0, len = target.length; i < len; i++) { insTarget = target[i]; this.instruction(insTarget); } } else if (isObject(target)) { for (insTarget in target) { if (!hasProp.call(target, insTarget)) continue; insValue = target[insTarget]; this.instruction(insTarget, insValue); } } else { if (isFunction(value)) { value = value.apply(); } node = new XMLProcessingInstruction(this, target, value); this.onData(this.writer.processingInstruction(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); } return this; }; XMLDocumentCB.prototype.declaration = function(version, encoding, standalone) { var node; this.openCurrent(); if (this.documentStarted) { throw new Error("declaration() must be the first node."); } node = new XMLDeclaration(this, version, encoding, standalone); this.onData(this.writer.declaration(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB.prototype.doctype = function(root, pubID, sysID) { this.openCurrent(); if (root == null) { throw new Error("Missing root node name."); } if (this.root) { throw new Error("dtd() must come before the root node."); } this.currentNode = new XMLDocType(this, pubID, sysID); this.currentNode.rootNodeName = root; this.currentNode.children = false; this.currentLevel++; this.openTags[this.currentLevel] = this.currentNode; return this; }; XMLDocumentCB.prototype.dtdElement = function(name, value) { var node; this.openCurrent(); node = new XMLDTDElement(this, name, value); this.onData(this.writer.dtdElement(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) { var node; this.openCurrent(); node = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue); this.onData(this.writer.dtdAttList(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB.prototype.entity = function(name, value) { var node; this.openCurrent(); node = new XMLDTDEntity(this, false, name, value); this.onData(this.writer.dtdEntity(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB.prototype.pEntity = function(name, value) { var node; this.openCurrent(); node = new XMLDTDEntity(this, true, name, value); this.onData(this.writer.dtdEntity(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB.prototype.notation = function(name, value) { var node; this.openCurrent(); node = new XMLDTDNotation(this, name, value); this.onData(this.writer.dtdNotation(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB.prototype.up = function() { if (this.currentLevel < 0) { throw new Error("The document node has no parent."); } if (this.currentNode) { if (this.currentNode.children) { this.closeNode(this.currentNode); } else { this.openNode(this.currentNode); } this.currentNode = null; } else { this.closeNode(this.openTags[this.currentLevel]); } delete this.openTags[this.currentLevel]; this.currentLevel--; return this; }; XMLDocumentCB.prototype.end = function() { while (this.currentLevel >= 0) { this.up(); } return this.onEnd(); }; XMLDocumentCB.prototype.openCurrent = function() { if (this.currentNode) { this.currentNode.children = true; return this.openNode(this.currentNode); } }; XMLDocumentCB.prototype.openNode = function(node) { var att, chunk, name, ref1; if (!node.isOpen) { if (!this.root && this.currentLevel === 0 && node.type === NodeType.Element) { this.root = node; } chunk = ''; if (node.type === NodeType.Element) { this.writerOptions.state = WriterState.OpenTag; chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + '<' + node.name; ref1 = node.attribs; for (name in ref1) { if (!hasProp.call(ref1, name)) continue; att = ref1[name]; chunk += this.writer.attribute(att, this.writerOptions, this.currentLevel); } chunk += (node.children ? '>' : '/>') + this.writer.endline(node, this.writerOptions, this.currentLevel); this.writerOptions.state = WriterState.InsideTag; } else { this.writerOptions.state = WriterState.OpenTag; chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + ''; } chunk += this.writer.endline(node, this.writerOptions, this.currentLevel); } this.onData(chunk, this.currentLevel); return node.isOpen = true; } }; XMLDocumentCB.prototype.closeNode = function(node) { var chunk; if (!node.isClosed) { chunk = ''; this.writerOptions.state = WriterState.CloseTag; if (node.type === NodeType.Element) { chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + '' + this.writer.endline(node, this.writerOptions, this.currentLevel); } else { chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + ']>' + this.writer.endline(node, this.writerOptions, this.currentLevel); } this.writerOptions.state = WriterState.None; this.onData(chunk, this.currentLevel); return node.isClosed = true; } }; XMLDocumentCB.prototype.onData = function(chunk, level) { this.documentStarted = true; return this.onDataCallback(chunk, level + 1); }; XMLDocumentCB.prototype.onEnd = function() { this.documentCompleted = true; return this.onEndCallback(); }; XMLDocumentCB.prototype.debugInfo = function(name) { if (name == null) { return ""; } else { return "node: <" + name + ">"; } }; XMLDocumentCB.prototype.ele = function() { return this.element.apply(this, arguments); }; XMLDocumentCB.prototype.nod = function(name, attributes, text) { return this.node(name, attributes, text); }; XMLDocumentCB.prototype.txt = function(value) { return this.text(value); }; XMLDocumentCB.prototype.dat = function(value) { return this.cdata(value); }; XMLDocumentCB.prototype.com = function(value) { return this.comment(value); }; XMLDocumentCB.prototype.ins = function(target, value) { return this.instruction(target, value); }; XMLDocumentCB.prototype.dec = function(version, encoding, standalone) { return this.declaration(version, encoding, standalone); }; XMLDocumentCB.prototype.dtd = function(root, pubID, sysID) { return this.doctype(root, pubID, sysID); }; XMLDocumentCB.prototype.e = function(name, attributes, text) { return this.element(name, attributes, text); }; XMLDocumentCB.prototype.n = function(name, attributes, text) { return this.node(name, attributes, text); }; XMLDocumentCB.prototype.t = function(value) { return this.text(value); }; XMLDocumentCB.prototype.d = function(value) { return this.cdata(value); }; XMLDocumentCB.prototype.c = function(value) { return this.comment(value); }; XMLDocumentCB.prototype.r = function(value) { return this.raw(value); }; XMLDocumentCB.prototype.i = function(target, value) { return this.instruction(target, value); }; XMLDocumentCB.prototype.att = function() { if (this.currentNode && this.currentNode.type === NodeType.DocType) { return this.attList.apply(this, arguments); } else { return this.attribute.apply(this, arguments); } }; XMLDocumentCB.prototype.a = function() { if (this.currentNode && this.currentNode.type === NodeType.DocType) { return this.attList.apply(this, arguments); } else { return this.attribute.apply(this, arguments); } }; XMLDocumentCB.prototype.ent = function(name, value) { return this.entity(name, value); }; XMLDocumentCB.prototype.pent = function(name, value) { return this.pEntity(name, value); }; XMLDocumentCB.prototype.not = function(name, value) { return this.notation(name, value); }; return XMLDocumentCB; })(); }).call(this); /***/ }), /***/ 78833: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var NodeType, XMLDummy, XMLNode, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; XMLNode = __webpack_require__(32026); NodeType = __webpack_require__(39335); module.exports = XMLDummy = (function(superClass) { extend(XMLDummy, superClass); function XMLDummy(parent) { XMLDummy.__super__.constructor.call(this, parent); this.type = NodeType.Dummy; } XMLDummy.prototype.clone = function() { return Object.create(this); }; XMLDummy.prototype.toString = function(options) { return ''; }; return XMLDummy; })(XMLNode); }).call(this); /***/ }), /***/ 32161: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var NodeType, XMLAttribute, XMLElement, XMLNamedNodeMap, XMLNode, getValue, isFunction, isObject, ref, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; ref = __webpack_require__(78369), isObject = ref.isObject, isFunction = ref.isFunction, getValue = ref.getValue; XMLNode = __webpack_require__(32026); NodeType = __webpack_require__(39335); XMLAttribute = __webpack_require__(72750); XMLNamedNodeMap = __webpack_require__(40663); module.exports = XMLElement = (function(superClass) { extend(XMLElement, superClass); function XMLElement(parent, name, attributes) { var child, j, len, ref1; XMLElement.__super__.constructor.call(this, parent); if (name == null) { throw new Error("Missing element name. " + this.debugInfo()); } this.name = this.stringify.name(name); this.type = NodeType.Element; this.attribs = {}; this.schemaTypeInfo = null; if (attributes != null) { this.attribute(attributes); } if (parent.type === NodeType.Document) { this.isRoot = true; this.documentObject = parent; parent.rootObject = this; if (parent.children) { ref1 = parent.children; for (j = 0, len = ref1.length; j < len; j++) { child = ref1[j]; if (child.type === NodeType.DocType) { child.name = this.name; break; } } } } } Object.defineProperty(XMLElement.prototype, 'tagName', { get: function() { return this.name; } }); Object.defineProperty(XMLElement.prototype, 'namespaceURI', { get: function() { return ''; } }); Object.defineProperty(XMLElement.prototype, 'prefix', { get: function() { return ''; } }); Object.defineProperty(XMLElement.prototype, 'localName', { get: function() { return this.name; } }); Object.defineProperty(XMLElement.prototype, 'id', { get: function() { throw new Error("This DOM method is not implemented." + this.debugInfo()); } }); Object.defineProperty(XMLElement.prototype, 'className', { get: function() { throw new Error("This DOM method is not implemented." + this.debugInfo()); } }); Object.defineProperty(XMLElement.prototype, 'classList', { get: function() { throw new Error("This DOM method is not implemented." + this.debugInfo()); } }); Object.defineProperty(XMLElement.prototype, 'attributes', { get: function() { if (!this.attributeMap || !this.attributeMap.nodes) { this.attributeMap = new XMLNamedNodeMap(this.attribs); } return this.attributeMap; } }); XMLElement.prototype.clone = function() { var att, attName, clonedSelf, ref1; clonedSelf = Object.create(this); if (clonedSelf.isRoot) { clonedSelf.documentObject = null; } clonedSelf.attribs = {}; ref1 = this.attribs; for (attName in ref1) { if (!hasProp.call(ref1, attName)) continue; att = ref1[attName]; clonedSelf.attribs[attName] = att.clone(); } clonedSelf.children = []; this.children.forEach(function(child) { var clonedChild; clonedChild = child.clone(); clonedChild.parent = clonedSelf; return clonedSelf.children.push(clonedChild); }); return clonedSelf; }; XMLElement.prototype.attribute = function(name, value) { var attName, attValue; if (name != null) { name = getValue(name); } if (isObject(name)) { for (attName in name) { if (!hasProp.call(name, attName)) continue; attValue = name[attName]; this.attribute(attName, attValue); } } else { if (isFunction(value)) { value = value.apply(); } if (this.options.keepNullAttributes && (value == null)) { this.attribs[name] = new XMLAttribute(this, name, ""); } else if (value != null) { this.attribs[name] = new XMLAttribute(this, name, value); } } return this; }; XMLElement.prototype.removeAttribute = function(name) { var attName, j, len; if (name == null) { throw new Error("Missing attribute name. " + this.debugInfo()); } name = getValue(name); if (Array.isArray(name)) { for (j = 0, len = name.length; j < len; j++) { attName = name[j]; delete this.attribs[attName]; } } else { delete this.attribs[name]; } return this; }; XMLElement.prototype.toString = function(options) { return this.options.writer.element(this, this.options.writer.filterOptions(options)); }; XMLElement.prototype.att = function(name, value) { return this.attribute(name, value); }; XMLElement.prototype.a = function(name, value) { return this.attribute(name, value); }; XMLElement.prototype.getAttribute = function(name) { if (this.attribs.hasOwnProperty(name)) { return this.attribs[name].value; } else { return null; } }; XMLElement.prototype.setAttribute = function(name, value) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement.prototype.getAttributeNode = function(name) { if (this.attribs.hasOwnProperty(name)) { return this.attribs[name]; } else { return null; } }; XMLElement.prototype.setAttributeNode = function(newAttr) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement.prototype.removeAttributeNode = function(oldAttr) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement.prototype.getElementsByTagName = function(name) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement.prototype.getAttributeNS = function(namespaceURI, localName) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement.prototype.setAttributeNS = function(namespaceURI, qualifiedName, value) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement.prototype.removeAttributeNS = function(namespaceURI, localName) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement.prototype.getAttributeNodeNS = function(namespaceURI, localName) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement.prototype.setAttributeNodeNS = function(newAttr) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement.prototype.getElementsByTagNameNS = function(namespaceURI, localName) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement.prototype.hasAttribute = function(name) { return this.attribs.hasOwnProperty(name); }; XMLElement.prototype.hasAttributeNS = function(namespaceURI, localName) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement.prototype.setIdAttribute = function(name, isId) { if (this.attribs.hasOwnProperty(name)) { return this.attribs[name].isId; } else { return isId; } }; XMLElement.prototype.setIdAttributeNS = function(namespaceURI, localName, isId) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement.prototype.setIdAttributeNode = function(idAttr, isId) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement.prototype.getElementsByTagName = function(tagname) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement.prototype.getElementsByTagNameNS = function(namespaceURI, localName) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement.prototype.getElementsByClassName = function(classNames) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement.prototype.isEqualNode = function(node) { var i, j, ref1; if (!XMLElement.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) { return false; } if (node.namespaceURI !== this.namespaceURI) { return false; } if (node.prefix !== this.prefix) { return false; } if (node.localName !== this.localName) { return false; } if (node.attribs.length !== this.attribs.length) { return false; } for (i = j = 0, ref1 = this.attribs.length - 1; 0 <= ref1 ? j <= ref1 : j >= ref1; i = 0 <= ref1 ? ++j : --j) { if (!this.attribs[i].isEqualNode(node.attribs[i])) { return false; } } return true; }; return XMLElement; })(XMLNode); }).call(this); /***/ }), /***/ 40663: /***/ (function(module) { // Generated by CoffeeScript 1.12.7 (function() { var XMLNamedNodeMap; module.exports = XMLNamedNodeMap = (function() { function XMLNamedNodeMap(nodes) { this.nodes = nodes; } Object.defineProperty(XMLNamedNodeMap.prototype, 'length', { get: function() { return Object.keys(this.nodes).length || 0; } }); XMLNamedNodeMap.prototype.clone = function() { return this.nodes = null; }; XMLNamedNodeMap.prototype.getNamedItem = function(name) { return this.nodes[name]; }; XMLNamedNodeMap.prototype.setNamedItem = function(node) { var oldNode; oldNode = this.nodes[node.nodeName]; this.nodes[node.nodeName] = node; return oldNode || null; }; XMLNamedNodeMap.prototype.removeNamedItem = function(name) { var oldNode; oldNode = this.nodes[name]; delete this.nodes[name]; return oldNode || null; }; XMLNamedNodeMap.prototype.item = function(index) { return this.nodes[Object.keys(this.nodes)[index]] || null; }; XMLNamedNodeMap.prototype.getNamedItemNS = function(namespaceURI, localName) { throw new Error("This DOM method is not implemented."); }; XMLNamedNodeMap.prototype.setNamedItemNS = function(node) { throw new Error("This DOM method is not implemented."); }; XMLNamedNodeMap.prototype.removeNamedItemNS = function(namespaceURI, localName) { throw new Error("This DOM method is not implemented."); }; return XMLNamedNodeMap; })(); }).call(this); /***/ }), /***/ 32026: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var DocumentPosition, NodeType, XMLCData, XMLComment, XMLDeclaration, XMLDocType, XMLDummy, XMLElement, XMLNamedNodeMap, XMLNode, XMLNodeList, XMLProcessingInstruction, XMLRaw, XMLText, getValue, isEmpty, isFunction, isObject, ref1, hasProp = {}.hasOwnProperty; ref1 = __webpack_require__(78369), isObject = ref1.isObject, isFunction = ref1.isFunction, isEmpty = ref1.isEmpty, getValue = ref1.getValue; XMLElement = null; XMLCData = null; XMLComment = null; XMLDeclaration = null; XMLDocType = null; XMLRaw = null; XMLText = null; XMLProcessingInstruction = null; XMLDummy = null; NodeType = null; XMLNodeList = null; XMLNamedNodeMap = null; DocumentPosition = null; module.exports = XMLNode = (function() { function XMLNode(parent1) { this.parent = parent1; if (this.parent) { this.options = this.parent.options; this.stringify = this.parent.stringify; } this.value = null; this.children = []; this.baseURI = null; if (!XMLElement) { XMLElement = __webpack_require__(32161); XMLCData = __webpack_require__(66170); XMLComment = __webpack_require__(62096); XMLDeclaration = __webpack_require__(59077); XMLDocType = __webpack_require__(86544); XMLRaw = __webpack_require__(79406); XMLText = __webpack_require__(43595); XMLProcessingInstruction = __webpack_require__(19181); XMLDummy = __webpack_require__(78833); NodeType = __webpack_require__(39335); XMLNodeList = __webpack_require__(82390); XMLNamedNodeMap = __webpack_require__(40663); DocumentPosition = __webpack_require__(17557); } } Object.defineProperty(XMLNode.prototype, 'nodeName', { get: function() { return this.name; } }); Object.defineProperty(XMLNode.prototype, 'nodeType', { get: function() { return this.type; } }); Object.defineProperty(XMLNode.prototype, 'nodeValue', { get: function() { return this.value; } }); Object.defineProperty(XMLNode.prototype, 'parentNode', { get: function() { return this.parent; } }); Object.defineProperty(XMLNode.prototype, 'childNodes', { get: function() { if (!this.childNodeList || !this.childNodeList.nodes) { this.childNodeList = new XMLNodeList(this.children); } return this.childNodeList; } }); Object.defineProperty(XMLNode.prototype, 'firstChild', { get: function() { return this.children[0] || null; } }); Object.defineProperty(XMLNode.prototype, 'lastChild', { get: function() { return this.children[this.children.length - 1] || null; } }); Object.defineProperty(XMLNode.prototype, 'previousSibling', { get: function() { var i; i = this.parent.children.indexOf(this); return this.parent.children[i - 1] || null; } }); Object.defineProperty(XMLNode.prototype, 'nextSibling', { get: function() { var i; i = this.parent.children.indexOf(this); return this.parent.children[i + 1] || null; } }); Object.defineProperty(XMLNode.prototype, 'ownerDocument', { get: function() { return this.document() || null; } }); Object.defineProperty(XMLNode.prototype, 'textContent', { get: function() { var child, j, len, ref2, str; if (this.nodeType === NodeType.Element || this.nodeType === NodeType.DocumentFragment) { str = ''; ref2 = this.children; for (j = 0, len = ref2.length; j < len; j++) { child = ref2[j]; if (child.textContent) { str += child.textContent; } } return str; } else { return null; } }, set: function(value) { throw new Error("This DOM method is not implemented." + this.debugInfo()); } }); XMLNode.prototype.setParent = function(parent) { var child, j, len, ref2, results; this.parent = parent; if (parent) { this.options = parent.options; this.stringify = parent.stringify; } ref2 = this.children; results = []; for (j = 0, len = ref2.length; j < len; j++) { child = ref2[j]; results.push(child.setParent(this)); } return results; }; XMLNode.prototype.element = function(name, attributes, text) { var childNode, item, j, k, key, lastChild, len, len1, ref2, ref3, val; lastChild = null; if (attributes === null && (text == null)) { ref2 = [{}, null], attributes = ref2[0], text = ref2[1]; } if (attributes == null) { attributes = {}; } attributes = getValue(attributes); if (!isObject(attributes)) { ref3 = [attributes, text], text = ref3[0], attributes = ref3[1]; } if (name != null) { name = getValue(name); } if (Array.isArray(name)) { for (j = 0, len = name.length; j < len; j++) { item = name[j]; lastChild = this.element(item); } } else if (isFunction(name)) { lastChild = this.element(name.apply()); } else if (isObject(name)) { for (key in name) { if (!hasProp.call(name, key)) continue; val = name[key]; if (isFunction(val)) { val = val.apply(); } if (!this.options.ignoreDecorators && this.stringify.convertAttKey && key.indexOf(this.stringify.convertAttKey) === 0) { lastChild = this.attribute(key.substr(this.stringify.convertAttKey.length), val); } else if (!this.options.separateArrayItems && Array.isArray(val) && isEmpty(val)) { lastChild = this.dummy(); } else if (isObject(val) && isEmpty(val)) { lastChild = this.element(key); } else if (!this.options.keepNullNodes && (val == null)) { lastChild = this.dummy(); } else if (!this.options.separateArrayItems && Array.isArray(val)) { for (k = 0, len1 = val.length; k < len1; k++) { item = val[k]; childNode = {}; childNode[key] = item; lastChild = this.element(childNode); } } else if (isObject(val)) { if (!this.options.ignoreDecorators && this.stringify.convertTextKey && key.indexOf(this.stringify.convertTextKey) === 0) { lastChild = this.element(val); } else { lastChild = this.element(key); lastChild.element(val); } } else { lastChild = this.element(key, val); } } } else if (!this.options.keepNullNodes && text === null) { lastChild = this.dummy(); } else { if (!this.options.ignoreDecorators && this.stringify.convertTextKey && name.indexOf(this.stringify.convertTextKey) === 0) { lastChild = this.text(text); } else if (!this.options.ignoreDecorators && this.stringify.convertCDataKey && name.indexOf(this.stringify.convertCDataKey) === 0) { lastChild = this.cdata(text); } else if (!this.options.ignoreDecorators && this.stringify.convertCommentKey && name.indexOf(this.stringify.convertCommentKey) === 0) { lastChild = this.comment(text); } else if (!this.options.ignoreDecorators && this.stringify.convertRawKey && name.indexOf(this.stringify.convertRawKey) === 0) { lastChild = this.raw(text); } else if (!this.options.ignoreDecorators && this.stringify.convertPIKey && name.indexOf(this.stringify.convertPIKey) === 0) { lastChild = this.instruction(name.substr(this.stringify.convertPIKey.length), text); } else { lastChild = this.node(name, attributes, text); } } if (lastChild == null) { throw new Error("Could not create any elements with: " + name + ". " + this.debugInfo()); } return lastChild; }; XMLNode.prototype.insertBefore = function(name, attributes, text) { var child, i, newChild, refChild, removed; if (name != null ? name.type : void 0) { newChild = name; refChild = attributes; newChild.setParent(this); if (refChild) { i = children.indexOf(refChild); removed = children.splice(i); children.push(newChild); Array.prototype.push.apply(children, removed); } else { children.push(newChild); } return newChild; } else { if (this.isRoot) { throw new Error("Cannot insert elements at root level. " + this.debugInfo(name)); } i = this.parent.children.indexOf(this); removed = this.parent.children.splice(i); child = this.parent.element(name, attributes, text); Array.prototype.push.apply(this.parent.children, removed); return child; } }; XMLNode.prototype.insertAfter = function(name, attributes, text) { var child, i, removed; if (this.isRoot) { throw new Error("Cannot insert elements at root level. " + this.debugInfo(name)); } i = this.parent.children.indexOf(this); removed = this.parent.children.splice(i + 1); child = this.parent.element(name, attributes, text); Array.prototype.push.apply(this.parent.children, removed); return child; }; XMLNode.prototype.remove = function() { var i, ref2; if (this.isRoot) { throw new Error("Cannot remove the root element. " + this.debugInfo()); } i = this.parent.children.indexOf(this); [].splice.apply(this.parent.children, [i, i - i + 1].concat(ref2 = [])), ref2; return this.parent; }; XMLNode.prototype.node = function(name, attributes, text) { var child, ref2; if (name != null) { name = getValue(name); } attributes || (attributes = {}); attributes = getValue(attributes); if (!isObject(attributes)) { ref2 = [attributes, text], text = ref2[0], attributes = ref2[1]; } child = new XMLElement(this, name, attributes); if (text != null) { child.text(text); } this.children.push(child); return child; }; XMLNode.prototype.text = function(value) { var child; if (isObject(value)) { this.element(value); } child = new XMLText(this, value); this.children.push(child); return this; }; XMLNode.prototype.cdata = function(value) { var child; child = new XMLCData(this, value); this.children.push(child); return this; }; XMLNode.prototype.comment = function(value) { var child; child = new XMLComment(this, value); this.children.push(child); return this; }; XMLNode.prototype.commentBefore = function(value) { var child, i, removed; i = this.parent.children.indexOf(this); removed = this.parent.children.splice(i); child = this.parent.comment(value); Array.prototype.push.apply(this.parent.children, removed); return this; }; XMLNode.prototype.commentAfter = function(value) { var child, i, removed; i = this.parent.children.indexOf(this); removed = this.parent.children.splice(i + 1); child = this.parent.comment(value); Array.prototype.push.apply(this.parent.children, removed); return this; }; XMLNode.prototype.raw = function(value) { var child; child = new XMLRaw(this, value); this.children.push(child); return this; }; XMLNode.prototype.dummy = function() { var child; child = new XMLDummy(this); return child; }; XMLNode.prototype.instruction = function(target, value) { var insTarget, insValue, instruction, j, len; if (target != null) { target = getValue(target); } if (value != null) { value = getValue(value); } if (Array.isArray(target)) { for (j = 0, len = target.length; j < len; j++) { insTarget = target[j]; this.instruction(insTarget); } } else if (isObject(target)) { for (insTarget in target) { if (!hasProp.call(target, insTarget)) continue; insValue = target[insTarget]; this.instruction(insTarget, insValue); } } else { if (isFunction(value)) { value = value.apply(); } instruction = new XMLProcessingInstruction(this, target, value); this.children.push(instruction); } return this; }; XMLNode.prototype.instructionBefore = function(target, value) { var child, i, removed; i = this.parent.children.indexOf(this); removed = this.parent.children.splice(i); child = this.parent.instruction(target, value); Array.prototype.push.apply(this.parent.children, removed); return this; }; XMLNode.prototype.instructionAfter = function(target, value) { var child, i, removed; i = this.parent.children.indexOf(this); removed = this.parent.children.splice(i + 1); child = this.parent.instruction(target, value); Array.prototype.push.apply(this.parent.children, removed); return this; }; XMLNode.prototype.declaration = function(version, encoding, standalone) { var doc, xmldec; doc = this.document(); xmldec = new XMLDeclaration(doc, version, encoding, standalone); if (doc.children.length === 0) { doc.children.unshift(xmldec); } else if (doc.children[0].type === NodeType.Declaration) { doc.children[0] = xmldec; } else { doc.children.unshift(xmldec); } return doc.root() || doc; }; XMLNode.prototype.dtd = function(pubID, sysID) { var child, doc, doctype, i, j, k, len, len1, ref2, ref3; doc = this.document(); doctype = new XMLDocType(doc, pubID, sysID); ref2 = doc.children; for (i = j = 0, len = ref2.length; j < len; i = ++j) { child = ref2[i]; if (child.type === NodeType.DocType) { doc.children[i] = doctype; return doctype; } } ref3 = doc.children; for (i = k = 0, len1 = ref3.length; k < len1; i = ++k) { child = ref3[i]; if (child.isRoot) { doc.children.splice(i, 0, doctype); return doctype; } } doc.children.push(doctype); return doctype; }; XMLNode.prototype.up = function() { if (this.isRoot) { throw new Error("The root node has no parent. Use doc() if you need to get the document object."); } return this.parent; }; XMLNode.prototype.root = function() { var node; node = this; while (node) { if (node.type === NodeType.Document) { return node.rootObject; } else if (node.isRoot) { return node; } else { node = node.parent; } } }; XMLNode.prototype.document = function() { var node; node = this; while (node) { if (node.type === NodeType.Document) { return node; } else { node = node.parent; } } }; XMLNode.prototype.end = function(options) { return this.document().end(options); }; XMLNode.prototype.prev = function() { var i; i = this.parent.children.indexOf(this); if (i < 1) { throw new Error("Already at the first node. " + this.debugInfo()); } return this.parent.children[i - 1]; }; XMLNode.prototype.next = function() { var i; i = this.parent.children.indexOf(this); if (i === -1 || i === this.parent.children.length - 1) { throw new Error("Already at the last node. " + this.debugInfo()); } return this.parent.children[i + 1]; }; XMLNode.prototype.importDocument = function(doc) { var clonedRoot; clonedRoot = doc.root().clone(); clonedRoot.parent = this; clonedRoot.isRoot = false; this.children.push(clonedRoot); return this; }; XMLNode.prototype.debugInfo = function(name) { var ref2, ref3; name = name || this.name; if ((name == null) && !((ref2 = this.parent) != null ? ref2.name : void 0)) { return ""; } else if (name == null) { return "parent: <" + this.parent.name + ">"; } else if (!((ref3 = this.parent) != null ? ref3.name : void 0)) { return "node: <" + name + ">"; } else { return "node: <" + name + ">, parent: <" + this.parent.name + ">"; } }; XMLNode.prototype.ele = function(name, attributes, text) { return this.element(name, attributes, text); }; XMLNode.prototype.nod = function(name, attributes, text) { return this.node(name, attributes, text); }; XMLNode.prototype.txt = function(value) { return this.text(value); }; XMLNode.prototype.dat = function(value) { return this.cdata(value); }; XMLNode.prototype.com = function(value) { return this.comment(value); }; XMLNode.prototype.ins = function(target, value) { return this.instruction(target, value); }; XMLNode.prototype.doc = function() { return this.document(); }; XMLNode.prototype.dec = function(version, encoding, standalone) { return this.declaration(version, encoding, standalone); }; XMLNode.prototype.e = function(name, attributes, text) { return this.element(name, attributes, text); }; XMLNode.prototype.n = function(name, attributes, text) { return this.node(name, attributes, text); }; XMLNode.prototype.t = function(value) { return this.text(value); }; XMLNode.prototype.d = function(value) { return this.cdata(value); }; XMLNode.prototype.c = function(value) { return this.comment(value); }; XMLNode.prototype.r = function(value) { return this.raw(value); }; XMLNode.prototype.i = function(target, value) { return this.instruction(target, value); }; XMLNode.prototype.u = function() { return this.up(); }; XMLNode.prototype.importXMLBuilder = function(doc) { return this.importDocument(doc); }; XMLNode.prototype.replaceChild = function(newChild, oldChild) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLNode.prototype.removeChild = function(oldChild) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLNode.prototype.appendChild = function(newChild) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLNode.prototype.hasChildNodes = function() { return this.children.length !== 0; }; XMLNode.prototype.cloneNode = function(deep) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLNode.prototype.normalize = function() { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLNode.prototype.isSupported = function(feature, version) { return true; }; XMLNode.prototype.hasAttributes = function() { return this.attribs.length !== 0; }; XMLNode.prototype.compareDocumentPosition = function(other) { var ref, res; ref = this; if (ref === other) { return 0; } else if (this.document() !== other.document()) { res = DocumentPosition.Disconnected | DocumentPosition.ImplementationSpecific; if (Math.random() < 0.5) { res |= DocumentPosition.Preceding; } else { res |= DocumentPosition.Following; } return res; } else if (ref.isAncestor(other)) { return DocumentPosition.Contains | DocumentPosition.Preceding; } else if (ref.isDescendant(other)) { return DocumentPosition.Contains | DocumentPosition.Following; } else if (ref.isPreceding(other)) { return DocumentPosition.Preceding; } else { return DocumentPosition.Following; } }; XMLNode.prototype.isSameNode = function(other) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLNode.prototype.lookupPrefix = function(namespaceURI) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLNode.prototype.isDefaultNamespace = function(namespaceURI) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLNode.prototype.lookupNamespaceURI = function(prefix) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLNode.prototype.isEqualNode = function(node) { var i, j, ref2; if (node.nodeType !== this.nodeType) { return false; } if (node.children.length !== this.children.length) { return false; } for (i = j = 0, ref2 = this.children.length - 1; 0 <= ref2 ? j <= ref2 : j >= ref2; i = 0 <= ref2 ? ++j : --j) { if (!this.children[i].isEqualNode(node.children[i])) { return false; } } return true; }; XMLNode.prototype.getFeature = function(feature, version) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLNode.prototype.setUserData = function(key, data, handler) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLNode.prototype.getUserData = function(key) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLNode.prototype.contains = function(other) { if (!other) { return false; } return other === this || this.isDescendant(other); }; XMLNode.prototype.isDescendant = function(node) { var child, isDescendantChild, j, len, ref2; ref2 = this.children; for (j = 0, len = ref2.length; j < len; j++) { child = ref2[j]; if (node === child) { return true; } isDescendantChild = child.isDescendant(node); if (isDescendantChild) { return true; } } return false; }; XMLNode.prototype.isAncestor = function(node) { return node.isDescendant(this); }; XMLNode.prototype.isPreceding = function(node) { var nodePos, thisPos; nodePos = this.treePosition(node); thisPos = this.treePosition(this); if (nodePos === -1 || thisPos === -1) { return false; } else { return nodePos < thisPos; } }; XMLNode.prototype.isFollowing = function(node) { var nodePos, thisPos; nodePos = this.treePosition(node); thisPos = this.treePosition(this); if (nodePos === -1 || thisPos === -1) { return false; } else { return nodePos > thisPos; } }; XMLNode.prototype.treePosition = function(node) { var found, pos; pos = 0; found = false; this.foreachTreeNode(this.document(), function(childNode) { pos++; if (!found && childNode === node) { return found = true; } }); if (found) { return pos; } else { return -1; } }; XMLNode.prototype.foreachTreeNode = function(node, func) { var child, j, len, ref2, res; node || (node = this.document()); ref2 = node.children; for (j = 0, len = ref2.length; j < len; j++) { child = ref2[j]; if (res = func(child)) { return res; } else { res = this.foreachTreeNode(child, func); if (res) { return res; } } } }; return XMLNode; })(); }).call(this); /***/ }), /***/ 82390: /***/ (function(module) { // Generated by CoffeeScript 1.12.7 (function() { var XMLNodeList; module.exports = XMLNodeList = (function() { function XMLNodeList(nodes) { this.nodes = nodes; } Object.defineProperty(XMLNodeList.prototype, 'length', { get: function() { return this.nodes.length || 0; } }); XMLNodeList.prototype.clone = function() { return this.nodes = null; }; XMLNodeList.prototype.item = function(index) { return this.nodes[index] || null; }; return XMLNodeList; })(); }).call(this); /***/ }), /***/ 19181: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var NodeType, XMLCharacterData, XMLProcessingInstruction, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; NodeType = __webpack_require__(39335); XMLCharacterData = __webpack_require__(6488); module.exports = XMLProcessingInstruction = (function(superClass) { extend(XMLProcessingInstruction, superClass); function XMLProcessingInstruction(parent, target, value) { XMLProcessingInstruction.__super__.constructor.call(this, parent); if (target == null) { throw new Error("Missing instruction target. " + this.debugInfo()); } this.type = NodeType.ProcessingInstruction; this.target = this.stringify.insTarget(target); this.name = this.target; if (value) { this.value = this.stringify.insValue(value); } } XMLProcessingInstruction.prototype.clone = function() { return Object.create(this); }; XMLProcessingInstruction.prototype.toString = function(options) { return this.options.writer.processingInstruction(this, this.options.writer.filterOptions(options)); }; XMLProcessingInstruction.prototype.isEqualNode = function(node) { if (!XMLProcessingInstruction.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) { return false; } if (node.target !== this.target) { return false; } return true; }; return XMLProcessingInstruction; })(XMLCharacterData); }).call(this); /***/ }), /***/ 79406: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var NodeType, XMLNode, XMLRaw, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; NodeType = __webpack_require__(39335); XMLNode = __webpack_require__(32026); module.exports = XMLRaw = (function(superClass) { extend(XMLRaw, superClass); function XMLRaw(parent, text) { XMLRaw.__super__.constructor.call(this, parent); if (text == null) { throw new Error("Missing raw text. " + this.debugInfo()); } this.type = NodeType.Raw; this.value = this.stringify.raw(text); } XMLRaw.prototype.clone = function() { return Object.create(this); }; XMLRaw.prototype.toString = function(options) { return this.options.writer.raw(this, this.options.writer.filterOptions(options)); }; return XMLRaw; })(XMLNode); }).call(this); /***/ }), /***/ 81996: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var NodeType, WriterState, XMLStreamWriter, XMLWriterBase, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; NodeType = __webpack_require__(39335); XMLWriterBase = __webpack_require__(60751); WriterState = __webpack_require__(30594); module.exports = XMLStreamWriter = (function(superClass) { extend(XMLStreamWriter, superClass); function XMLStreamWriter(stream, options) { this.stream = stream; XMLStreamWriter.__super__.constructor.call(this, options); } XMLStreamWriter.prototype.endline = function(node, options, level) { if (node.isLastRootNode && options.state === WriterState.CloseTag) { return ''; } else { return XMLStreamWriter.__super__.endline.call(this, node, options, level); } }; XMLStreamWriter.prototype.document = function(doc, options) { var child, i, j, k, len, len1, ref, ref1, results; ref = doc.children; for (i = j = 0, len = ref.length; j < len; i = ++j) { child = ref[i]; child.isLastRootNode = i === doc.children.length - 1; } options = this.filterOptions(options); ref1 = doc.children; results = []; for (k = 0, len1 = ref1.length; k < len1; k++) { child = ref1[k]; results.push(this.writeChildNode(child, options, 0)); } return results; }; XMLStreamWriter.prototype.attribute = function(att, options, level) { return this.stream.write(XMLStreamWriter.__super__.attribute.call(this, att, options, level)); }; XMLStreamWriter.prototype.cdata = function(node, options, level) { return this.stream.write(XMLStreamWriter.__super__.cdata.call(this, node, options, level)); }; XMLStreamWriter.prototype.comment = function(node, options, level) { return this.stream.write(XMLStreamWriter.__super__.comment.call(this, node, options, level)); }; XMLStreamWriter.prototype.declaration = function(node, options, level) { return this.stream.write(XMLStreamWriter.__super__.declaration.call(this, node, options, level)); }; XMLStreamWriter.prototype.docType = function(node, options, level) { var child, j, len, ref; level || (level = 0); this.openNode(node, options, level); options.state = WriterState.OpenTag; this.stream.write(this.indent(node, options, level)); this.stream.write(' 0) { this.stream.write(' ['); this.stream.write(this.endline(node, options, level)); options.state = WriterState.InsideTag; ref = node.children; for (j = 0, len = ref.length; j < len; j++) { child = ref[j]; this.writeChildNode(child, options, level + 1); } options.state = WriterState.CloseTag; this.stream.write(']'); } options.state = WriterState.CloseTag; this.stream.write(options.spaceBeforeSlash + '>'); this.stream.write(this.endline(node, options, level)); options.state = WriterState.None; return this.closeNode(node, options, level); }; XMLStreamWriter.prototype.element = function(node, options, level) { var att, child, childNodeCount, firstChildNode, j, len, name, prettySuppressed, ref, ref1; level || (level = 0); this.openNode(node, options, level); options.state = WriterState.OpenTag; this.stream.write(this.indent(node, options, level) + '<' + node.name); ref = node.attribs; for (name in ref) { if (!hasProp.call(ref, name)) continue; att = ref[name]; this.attribute(att, options, level); } childNodeCount = node.children.length; firstChildNode = childNodeCount === 0 ? null : node.children[0]; if (childNodeCount === 0 || node.children.every(function(e) { return (e.type === NodeType.Text || e.type === NodeType.Raw) && e.value === ''; })) { if (options.allowEmpty) { this.stream.write('>'); options.state = WriterState.CloseTag; this.stream.write(''); } else { options.state = WriterState.CloseTag; this.stream.write(options.spaceBeforeSlash + '/>'); } } else if (options.pretty && childNodeCount === 1 && (firstChildNode.type === NodeType.Text || firstChildNode.type === NodeType.Raw) && (firstChildNode.value != null)) { this.stream.write('>'); options.state = WriterState.InsideTag; options.suppressPrettyCount++; prettySuppressed = true; this.writeChildNode(firstChildNode, options, level + 1); options.suppressPrettyCount--; prettySuppressed = false; options.state = WriterState.CloseTag; this.stream.write(''); } else { this.stream.write('>' + this.endline(node, options, level)); options.state = WriterState.InsideTag; ref1 = node.children; for (j = 0, len = ref1.length; j < len; j++) { child = ref1[j]; this.writeChildNode(child, options, level + 1); } options.state = WriterState.CloseTag; this.stream.write(this.indent(node, options, level) + ''); } this.stream.write(this.endline(node, options, level)); options.state = WriterState.None; return this.closeNode(node, options, level); }; XMLStreamWriter.prototype.processingInstruction = function(node, options, level) { return this.stream.write(XMLStreamWriter.__super__.processingInstruction.call(this, node, options, level)); }; XMLStreamWriter.prototype.raw = function(node, options, level) { return this.stream.write(XMLStreamWriter.__super__.raw.call(this, node, options, level)); }; XMLStreamWriter.prototype.text = function(node, options, level) { return this.stream.write(XMLStreamWriter.__super__.text.call(this, node, options, level)); }; XMLStreamWriter.prototype.dtdAttList = function(node, options, level) { return this.stream.write(XMLStreamWriter.__super__.dtdAttList.call(this, node, options, level)); }; XMLStreamWriter.prototype.dtdElement = function(node, options, level) { return this.stream.write(XMLStreamWriter.__super__.dtdElement.call(this, node, options, level)); }; XMLStreamWriter.prototype.dtdEntity = function(node, options, level) { return this.stream.write(XMLStreamWriter.__super__.dtdEntity.call(this, node, options, level)); }; XMLStreamWriter.prototype.dtdNotation = function(node, options, level) { return this.stream.write(XMLStreamWriter.__super__.dtdNotation.call(this, node, options, level)); }; return XMLStreamWriter; })(XMLWriterBase); }).call(this); /***/ }), /***/ 20437: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var XMLStringWriter, XMLWriterBase, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; XMLWriterBase = __webpack_require__(60751); module.exports = XMLStringWriter = (function(superClass) { extend(XMLStringWriter, superClass); function XMLStringWriter(options) { XMLStringWriter.__super__.constructor.call(this, options); } XMLStringWriter.prototype.document = function(doc, options) { var child, i, len, r, ref; options = this.filterOptions(options); r = ''; ref = doc.children; for (i = 0, len = ref.length; i < len; i++) { child = ref[i]; r += this.writeChildNode(child, options, 0); } if (options.pretty && r.slice(-options.newline.length) === options.newline) { r = r.slice(0, -options.newline.length); } return r; }; return XMLStringWriter; })(XMLWriterBase); }).call(this); /***/ }), /***/ 95549: /***/ (function(module) { // Generated by CoffeeScript 1.12.7 (function() { var XMLStringifier, bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, hasProp = {}.hasOwnProperty; module.exports = XMLStringifier = (function() { function XMLStringifier(options) { this.assertLegalName = bind(this.assertLegalName, this); this.assertLegalChar = bind(this.assertLegalChar, this); var key, ref, value; options || (options = {}); this.options = options; if (!this.options.version) { this.options.version = '1.0'; } ref = options.stringify || {}; for (key in ref) { if (!hasProp.call(ref, key)) continue; value = ref[key]; this[key] = value; } } XMLStringifier.prototype.name = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalName('' + val || ''); }; XMLStringifier.prototype.text = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar(this.textEscape('' + val || '')); }; XMLStringifier.prototype.cdata = function(val) { if (this.options.noValidation) { return val; } val = '' + val || ''; val = val.replace(']]>', ']]]]>'); return this.assertLegalChar(val); }; XMLStringifier.prototype.comment = function(val) { if (this.options.noValidation) { return val; } val = '' + val || ''; if (val.match(/--/)) { throw new Error("Comment text cannot contain double-hypen: " + val); } return this.assertLegalChar(val); }; XMLStringifier.prototype.raw = function(val) { if (this.options.noValidation) { return val; } return '' + val || ''; }; XMLStringifier.prototype.attValue = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar(this.attEscape(val = '' + val || '')); }; XMLStringifier.prototype.insTarget = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar('' + val || ''); }; XMLStringifier.prototype.insValue = function(val) { if (this.options.noValidation) { return val; } val = '' + val || ''; if (val.match(/\?>/)) { throw new Error("Invalid processing instruction value: " + val); } return this.assertLegalChar(val); }; XMLStringifier.prototype.xmlVersion = function(val) { if (this.options.noValidation) { return val; } val = '' + val || ''; if (!val.match(/1\.[0-9]+/)) { throw new Error("Invalid version number: " + val); } return val; }; XMLStringifier.prototype.xmlEncoding = function(val) { if (this.options.noValidation) { return val; } val = '' + val || ''; if (!val.match(/^[A-Za-z](?:[A-Za-z0-9._-])*$/)) { throw new Error("Invalid encoding: " + val); } return this.assertLegalChar(val); }; XMLStringifier.prototype.xmlStandalone = function(val) { if (this.options.noValidation) { return val; } if (val) { return "yes"; } else { return "no"; } }; XMLStringifier.prototype.dtdPubID = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar('' + val || ''); }; XMLStringifier.prototype.dtdSysID = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar('' + val || ''); }; XMLStringifier.prototype.dtdElementValue = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar('' + val || ''); }; XMLStringifier.prototype.dtdAttType = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar('' + val || ''); }; XMLStringifier.prototype.dtdAttDefault = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar('' + val || ''); }; XMLStringifier.prototype.dtdEntityValue = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar('' + val || ''); }; XMLStringifier.prototype.dtdNData = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar('' + val || ''); }; XMLStringifier.prototype.convertAttKey = '@'; XMLStringifier.prototype.convertPIKey = '?'; XMLStringifier.prototype.convertTextKey = '#text'; XMLStringifier.prototype.convertCDataKey = '#cdata'; XMLStringifier.prototype.convertCommentKey = '#comment'; XMLStringifier.prototype.convertRawKey = '#raw'; XMLStringifier.prototype.assertLegalChar = function(str) { var regex, res; if (this.options.noValidation) { return str; } regex = ''; if (this.options.version === '1.0') { regex = /[\0-\x08\x0B\f\x0E-\x1F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; if (res = str.match(regex)) { throw new Error("Invalid character in string: " + str + " at index " + res.index); } } else if (this.options.version === '1.1') { regex = /[\0\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; if (res = str.match(regex)) { throw new Error("Invalid character in string: " + str + " at index " + res.index); } } return str; }; XMLStringifier.prototype.assertLegalName = function(str) { var regex; if (this.options.noValidation) { return str; } this.assertLegalChar(str); regex = /^([:A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])([\x2D\.0-:A-Z_a-z\xB7\xC0-\xD6\xD8-\xF6\xF8-\u037D\u037F-\u1FFF\u200C\u200D\u203F\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])*$/; if (!str.match(regex)) { throw new Error("Invalid character in name"); } return str; }; XMLStringifier.prototype.textEscape = function(str) { var ampregex; if (this.options.noValidation) { return str; } ampregex = this.options.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g; return str.replace(ampregex, '&').replace(//g, '>').replace(/\r/g, ' '); }; XMLStringifier.prototype.attEscape = function(str) { var ampregex; if (this.options.noValidation) { return str; } ampregex = this.options.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g; return str.replace(ampregex, '&').replace(/ 0) { return new Array(indentLevel).join(options.indent); } } return ''; }; XMLWriterBase.prototype.endline = function(node, options, level) { if (!options.pretty || options.suppressPrettyCount) { return ''; } else { return options.newline; } }; XMLWriterBase.prototype.attribute = function(att, options, level) { var r; this.openAttribute(att, options, level); r = ' ' + att.name + '="' + att.value + '"'; this.closeAttribute(att, options, level); return r; }; XMLWriterBase.prototype.cdata = function(node, options, level) { var r; this.openNode(node, options, level); options.state = WriterState.OpenTag; r = this.indent(node, options, level) + '' + this.endline(node, options, level); options.state = WriterState.None; this.closeNode(node, options, level); return r; }; XMLWriterBase.prototype.comment = function(node, options, level) { var r; this.openNode(node, options, level); options.state = WriterState.OpenTag; r = this.indent(node, options, level) + '' + this.endline(node, options, level); options.state = WriterState.None; this.closeNode(node, options, level); return r; }; XMLWriterBase.prototype.declaration = function(node, options, level) { var r; this.openNode(node, options, level); options.state = WriterState.OpenTag; r = this.indent(node, options, level) + ''; r += this.endline(node, options, level); options.state = WriterState.None; this.closeNode(node, options, level); return r; }; XMLWriterBase.prototype.docType = function(node, options, level) { var child, i, len, r, ref; level || (level = 0); this.openNode(node, options, level); options.state = WriterState.OpenTag; r = this.indent(node, options, level); r += ' 0) { r += ' ['; r += this.endline(node, options, level); options.state = WriterState.InsideTag; ref = node.children; for (i = 0, len = ref.length; i < len; i++) { child = ref[i]; r += this.writeChildNode(child, options, level + 1); } options.state = WriterState.CloseTag; r += ']'; } options.state = WriterState.CloseTag; r += options.spaceBeforeSlash + '>'; r += this.endline(node, options, level); options.state = WriterState.None; this.closeNode(node, options, level); return r; }; XMLWriterBase.prototype.element = function(node, options, level) { var att, child, childNodeCount, firstChildNode, i, j, len, len1, name, prettySuppressed, r, ref, ref1, ref2; level || (level = 0); prettySuppressed = false; r = ''; this.openNode(node, options, level); options.state = WriterState.OpenTag; r += this.indent(node, options, level) + '<' + node.name; ref = node.attribs; for (name in ref) { if (!hasProp.call(ref, name)) continue; att = ref[name]; r += this.attribute(att, options, level); } childNodeCount = node.children.length; firstChildNode = childNodeCount === 0 ? null : node.children[0]; if (childNodeCount === 0 || node.children.every(function(e) { return (e.type === NodeType.Text || e.type === NodeType.Raw) && e.value === ''; })) { if (options.allowEmpty) { r += '>'; options.state = WriterState.CloseTag; r += '' + this.endline(node, options, level); } else { options.state = WriterState.CloseTag; r += options.spaceBeforeSlash + '/>' + this.endline(node, options, level); } } else if (options.pretty && childNodeCount === 1 && (firstChildNode.type === NodeType.Text || firstChildNode.type === NodeType.Raw) && (firstChildNode.value != null)) { r += '>'; options.state = WriterState.InsideTag; options.suppressPrettyCount++; prettySuppressed = true; r += this.writeChildNode(firstChildNode, options, level + 1); options.suppressPrettyCount--; prettySuppressed = false; options.state = WriterState.CloseTag; r += '' + this.endline(node, options, level); } else { if (options.dontPrettyTextNodes) { ref1 = node.children; for (i = 0, len = ref1.length; i < len; i++) { child = ref1[i]; if ((child.type === NodeType.Text || child.type === NodeType.Raw) && (child.value != null)) { options.suppressPrettyCount++; prettySuppressed = true; break; } } } r += '>' + this.endline(node, options, level); options.state = WriterState.InsideTag; ref2 = node.children; for (j = 0, len1 = ref2.length; j < len1; j++) { child = ref2[j]; r += this.writeChildNode(child, options, level + 1); } options.state = WriterState.CloseTag; r += this.indent(node, options, level) + ''; if (prettySuppressed) { options.suppressPrettyCount--; } r += this.endline(node, options, level); options.state = WriterState.None; } this.closeNode(node, options, level); return r; }; XMLWriterBase.prototype.writeChildNode = function(node, options, level) { switch (node.type) { case NodeType.CData: return this.cdata(node, options, level); case NodeType.Comment: return this.comment(node, options, level); case NodeType.Element: return this.element(node, options, level); case NodeType.Raw: return this.raw(node, options, level); case NodeType.Text: return this.text(node, options, level); case NodeType.ProcessingInstruction: return this.processingInstruction(node, options, level); case NodeType.Dummy: return ''; case NodeType.Declaration: return this.declaration(node, options, level); case NodeType.DocType: return this.docType(node, options, level); case NodeType.AttributeDeclaration: return this.dtdAttList(node, options, level); case NodeType.ElementDeclaration: return this.dtdElement(node, options, level); case NodeType.EntityDeclaration: return this.dtdEntity(node, options, level); case NodeType.NotationDeclaration: return this.dtdNotation(node, options, level); default: throw new Error("Unknown XML node type: " + node.constructor.name); } }; XMLWriterBase.prototype.processingInstruction = function(node, options, level) { var r; this.openNode(node, options, level); options.state = WriterState.OpenTag; r = this.indent(node, options, level) + ''; r += this.endline(node, options, level); options.state = WriterState.None; this.closeNode(node, options, level); return r; }; XMLWriterBase.prototype.raw = function(node, options, level) { var r; this.openNode(node, options, level); options.state = WriterState.OpenTag; r = this.indent(node, options, level); options.state = WriterState.InsideTag; r += node.value; options.state = WriterState.CloseTag; r += this.endline(node, options, level); options.state = WriterState.None; this.closeNode(node, options, level); return r; }; XMLWriterBase.prototype.text = function(node, options, level) { var r; this.openNode(node, options, level); options.state = WriterState.OpenTag; r = this.indent(node, options, level); options.state = WriterState.InsideTag; r += node.value; options.state = WriterState.CloseTag; r += this.endline(node, options, level); options.state = WriterState.None; this.closeNode(node, options, level); return r; }; XMLWriterBase.prototype.dtdAttList = function(node, options, level) { var r; this.openNode(node, options, level); options.state = WriterState.OpenTag; r = this.indent(node, options, level) + '' + this.endline(node, options, level); options.state = WriterState.None; this.closeNode(node, options, level); return r; }; XMLWriterBase.prototype.dtdElement = function(node, options, level) { var r; this.openNode(node, options, level); options.state = WriterState.OpenTag; r = this.indent(node, options, level) + '' + this.endline(node, options, level); options.state = WriterState.None; this.closeNode(node, options, level); return r; }; XMLWriterBase.prototype.dtdEntity = function(node, options, level) { var r; this.openNode(node, options, level); options.state = WriterState.OpenTag; r = this.indent(node, options, level) + '' + this.endline(node, options, level); options.state = WriterState.None; this.closeNode(node, options, level); return r; }; XMLWriterBase.prototype.dtdNotation = function(node, options, level) { var r; this.openNode(node, options, level); options.state = WriterState.OpenTag; r = this.indent(node, options, level) + '' + this.endline(node, options, level); options.state = WriterState.None; this.closeNode(node, options, level); return r; }; XMLWriterBase.prototype.openNode = function(node, options, level) {}; XMLWriterBase.prototype.closeNode = function(node, options, level) {}; XMLWriterBase.prototype.openAttribute = function(att, options, level) {}; XMLWriterBase.prototype.closeAttribute = function(att, options, level) {}; return XMLWriterBase; })(); }).call(this); /***/ }), /***/ 5532: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // Generated by CoffeeScript 1.12.7 (function() { var NodeType, WriterState, XMLDOMImplementation, XMLDocument, XMLDocumentCB, XMLStreamWriter, XMLStringWriter, assign, isFunction, ref; ref = __webpack_require__(78369), assign = ref.assign, isFunction = ref.isFunction; XMLDOMImplementation = __webpack_require__(91770); XMLDocument = __webpack_require__(66934); XMLDocumentCB = __webpack_require__(79227); XMLStringWriter = __webpack_require__(20437); XMLStreamWriter = __webpack_require__(81996); NodeType = __webpack_require__(39335); WriterState = __webpack_require__(30594); module.exports.create = function(name, xmldec, doctype, options) { var doc, root; if (name == null) { throw new Error("Root element needs a name."); } options = assign({}, xmldec, doctype, options); doc = new XMLDocument(options); root = doc.element(name); if (!options.headless) { doc.declaration(options); if ((options.pubID != null) || (options.sysID != null)) { doc.dtd(options); } } return root; }; module.exports.begin = function(options, onData, onEnd) { var ref1; if (isFunction(options)) { ref1 = [options, onData], onData = ref1[0], onEnd = ref1[1]; options = {}; } if (onData) { return new XMLDocumentCB(options, onData, onEnd); } else { return new XMLDocument(options); } }; module.exports.stringWriter = function(options) { return new XMLStringWriter(options); }; module.exports.streamWriter = function(stream, options) { return new XMLStreamWriter(stream, options); }; module.exports.implementation = new XMLDOMImplementation(); module.exports.nodeType = NodeType; module.exports.writerState = WriterState; }).call(this); /***/ }), /***/ 47529: /***/ ((module) => { module.exports = extend var hasOwnProperty = Object.prototype.hasOwnProperty; function extend() { var target = {} for (var i = 0; i < arguments.length; i++) { var source = arguments[i] for (var key in source) { if (hasOwnProperty.call(source, key)) { target[key] = source[key] } } } return target } /***/ }), /***/ 49602: /***/ ((module) => { "use strict"; module.exports = function (Yallist) { Yallist.prototype[Symbol.iterator] = function* () { for (let walker = this.head; walker; walker = walker.next) { yield walker.value } } } /***/ }), /***/ 34411: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = Yallist Yallist.Node = Node Yallist.create = Yallist function Yallist (list) { var self = this if (!(self instanceof Yallist)) { self = new Yallist() } self.tail = null self.head = null self.length = 0 if (list && typeof list.forEach === 'function') { list.forEach(function (item) { self.push(item) }) } else if (arguments.length > 0) { for (var i = 0, l = arguments.length; i < l; i++) { self.push(arguments[i]) } } return self } Yallist.prototype.removeNode = function (node) { if (node.list !== this) { throw new Error('removing node which does not belong to this list') } var next = node.next var prev = node.prev if (next) { next.prev = prev } if (prev) { prev.next = next } if (node === this.head) { this.head = next } if (node === this.tail) { this.tail = prev } node.list.length-- node.next = null node.prev = null node.list = null return next } Yallist.prototype.unshiftNode = function (node) { if (node === this.head) { return } if (node.list) { node.list.removeNode(node) } var head = this.head node.list = this node.next = head if (head) { head.prev = node } this.head = node if (!this.tail) { this.tail = node } this.length++ } Yallist.prototype.pushNode = function (node) { if (node === this.tail) { return } if (node.list) { node.list.removeNode(node) } var tail = this.tail node.list = this node.prev = tail if (tail) { tail.next = node } this.tail = node if (!this.head) { this.head = node } this.length++ } Yallist.prototype.push = function () { for (var i = 0, l = arguments.length; i < l; i++) { push(this, arguments[i]) } return this.length } Yallist.prototype.unshift = function () { for (var i = 0, l = arguments.length; i < l; i++) { unshift(this, arguments[i]) } return this.length } Yallist.prototype.pop = function () { if (!this.tail) { return undefined } var res = this.tail.value this.tail = this.tail.prev if (this.tail) { this.tail.next = null } else { this.head = null } this.length-- return res } Yallist.prototype.shift = function () { if (!this.head) { return undefined } var res = this.head.value this.head = this.head.next if (this.head) { this.head.prev = null } else { this.tail = null } this.length-- return res } Yallist.prototype.forEach = function (fn, thisp) { thisp = thisp || this for (var walker = this.head, i = 0; walker !== null; i++) { fn.call(thisp, walker.value, i, this) walker = walker.next } } Yallist.prototype.forEachReverse = function (fn, thisp) { thisp = thisp || this for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { fn.call(thisp, walker.value, i, this) walker = walker.prev } } Yallist.prototype.get = function (n) { for (var i = 0, walker = this.head; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.next } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.getReverse = function (n) { for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.prev } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.map = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.head; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.next } return res } Yallist.prototype.mapReverse = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.tail; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.prev } return res } Yallist.prototype.reduce = function (fn, initial) { var acc var walker = this.head if (arguments.length > 1) { acc = initial } else if (this.head) { walker = this.head.next acc = this.head.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = 0; walker !== null; i++) { acc = fn(acc, walker.value, i) walker = walker.next } return acc } Yallist.prototype.reduceReverse = function (fn, initial) { var acc var walker = this.tail if (arguments.length > 1) { acc = initial } else if (this.tail) { walker = this.tail.prev acc = this.tail.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = this.length - 1; walker !== null; i--) { acc = fn(acc, walker.value, i) walker = walker.prev } return acc } Yallist.prototype.toArray = function () { var arr = new Array(this.length) for (var i = 0, walker = this.head; walker !== null; i++) { arr[i] = walker.value walker = walker.next } return arr } Yallist.prototype.toArrayReverse = function () { var arr = new Array(this.length) for (var i = 0, walker = this.tail; walker !== null; i++) { arr[i] = walker.value walker = walker.prev } return arr } Yallist.prototype.slice = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = 0, walker = this.head; walker !== null && i < from; i++) { walker = walker.next } for (; walker !== null && i < to; i++, walker = walker.next) { ret.push(walker.value) } return ret } Yallist.prototype.sliceReverse = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { walker = walker.prev } for (; walker !== null && i > from; i--, walker = walker.prev) { ret.push(walker.value) } return ret } Yallist.prototype.splice = function (start, deleteCount /*, ...nodes */) { if (start > this.length) { start = this.length - 1 } if (start < 0) { start = this.length + start; } for (var i = 0, walker = this.head; walker !== null && i < start; i++) { walker = walker.next } var ret = [] for (var i = 0; walker && i < deleteCount; i++) { ret.push(walker.value) walker = this.removeNode(walker) } if (walker === null) { walker = this.tail } if (walker !== this.head && walker !== this.tail) { walker = walker.prev } for (var i = 2; i < arguments.length; i++) { walker = insert(this, walker, arguments[i]) } return ret; } Yallist.prototype.reverse = function () { var head = this.head var tail = this.tail for (var walker = head; walker !== null; walker = walker.prev) { var p = walker.prev walker.prev = walker.next walker.next = p } this.head = tail this.tail = head return this } function insert (self, node, value) { var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self) if (inserted.next === null) { self.tail = inserted } if (inserted.prev === null) { self.head = inserted } self.length++ return inserted } function push (self, item) { self.tail = new Node(item, self.tail, null, self) if (!self.head) { self.head = self.tail } self.length++ } function unshift (self, item) { self.head = new Node(item, null, self.head, self) if (!self.tail) { self.tail = self.head } self.length++ } function Node (value, prev, next, list) { if (!(this instanceof Node)) { return new Node(value, prev, next, list) } this.list = list this.value = value if (prev) { prev.next = this this.prev = prev } else { this.prev = null } if (next) { next.prev = this this.next = next } else { this.next = null } } try { // add if support for Symbol.iterator is present __webpack_require__(49602)(Yallist) } catch (er) {} /***/ }), /***/ 82608: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PRTemplateInvalidPayloadError = exports.FailedToDeletePRTemplateError = exports.FailedToReadPRTemplateError = exports.FailedToCreatePRTemplateError = exports.FailedToGenerateHashError = exports.FailedToLoadCompiledYamlError = exports.FailedToParsePullRequestAttributesError = exports.FailedToCompilePrTemplateError = exports.PullRequestTemplateNotFoundError = exports.FailedToGetPullRequestAttributesError = void 0; const problem_error_1 = __webpack_require__(45280); /** * @class * @name FailedToGetPullRequestAttributesError * @description Snyk could not get the custom pull request template attributes, using the given variables and the fetched pr template. * * See more: * - [https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta](https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta) * @summary Failed to get pull request attributes * @category Fix * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class FailedToGetPullRequestAttributesError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Failed to get pull request attributes', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-pr-template-0001', status: 500, errorCode: 'SNYK-PR-TEMPLATE-0001', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.FailedToGetPullRequestAttributesError = FailedToGetPullRequestAttributesError; /** * @class * @name PullRequestTemplateNotFoundError * @description Could not find pull request template. * @summary Not found * @category Fix * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class PullRequestTemplateNotFoundError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Not found', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-pr-template-0002', status: 404, errorCode: 'SNYK-PR-TEMPLATE-0002', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.PullRequestTemplateNotFoundError = PullRequestTemplateNotFoundError; /** * @class * @name FailedToCompilePrTemplateError * @description Could not compile your customize pull request template, using Handlebars compilation and Snyk variables in place. * * See more: * - [https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta](https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta) * @summary Failed to compile pull request template * @category Fix * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class FailedToCompilePrTemplateError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Failed to compile pull request template', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-pr-template-0003', status: 400, errorCode: 'SNYK-PR-TEMPLATE-0003', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.FailedToCompilePrTemplateError = FailedToCompilePrTemplateError; /** * @class * @name FailedToParsePullRequestAttributesError * @description Snyk could not parse the custom pull request template, using the given variables and assigning them to the fetched pr template. * * See more: * - [https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta](https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta) * @summary Failed to parse pull request attributes * @category Fix * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class FailedToParsePullRequestAttributesError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Failed to parse pull request attributes', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-pr-template-0004', status: 500, errorCode: 'SNYK-PR-TEMPLATE-0004', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.FailedToParsePullRequestAttributesError = FailedToParsePullRequestAttributesError; /** * @class * @name FailedToLoadCompiledYamlError * @description Could not load YAML file after substituting Snyk variables into the custom PR template. * * See more: * - [https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta](https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta) * @summary Failed to load YAML file after substituting Snyk variables * @category Fix * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class FailedToLoadCompiledYamlError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Failed to load YAML file after substituting Snyk variables', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-pr-template-0005', status: 400, errorCode: 'SNYK-PR-TEMPLATE-0005', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.FailedToLoadCompiledYamlError = FailedToLoadCompiledYamlError; /** * @class * @name FailedToGenerateHashError * @description Snyk could not generate hash using the customer PR files and projects vulnIds. * * See more: * - [https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta](https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta) * @summary Failed to generate hash for custom PR template * @category Fix * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class FailedToGenerateHashError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Failed to generate hash for custom PR template', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-pr-template-0006', status: 500, errorCode: 'SNYK-PR-TEMPLATE-0006', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.FailedToGenerateHashError = FailedToGenerateHashError; /** * @class * @name FailedToCreatePRTemplateError * @description Snyk could not create pull request template. * * See more: * - [https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta](https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta) * @summary Unable to create pull request template * @category Fix * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class FailedToCreatePRTemplateError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unable to create pull request template', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-pr-template-0007', status: 500, errorCode: 'SNYK-PR-TEMPLATE-0007', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.FailedToCreatePRTemplateError = FailedToCreatePRTemplateError; /** * @class * @name FailedToReadPRTemplateError * @description Snyk could not get pull request template. * * See more: * - [https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta](https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta) * @summary Unable to get pull request template * @category Fix * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class FailedToReadPRTemplateError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unable to get pull request template', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-pr-template-0008', status: 500, errorCode: 'SNYK-PR-TEMPLATE-0008', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.FailedToReadPRTemplateError = FailedToReadPRTemplateError; /** * @class * @name FailedToDeletePRTemplateError * @description Snyk could not delete pull request template. * * See more: * - [https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta](https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta) * @summary Unable to delete pull request template * @category Fix * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class FailedToDeletePRTemplateError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unable to delete pull request template', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-pr-template-0009', status: 500, errorCode: 'SNYK-PR-TEMPLATE-0009', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.FailedToDeletePRTemplateError = FailedToDeletePRTemplateError; /** * @class * @name PRTemplateInvalidPayloadError * @description The pull request template payload is invalid. * @summary Invalid payload * @category Fix * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class PRTemplateInvalidPayloadError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Invalid payload', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-pr-template-0010', status: 400, errorCode: 'SNYK-PR-TEMPLATE-0010', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.PRTemplateInvalidPayloadError = PRTemplateInvalidPayloadError; //# sourceMappingURL=Fix-error-catalog.js.map /***/ }), /***/ 97142: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UnsupportedEcosystemError = exports.BuildEnvironmentNotFoundError = exports.InvalidRequestError = void 0; const problem_error_1 = __webpack_require__(45280); /** * @class * @name InvalidRequestError * @description The provided request payload is not valid for the selected ecosystem. Please review the API documentation. * * See more: * - [https://apidocs.snyk.io/](https://apidocs.snyk.io/) * @summary Invalid request * @category IsolatedBuilds * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InvalidRequestError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Invalid request', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-8001', status: 400, errorCode: 'SNYK-OS-8001', level: 'error', instance, }, details, Object.assign({ links: [ 'https://apidocs.snyk.io/', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.InvalidRequestError = InvalidRequestError; /** * @class * @name BuildEnvironmentNotFoundError * @description The build environment for the provided context could not be found. Please ensure you have created the build environment first. * @summary Build environment not found * @category IsolatedBuilds * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class BuildEnvironmentNotFoundError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Build environment not found', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-8002', status: 404, errorCode: 'SNYK-OS-8002', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.BuildEnvironmentNotFoundError = BuildEnvironmentNotFoundError; /** * @class * @name UnsupportedEcosystemError * @description The language or package manager is not supported. * * See more: * - [https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/supported-languages-frameworks-and-feature-availability-overview#open-source-and-licensing-snyk-open-source](https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/supported-languages-frameworks-and-feature-availability-overview#open-source-and-licensing-snyk-open-source) * @summary Unsupported Ecosystem * @category IsolatedBuilds * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnsupportedEcosystemError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unsupported Ecosystem', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-8003', status: 400, errorCode: 'SNYK-OS-8003', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/supported-languages-frameworks-and-feature-availability-overview#open-source-and-licensing-snyk-open-source', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnsupportedEcosystemError = UnsupportedEcosystemError; //# sourceMappingURL=IsolatedBuilds-error-catalog.js.map /***/ }), /***/ 16942: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UnsupportedMediaTypeError = exports.UnauthorizedError = exports.RequestEntityTooLargeError = exports.MethodNotAllowedError = exports.NotFoundError = exports.NotAcceptableError = exports.ForbiddenError = exports.BadRequestError = void 0; const problem_error_1 = __webpack_require__(45280); /** * @class * @name BadRequestError * @description The server cannot process the request due to invalid or corrupt data. Review the request, then try again. * * See more: * - [https://docs.snyk.io/snyk-api-info/getting-started-using-snyk-rest-api ](https://docs.snyk.io/snyk-api-info/getting-started-using-snyk-rest-api ) * @summary Bad request * @category OpenAPI * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class BadRequestError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Bad request', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-openapi-0001', status: 400, errorCode: 'SNYK-OPENAPI-0001', level: 'warn', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/snyk-api-info/getting-started-using-snyk-rest-api ', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.BadRequestError = BadRequestError; /** * @class * @name ForbiddenError * @description Access to the requested resource is forbidden. * @summary Forbidden * @category OpenAPI * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class ForbiddenError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Forbidden', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-openapi-0002', status: 403, errorCode: 'SNYK-OPENAPI-0002', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.ForbiddenError = ForbiddenError; /** * @class * @name NotAcceptableError * @description The server cannot provide a response that matches the provided accept headers. Review the request, then try again. * @summary Not acceptable * @category OpenAPI * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class NotAcceptableError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Not acceptable', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-openapi-0003', status: 406, errorCode: 'SNYK-OPENAPI-0003', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.NotAcceptableError = NotAcceptableError; /** * @class * @name NotFoundError * @description The server cannot find the requested resource. * @summary Not found * @category OpenAPI * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class NotFoundError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Not found', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-openapi-0004', status: 404, errorCode: 'SNYK-OPENAPI-0004', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.NotFoundError = NotFoundError; /** * @class * @name MethodNotAllowedError * @description The target endpoint does not support your request method. Review the request, then try again. * @summary Method not allowed * @category OpenAPI * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class MethodNotAllowedError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Method not allowed', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-openapi-0005', status: 405, errorCode: 'SNYK-OPENAPI-0005', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.MethodNotAllowedError = MethodNotAllowedError; /** * @class * @name RequestEntityTooLargeError * @description The request entity exceeds server limitations. * @summary Request entity too large * @category OpenAPI * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class RequestEntityTooLargeError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Request entity too large', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-openapi-0006', status: 413, errorCode: 'SNYK-OPENAPI-0006', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.RequestEntityTooLargeError = RequestEntityTooLargeError; /** * @class * @name UnauthorizedError * @description The request lacks authentication credentials for the requested resource. * * See more: * - [https://docs.snyk.io/snyk-api-info/authentication-for-api ](https://docs.snyk.io/snyk-api-info/authentication-for-api ) * @summary Unauthorized * @category OpenAPI * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnauthorizedError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unauthorized', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-openapi-0007', status: 401, errorCode: 'SNYK-OPENAPI-0007', level: 'warn', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/snyk-api-info/authentication-for-api ', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnauthorizedError = UnauthorizedError; /** * @class * @name UnsupportedMediaTypeError * @description The media format of the request is not supported. * @summary Unsupported media type * @category OpenAPI * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnsupportedMediaTypeError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unsupported media type', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-openapi-0008', status: 415, errorCode: 'SNYK-OPENAPI-0008', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnsupportedMediaTypeError = UnsupportedMediaTypeError; //# sourceMappingURL=OpenAPI-error-catalog.js.map /***/ }), /***/ 45244: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UnsupportedRequirementsFileError = exports.InvalidConfigurationError = exports.MissingSupportedFileError = exports.Base64DecodeError = exports.Base64EncodeError = exports.CouldNotParseJSONFileError = exports.NoDependencyUpdatesError = exports.NoValidPackageUpgradesError = exports.ChildProcessExecutionError = exports.NoResultsFromForkerProcessesError = exports.UnknownBlobEncodingOnGithubError = exports.BadNPMVersionError = exports.UnableToReplaceBrokerURLError = exports.CouldNotFindBrokerURLError = exports.CouldNotParseNPMRegistryURLError = exports.NoRepoFoundForTheNPMPackageError = exports.TimeoutWhenProcessingTheDepTreeError = exports.SourceNotSupportedError = exports.NoReleasedVersionForVersionsRangeError = exports.CannotCreateGitHostError = exports.CannotGetBuildFileFromRepoError = exports.CannotResolveTargetPomFromRepoError = exports.CannotResolveTargetPomFromXmlError = exports.MissingProjectFromPomError = exports.PomFileNotFoundError = exports.SkippedGroupError = exports.InvalidCoordinatesError = exports.UnableToParseXMLError = exports.CyclicPropertyDetectedInPomFileError = exports.UnableToResolveVersionForPropertyError = exports.UnableToResolveValueForPropertyError = exports.MissingRequirementFromPomError = exports.UnsupportedExternalFileGenerationSCMError = exports.InconsistentVendoringError = exports.IncompleteProjectError = exports.SsoReAuthRequiredError = exports.GoModFileMissingError = exports.PrivateModuleError = exports.PublishFailedError = exports.MissingStaticMainFunctionError = exports.UnsupportedTargetFrameworkError = exports.UnsupportedManifestFileError = exports.MissingEnvironmentVariableError = exports.CannotGetFileFromSourceError = exports.UnprocessableFileError = exports.MissingPayloadError = exports.MissingHeaderError = exports.UnknownDependencyVersionError = exports.UnparseableLockFileError = exports.UnparseableManifestError = void 0; exports.FailedToApplyDependencyUpdatesError = exports.TooManyManifestFilesError = void 0; const problem_error_1 = __webpack_require__(45280); /** * @class * @name UnparseableManifestError * @description The provided manifest file could not be parsed as it has invalid syntax or does not match the expected schema. Review the manifest file, then try again. * @summary Unable to parse manifest file * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnparseableManifestError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unable to parse manifest file', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-0001', status: 400, errorCode: 'SNYK-OS-0001', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnparseableManifestError = UnparseableManifestError; /** * @class * @name UnparseableLockFileError * @description The provided lock file could not be parsed as it has invalid syntax or does not match the expected schema. Review the lock file, then try again. * @summary Unable to parse lock file * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnparseableLockFileError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unable to parse lock file', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-0002', status: 400, errorCode: 'SNYK-OS-0002', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnparseableLockFileError = UnparseableLockFileError; /** * @class * @name UnknownDependencyVersionError * @description Dependency version could not be resolved. * * See more: * - [https://support.snyk.io/hc/en-us/articles/360001373178-Could-not-determine-version-for-dependencies](https://support.snyk.io/hc/en-us/articles/360001373178-Could-not-determine-version-for-dependencies) * @summary Unknown dependency version * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnknownDependencyVersionError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unknown dependency version', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-0003', status: 404, errorCode: 'SNYK-OS-0003', level: 'warn', instance, }, details, Object.assign({ links: [ 'https://support.snyk.io/hc/en-us/articles/360001373178-Could-not-determine-version-for-dependencies', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnknownDependencyVersionError = UnknownDependencyVersionError; /** * @class * @name MissingHeaderError * @description The server encountered a request that is missing a mandatory request header. * @summary Missing required request header * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class MissingHeaderError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Missing required request header', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-0004', status: 422, errorCode: 'SNYK-OS-0004', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.MissingHeaderError = MissingHeaderError; /** * @class * @name MissingPayloadError * @description The server could not process the request. * @summary Payload missing required elements * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class MissingPayloadError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Payload missing required elements', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-0005', status: 422, errorCode: 'SNYK-OS-0005', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.MissingPayloadError = MissingPayloadError; /** * @class * @name UnprocessableFileError * @description The dependency service could not process the files. * @summary Files cannot be processed * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnprocessableFileError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Files cannot be processed', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-0006', status: 422, errorCode: 'SNYK-OS-0006', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnprocessableFileError = UnprocessableFileError; /** * @class * @name CannotGetFileFromSourceError * @description Could not get the file from the source URL. * @summary Cannot get file from source * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class CannotGetFileFromSourceError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Cannot get file from source', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-0007', status: 500, errorCode: 'SNYK-OS-0007', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.CannotGetFileFromSourceError = CannotGetFileFromSourceError; /** * @class * @name MissingEnvironmentVariableError * @description The server encountered a critical operation that requires a specific environment variable, but the variable is not set or is not accessible within the current environment. * @summary Missing environment variable * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class MissingEnvironmentVariableError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Missing environment variable', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-0008', status: 500, errorCode: 'SNYK-OS-0008', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.MissingEnvironmentVariableError = MissingEnvironmentVariableError; /** * @class * @name UnsupportedManifestFileError * @description The provided manifest file is not supported by Snyk for .NET. * * See more: * - [https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/.net](https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/.net) * @summary Unsupported manifest file type for remediation * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnsupportedManifestFileError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unsupported manifest file type for remediation', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-dotnet-0001', status: 400, errorCode: 'SNYK-OS-DOTNET-0001', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/.net', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnsupportedManifestFileError = UnsupportedManifestFileError; /** * @class * @name UnsupportedTargetFrameworkError * @description The provided manifest file defines a `` or `` that is not currently supported by Snyk's .NET scanning solution. * @summary Target framework not supported * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnsupportedTargetFrameworkError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Target framework not supported', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-dotnet-0002', status: 422, errorCode: 'SNYK-OS-DOTNET-0002', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnsupportedTargetFrameworkError = UnsupportedTargetFrameworkError; /** * @class * @name MissingStaticMainFunctionError * @description This error occurs when no static Main method with a correct signature is found in the code that produces an executable file. * It also occurs if the entry point function, `Main`, is defined with the wrong case, such as lower-case main. * * In order to fix this issue, ensure that your program has a .cs file that contains a main function, such as * ```c# * namespace Example * { * class Program * { * static void Main(string[] args) * { * Console.WriteLine("hello world"); * } * } * } * ``` * * See more: * - [https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs5001](https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs5001) * @summary Your C# code is missing a static Main function * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class MissingStaticMainFunctionError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Your C# code is missing a static Main function', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-dotnet-0003', status: 422, errorCode: 'SNYK-OS-DOTNET-0003', level: 'error', instance, }, details, Object.assign({ links: [ 'https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs5001', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.MissingStaticMainFunctionError = MissingStaticMainFunctionError; /** * @class * @name PublishFailedError * @description This error occurs when running `dotnet publish --sc --framework ` fails to generate a * self-contained binary. Snyk needs to run this command in order to adequately determine the dependency tree for your project. If this command fails, Snyk cannot continue. * * Steps to determine why this happened: * * * Checkout a clean version of your project in a temporary folder * * Run `dotnet publish --sc --framework ` on your project, and confirm this step fails. * * If this step is successful locally, it is possible that Snyk is running another version of the .NET SDK. To tell Snyk which version of the .NET SDK to use, consider using the [global.json](https://learn.microsoft.com/en-us/dotnet/core/tools/global-json) solution provided by Microsoft. * * See more: * - [https://learn.microsoft.com/en-us/dotnet/core/tools/sdk-errors/](https://learn.microsoft.com/en-us/dotnet/core/tools/sdk-errors/) * - [https://learn.microsoft.com/en-us/dotnet/core/tools/global-json](https://learn.microsoft.com/en-us/dotnet/core/tools/global-json) * - [https://github.com/snyk/snyk-nuget-plugin/blob/885486aa656c28d3db465c8d22710770d5cc6773/lib/nuget-parser/cli/dotnet.ts#L67](https://github.com/snyk/snyk-nuget-plugin/blob/885486aa656c28d3db465c8d22710770d5cc6773/lib/nuget-parser/cli/dotnet.ts#L67) * @summary The dotnet CLI is unable to generate a self-contained binary * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class PublishFailedError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'The dotnet CLI is unable to generate a self-contained binary', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-dotnet-0004', status: 422, errorCode: 'SNYK-OS-DOTNET-0004', level: 'error', instance, }, details, Object.assign({ links: [ 'https://learn.microsoft.com/en-us/dotnet/core/tools/sdk-errors/', 'https://learn.microsoft.com/en-us/dotnet/core/tools/global-json', 'https://github.com/snyk/snyk-nuget-plugin/blob/885486aa656c28d3db465c8d22710770d5cc6773/lib/nuget-parser/cli/dotnet.ts#L67', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.PublishFailedError = PublishFailedError; /** * @class * @name PrivateModuleError * @description Snyk could not access the private modules within your go.mod files. * * See more: * - [https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/go](https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/go) * @summary Failed to access private module * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class PrivateModuleError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Failed to access private module', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-go-0001', status: 400, errorCode: 'SNYK-OS-GO-0001', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/go', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.PrivateModuleError = PrivateModuleError; /** * @class * @name GoModFileMissingError * @description A go.mod file was not found in the current directory or any parent directory. * * See more: * - [https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/go](https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/go) * @summary Go mod file not found * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class GoModFileMissingError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Go mod file not found', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-go-0002', status: 400, errorCode: 'SNYK-OS-GO-0002', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/go', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.GoModFileMissingError = GoModFileMissingError; /** * @class * @name SsoReAuthRequiredError * @description Your code is cloned on an isolated environment using Git as it is required by Snyk to analyze its dependencies. * * Your Organization has enabled or enforced SAML SSO after you authorized Snyk to access your code, and a re-authentication is therefore required. * * The error you're seeing is usually reproducible by attempting to do a `git clone` of your repository with incorrectly configured credentials. * Verify your authentication configuration with your Git cloud provider and try again. * * See more: * - [https://docs.github.com/en/enterprise-cloud@latest/authentication/authenticating-with-saml-single-sign-on/about-authentication-with-saml-single-sign-on#about-oauth-apps-github-apps-and-saml-sso](https://docs.github.com/en/enterprise-cloud@latest/authentication/authenticating-with-saml-single-sign-on/about-authentication-with-saml-single-sign-on#about-oauth-apps-github-apps-and-saml-sso) * @summary OAuth re-authorization required * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class SsoReAuthRequiredError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'OAuth re-authorization required', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-go-0003', status: 422, errorCode: 'SNYK-OS-GO-0003', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.github.com/en/enterprise-cloud@latest/authentication/authenticating-with-saml-single-sign-on/about-authentication-with-saml-single-sign-on#about-oauth-apps-github-apps-and-saml-sso', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.SsoReAuthRequiredError = SsoReAuthRequiredError; /** * @class * @name IncompleteProjectError * @description Generating the dependency graph requires Snyk to run go list `go list -deps -json` inside the project. If the operation fails, creating a full dependency graph cannot continue. * * This error means that you need some cleanup, such as `go mod tidy`) or your project deployment process contains a code generation step such as `protobuf` or similar that is not currently supported by Snyk. * * To verify if this is the case, clone your project in a clean environment, run go list `go list -deps -json` and verify whether the operation fails. * * If Snyk cannot process your code successfully, insert the Snyk CLI as part of your deployment pipeline. * * See more: * - [https://docs.snyk.io/snyk-cli](https://docs.snyk.io/snyk-cli) * - [https://github.com/snyk/snyk-go-plugin](https://github.com/snyk/snyk-go-plugin) * - [https://github.com/golang/go/blob/master/src/cmd/go/internal/list/list.go](https://github.com/golang/go/blob/master/src/cmd/go/internal/list/list.go) * @summary Your project repository is missing required files * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class IncompleteProjectError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Your project repository is missing required files', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-go-0004', status: 422, errorCode: 'SNYK-OS-GO-0004', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/snyk-cli', 'https://github.com/snyk/snyk-go-plugin', 'https://github.com/golang/go/blob/master/src/cmd/go/internal/list/list.go', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.IncompleteProjectError = IncompleteProjectError; /** * @class * @name InconsistentVendoringError * @description Generating the dependency graph requires Snyk to run `go list -deps -json` inside the project. If the operation fails, creating a full dependency graph cannot continue. * * This error means that there is inconsistency between your `vendor/modules.txt` file and your `go.mod` file. To remediate, you need to: * * * `go mod vendor` * * `go mod tidy` * * Next, commit those changes to your repo. Snyk does not manipulate with your code on our end by design, which is why this is not done automatically. * * To verify if this is the case, clone your project in a clean environment, run go list `go list -deps -json` and verify whether the operation fails. * Then try and run the above mentioned commands and see if your SCM system reports changes in files. * * See more: * - [https://go.dev/ref/mod#go-mod-vendor](https://go.dev/ref/mod#go-mod-vendor) * @summary Your project repository has inconsistent vendoring information * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InconsistentVendoringError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Your project repository has inconsistent vendoring information', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-go-0005', status: 422, errorCode: 'SNYK-OS-GO-0005', level: 'error', instance, }, details, Object.assign({ links: [ 'https://go.dev/ref/mod#go-mod-vendor', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.InconsistentVendoringError = InconsistentVendoringError; /** * @class * @name UnsupportedExternalFileGenerationSCMError * @description Snyk currently does not support external file generation in your project. This limitation is due to Snyk's lack of visibility into the third-party generator tools you may be using and the specific commands required to generate these files. * * Snyk can only work with the files available in your repository and does not have insight into the generation process for external files. * @summary Unsupported external file generation * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnsupportedExternalFileGenerationSCMError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unsupported external file generation', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-go-0006', status: 422, errorCode: 'SNYK-OS-GO-0006', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnsupportedExternalFileGenerationSCMError = UnsupportedExternalFileGenerationSCMError; /** * @class * @name MissingRequirementFromPomError * @description The required property is missing from the pom object. * @summary Missing property * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class MissingRequirementFromPomError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Missing property', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0001', status: 422, errorCode: 'SNYK-OS-MAVEN-0001', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.MissingRequirementFromPomError = MissingRequirementFromPomError; /** * @class * @name UnableToResolveValueForPropertyError * @description The targeted property could not be resolved with a valid value. * @summary Unable to resolve value for property * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnableToResolveValueForPropertyError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unable to resolve value for property', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0002', status: 422, errorCode: 'SNYK-OS-MAVEN-0002', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnableToResolveValueForPropertyError = UnableToResolveValueForPropertyError; /** * @class * @name UnableToResolveVersionForPropertyError * @description The targeted property could not be resolved with a valid version. * @summary Unable to resolve version for property * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnableToResolveVersionForPropertyError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unable to resolve version for property', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0003', status: 422, errorCode: 'SNYK-OS-MAVEN-0003', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnableToResolveVersionForPropertyError = UnableToResolveVersionForPropertyError; /** * @class * @name CyclicPropertyDetectedInPomFileError * @description There is circular dependency among properties in the Maven project's configuration file (POM), preventing proper resolution and causing an error. * @summary Cyclic property detected in POM file * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class CyclicPropertyDetectedInPomFileError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Cyclic property detected in POM file', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0004', status: 422, errorCode: 'SNYK-OS-MAVEN-0004', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.CyclicPropertyDetectedInPomFileError = CyclicPropertyDetectedInPomFileError; /** * @class * @name UnableToParseXMLError * @description There is an error parsing the XML file. This could be referring to either pom.xml or maven-metadata.xml. * @summary Error parsing the XML file * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnableToParseXMLError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Error parsing the XML file', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0005', status: 500, errorCode: 'SNYK-OS-MAVEN-0005', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnableToParseXMLError = UnableToParseXMLError; /** * @class * @name InvalidCoordinatesError * @description The coordinates provided for a project were invalid. * @summary Invalid coordinates provided * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InvalidCoordinatesError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Invalid coordinates provided', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0006', status: 422, errorCode: 'SNYK-OS-MAVEN-0006', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.InvalidCoordinatesError = InvalidCoordinatesError; /** * @class * @name SkippedGroupError * @description Skipping a specific groupId starting due to remapped coordinates. * @summary Skipping group * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class SkippedGroupError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Skipping group', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0007', status: 422, errorCode: 'SNYK-OS-MAVEN-0007', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.SkippedGroupError = SkippedGroupError; /** * @class * @name PomFileNotFoundError * @description The pom file was not found in Maven repository. * @summary Pom file not found * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class PomFileNotFoundError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Pom file not found', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0008', status: 422, errorCode: 'SNYK-OS-MAVEN-0008', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.PomFileNotFoundError = PomFileNotFoundError; /** * @class * @name MissingProjectFromPomError * @description A project element is missing from POM. * @summary Missing project from POM * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class MissingProjectFromPomError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Missing project from POM', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0009', status: 422, errorCode: 'SNYK-OS-MAVEN-0009', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.MissingProjectFromPomError = MissingProjectFromPomError; /** * @class * @name CannotResolveTargetPomFromXmlError * @description Cannot resolve the targeted POM from the input XML. * @summary Cannot resolve the target POM from the input XML * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class CannotResolveTargetPomFromXmlError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Cannot resolve the target POM from the input XML', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0010', status: 422, errorCode: 'SNYK-OS-MAVEN-0010', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.CannotResolveTargetPomFromXmlError = CannotResolveTargetPomFromXmlError; /** * @class * @name CannotResolveTargetPomFromRepoError * @description Cannot resolve the targeted POM from the repository. * @summary Cannot resolve the target POM from the repository * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class CannotResolveTargetPomFromRepoError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Cannot resolve the target POM from the repository', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0011', status: 404, errorCode: 'SNYK-OS-MAVEN-0011', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.CannotResolveTargetPomFromRepoError = CannotResolveTargetPomFromRepoError; /** * @class * @name CannotGetBuildFileFromRepoError * @description Cannot get the build file repository. * @summary Cannot get the build file repository * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class CannotGetBuildFileFromRepoError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Cannot get the build file repository', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0012', status: 404, errorCode: 'SNYK-OS-MAVEN-0012', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.CannotGetBuildFileFromRepoError = CannotGetBuildFileFromRepoError; /** * @class * @name CannotCreateGitHostError * @description Cannot create source URL. * @summary Unable to create hosted git info * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class CannotCreateGitHostError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unable to create hosted git info', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0013', status: 500, errorCode: 'SNYK-OS-MAVEN-0013', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.CannotCreateGitHostError = CannotCreateGitHostError; /** * @class * @name NoReleasedVersionForVersionsRangeError * @description There was no version released for the specified versions range. * @summary No released version for versions range * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class NoReleasedVersionForVersionsRangeError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'No released version for versions range', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0014', status: 422, errorCode: 'SNYK-OS-MAVEN-0014', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.NoReleasedVersionForVersionsRangeError = NoReleasedVersionForVersionsRangeError; /** * @class * @name SourceNotSupportedError * @description The source used is not supported by fetcher. The supported sources are: github, bitbucket, gitlab. * @summary Source is not supported * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class SourceNotSupportedError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Source is not supported', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0015', status: 422, errorCode: 'SNYK-OS-MAVEN-0015', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.SourceNotSupportedError = SourceNotSupportedError; /** * @class * @name TimeoutWhenProcessingTheDepTreeError * @description There was an timeout when processing the dependecy tree. * @summary Timeout when processing the dependency tree * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class TimeoutWhenProcessingTheDepTreeError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Timeout when processing the dependency tree', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0016', status: 422, errorCode: 'SNYK-OS-MAVEN-0016', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.TimeoutWhenProcessingTheDepTreeError = TimeoutWhenProcessingTheDepTreeError; /** * @class * @name NoRepoFoundForTheNPMPackageError * @description No repository found for the NPM package. * @summary No repository found for A NPM package * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class NoRepoFoundForTheNPMPackageError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'No repository found for A NPM package', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0001', status: 422, errorCode: 'SNYK-OS-NODEJS-0001', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.NoRepoFoundForTheNPMPackageError = NoRepoFoundForTheNPMPackageError; /** * @class * @name CouldNotParseNPMRegistryURLError * @description Could not parse NPM registry URL. * @summary Could not parse NPM registry URL * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class CouldNotParseNPMRegistryURLError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Could not parse NPM registry URL', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0002', status: 422, errorCode: 'SNYK-OS-NODEJS-0002', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.CouldNotParseNPMRegistryURLError = CouldNotParseNPMRegistryURLError; /** * @class * @name CouldNotFindBrokerURLError * @description Could not find a broker resolved URL. * @summary Could not find a broker resolved URL * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class CouldNotFindBrokerURLError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Could not find a broker resolved URL', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0003', status: 422, errorCode: 'SNYK-OS-NODEJS-0003', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.CouldNotFindBrokerURLError = CouldNotFindBrokerURLError; /** * @class * @name UnableToReplaceBrokerURLError * @description Unable to replace all broker urls in lock file. * @summary Unable to replace broker URL * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnableToReplaceBrokerURLError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unable to replace broker URL', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0004', status: 422, errorCode: 'SNYK-OS-NODEJS-0004', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnableToReplaceBrokerURLError = UnableToReplaceBrokerURLError; /** * @class * @name BadNPMVersionError * @description The NPM version is not supported. * @summary Bad NPM version * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class BadNPMVersionError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Bad NPM version', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0005', status: 422, errorCode: 'SNYK-OS-NODEJS-0005', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.BadNPMVersionError = BadNPMVersionError; /** * @class * @name UnknownBlobEncodingOnGithubError * @description Unknown blob encoding on Github. * @summary Unknown blob encoding on Github * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnknownBlobEncodingOnGithubError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unknown blob encoding on Github', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0006', status: 422, errorCode: 'SNYK-OS-NODEJS-0006', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnknownBlobEncodingOnGithubError = UnknownBlobEncodingOnGithubError; /** * @class * @name NoResultsFromForkerProcessesError * @description No result from forked process. * @summary No result from forked process * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class NoResultsFromForkerProcessesError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'No result from forked process', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0007', status: 500, errorCode: 'SNYK-OS-NODEJS-0007', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.NoResultsFromForkerProcessesError = NoResultsFromForkerProcessesError; /** * @class * @name ChildProcessExecutionError * @description The child process encountered an error during execution. * @summary Child Process Execution Error * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class ChildProcessExecutionError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Child Process Execution Error', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0008', status: 500, errorCode: 'SNYK-OS-NODEJS-0008', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.ChildProcessExecutionError = ChildProcessExecutionError; /** * @class * @name NoValidPackageUpgradesError * @description The system attempted to find valid upgrades for the packages specified in the lock file, but none were available. * @summary No valid package upgrades * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class NoValidPackageUpgradesError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'No valid package upgrades', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0009', status: 422, errorCode: 'SNYK-OS-NODEJS-0009', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.NoValidPackageUpgradesError = NoValidPackageUpgradesError; /** * @class * @name NoDependencyUpdatesError * @description There are no available updates for the dependencies. * @summary No dependency updates * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class NoDependencyUpdatesError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'No dependency updates', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0010', status: 422, errorCode: 'SNYK-OS-NODEJS-0010', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.NoDependencyUpdatesError = NoDependencyUpdatesError; /** * @class * @name CouldNotParseJSONFileError * @description An error occurred while attempting to parse a JSON file. * @summary Could not parse JSON file * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class CouldNotParseJSONFileError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Could not parse JSON file', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0011', status: 422, errorCode: 'SNYK-OS-NODEJS-0011', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.CouldNotParseJSONFileError = CouldNotParseJSONFileError; /** * @class * @name Base64EncodeError * @description An error occurred while attempting to perform Base64 encoding. * @summary Could not Base64 encode * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class Base64EncodeError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Could not Base64 encode', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0012', status: 422, errorCode: 'SNYK-OS-NODEJS-0012', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.Base64EncodeError = Base64EncodeError; /** * @class * @name Base64DecodeError * @description An error occurred while attempting to perform Base64 decoding. * @summary Could not Base64 decode * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class Base64DecodeError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Could not Base64 decode', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0013', status: 422, errorCode: 'SNYK-OS-NODEJS-0013', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.Base64DecodeError = Base64DecodeError; /** * @class * @name MissingSupportedFileError * @description Could not find supported file. * @summary Missing supported file * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class MissingSupportedFileError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Missing supported file', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0014', status: 400, errorCode: 'SNYK-OS-NODEJS-0014', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.MissingSupportedFileError = MissingSupportedFileError; /** * @class * @name InvalidConfigurationError * @description The configuration parameter does not meet the expected data type. Please ensure the provided value is of the correct data type. * @summary Invalid configuration * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InvalidConfigurationError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Invalid configuration', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0015', status: 400, errorCode: 'SNYK-OS-NODEJS-0015', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.InvalidConfigurationError = InvalidConfigurationError; /** * @class * @name UnsupportedRequirementsFileError * @description The provided requirements file is not supported by Snyk for Python. * * See more: * - [https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/python](https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/python) * @summary Unsupported manifest file type for remediation * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnsupportedRequirementsFileError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unsupported manifest file type for remediation', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-pip-0001', status: 422, errorCode: 'SNYK-OS-PIP-0001', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/python', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnsupportedRequirementsFileError = UnsupportedRequirementsFileError; /** * @class * @name TooManyManifestFilesError * @description Too many manifest files were provided in the request body. * @summary Received more manifests than expected * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class TooManyManifestFilesError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Received more manifests than expected', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-pip-0002', status: 422, errorCode: 'SNYK-OS-PIP-0002', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.TooManyManifestFilesError = TooManyManifestFilesError; /** * @class * @name FailedToApplyDependencyUpdatesError * @description An error occured while updating dependencies. * @summary Failed to apply dependency updates * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class FailedToApplyDependencyUpdatesError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Failed to apply dependency updates', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-pip-0003', status: 422, errorCode: 'SNYK-OS-PIP-0003', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.FailedToApplyDependencyUpdatesError = FailedToApplyDependencyUpdatesError; //# sourceMappingURL=OpenSourceEcosystems-error-catalog.js.map /***/ }), /***/ 5410: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.InternalServerError = exports.StorageFailureError = exports.DataTransformationError = exports.InvalidResponseError = exports.InvalidRequestError = void 0; const problem_error_1 = __webpack_require__(45280); /** * @class * @name InvalidRequestError * @description Check the body of your request and try again. * @summary Invalid request * @category OpenSourceProjectIssues * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InvalidRequestError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Invalid request', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-ospi-1001', status: 400, errorCode: 'SNYK-OSSI-OSPI-1001', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.InvalidRequestError = InvalidRequestError; /** * @class * @name InvalidResponseError * @description This issue is unexpected, and the service will recover shortly. If the error still occurs, contact support. * @summary Unable to return valid API response * @category OpenSourceProjectIssues * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InvalidResponseError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unable to return valid API response', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-ospi-1002', status: 500, errorCode: 'SNYK-OSSI-OSPI-1002', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.InvalidResponseError = InvalidResponseError; /** * @class * @name DataTransformationError * @description This issue is unexpected, and the service will recover shortly. If the error still occurs, contact support. * @summary Failed to process data * @category OpenSourceProjectIssues * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class DataTransformationError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Failed to process data', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-ospi-2001', status: 500, errorCode: 'SNYK-OSSI-OSPI-2001', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.DataTransformationError = DataTransformationError; /** * @class * @name StorageFailureError * @description Check inputs and then try again. If the error still occurs, contact support. * @summary Failed to store issue data * @category OpenSourceProjectIssues * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class StorageFailureError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Failed to store issue data', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-ospi-3001', status: 500, errorCode: 'SNYK-OSSI-OSPI-3001', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.StorageFailureError = StorageFailureError; /** * @class * @name InternalServerError * @description This issue is unexpected, and the service will recover shortly. If the error still occurs, contact support. * @summary Internal server error * @category OpenSourceProjectIssues * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InternalServerError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Internal server error', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-ospi-4001', status: 500, errorCode: 'SNYK-OSSI-OSPI-4001', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.InternalServerError = InternalServerError; //# sourceMappingURL=OpenSourceProjectIssues-error-catalog.js.map /***/ }), /***/ 45996: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.InternalServerError = exports.StorageFailureError = exports.DataTransformationError = exports.InvalidResponseError = exports.InvalidRequestError = void 0; const problem_error_1 = __webpack_require__(45280); /** * @class * @name InvalidRequestError * @description Check the body of your request and try again. * @summary Invalid request * @category OpenSourceProjectSnapshots * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InvalidRequestError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Invalid request', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-ospss-1001', status: 400, errorCode: 'SNYK-OSSI-OSPSS-1001', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.InvalidRequestError = InvalidRequestError; /** * @class * @name InvalidResponseError * @description This issue is unexpected, and the service will recover shortly. If the error still occurs, contact support. * @summary Unable to return valid API response * @category OpenSourceProjectSnapshots * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InvalidResponseError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unable to return valid API response', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-ospss-1002', status: 500, errorCode: 'SNYK-OSSI-OSPSS-1002', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.InvalidResponseError = InvalidResponseError; /** * @class * @name DataTransformationError * @description This issue is unexpected, and the service will recover shortly. If the error still occurs, contact support. * @summary Failed to process data * @category OpenSourceProjectSnapshots * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class DataTransformationError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Failed to process data', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-ospss-2001', status: 500, errorCode: 'SNYK-OSSI-OSPSS-2001', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.DataTransformationError = DataTransformationError; /** * @class * @name StorageFailureError * @description Check inputs and then try again. If the error still occurs, contact support. * @summary Failed to store snapshot data * @category OpenSourceProjectSnapshots * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class StorageFailureError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Failed to store snapshot data', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-ospss-3001', status: 500, errorCode: 'SNYK-OSSI-OSPSS-3001', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.StorageFailureError = StorageFailureError; /** * @class * @name InternalServerError * @description This issue is unexpected, and the service will recover shortly. If the error still occurs, contact support. * @summary Internal server error * @category OpenSourceProjectSnapshots * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InternalServerError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Internal server error', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-ospss-4001', status: 500, errorCode: 'SNYK-OSSI-OSPSS-4001', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.InternalServerError = InternalServerError; //# sourceMappingURL=OpenSourceProjectSnapshots-error-catalog.js.map /***/ }), /***/ 41017: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Sha1NotFoundError = exports.MavenSearchServiceUnavailableError = void 0; const problem_error_1 = __webpack_require__(45280); /** * @class * @name MavenSearchServiceUnavailableError * @description The upstream Maven search service is not available. * * See more: * - [https://search.maven.org](https://search.maven.org) * - [https://status.maven.org](https://status.maven.org) * @summary Maven search service unavailable * @category OpenSourceUnmanaged * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class MavenSearchServiceUnavailableError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Maven search service unavailable', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-osjvm-001', status: 503, errorCode: 'SNYK-OSJVM-001', level: 'warn', instance, }, details, Object.assign({ links: [ 'https://search.maven.org', 'https://status.maven.org', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.MavenSearchServiceUnavailableError = MavenSearchServiceUnavailableError; /** * @class * @name Sha1NotFoundError * @description Unable to find the coordinates for the provided SHA1. * * See more: * - [https://docs.snyk.io/snyk-cli/test-for-vulnerabilities/scan-all-unmanaged-jar-files](https://docs.snyk.io/snyk-cli/test-for-vulnerabilities/scan-all-unmanaged-jar-files) * @summary SHA1 not found * @category OpenSourceUnmanaged * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class Sha1NotFoundError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'SHA1 not found', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-osjvm-002', status: 404, errorCode: 'SNYK-OSJVM-002', level: 'warn', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/snyk-cli/test-for-vulnerabilities/scan-all-unmanaged-jar-files', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.Sha1NotFoundError = Sha1NotFoundError; //# sourceMappingURL=OpenSourceUnmanaged-error-catalog.js.map /***/ }), /***/ 18549: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UnsupportedContainerVendorError = exports.UndefinedContainerVendorError = exports.UnsupportedDebianDistroError = exports.UndefinedContainerDistroError = exports.TooManyIssuesError = exports.TooManyPurlsError = exports.InvalidPaginationParametersError = exports.InternalServerError = exports.VulndbNextError = exports.VulnDBInvalidResponseError = exports.VulnerabilityServiceUnavailableError = exports.PackageNotFoundError = exports.UnsupportedGoVersionFormatError = exports.ComponentNotSupportedError = exports.MissingComponentError = exports.UnsupportedEcosystemError = exports.NamespaceNotProvidedError = exports.InvalidPurlError = exports.AuthorizationRequestFailureError = exports.OrganizationNotWhitelistedError = void 0; const problem_error_1 = __webpack_require__(45280); /** * @class * @name OrganizationNotWhitelistedError * @description You likely don’t have access to the features in Beta. To get access, you can request access to features in Beta through your account manager or team. * @summary Your Organisation is not authorized to perform this action * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class OrganizationNotWhitelistedError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Your Organisation is not authorized to perform this action', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-1040', status: 403, errorCode: 'SNYK-OSSI-1040', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.OrganizationNotWhitelistedError = OrganizationNotWhitelistedError; /** * @class * @name AuthorizationRequestFailureError * @description Unexpected error when authenticating. Try again, and if the error still occurs, contact support. * @summary Authorization request failure * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class AuthorizationRequestFailureError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Authorization request failure', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-1050', status: 500, errorCode: 'SNYK-OSSI-1050', level: 'fatal', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.AuthorizationRequestFailureError = AuthorizationRequestFailureError; /** * @class * @name InvalidPurlError * @description Make sure that the purl is valid. See the Package URL specification link for further information. * * See more: * - [https://github.com/package-url/purl-spec/blob/master/PURL-SPECIFICATION.rst](https://github.com/package-url/purl-spec/blob/master/PURL-SPECIFICATION.rst) * @summary Invalid purl * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InvalidPurlError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Invalid purl', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2010', status: 400, errorCode: 'SNYK-OSSI-2010', level: 'warn', instance, }, details, Object.assign({ links: [ 'https://github.com/package-url/purl-spec/blob/master/PURL-SPECIFICATION.rst', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.InvalidPurlError = InvalidPurlError; /** * @class * @name NamespaceNotProvidedError * @description You have requested a package type that requires a namespace (e.g. maven group id). Provide the namespace to retrieve the package. * * See more: * - [https://github.com/package-url/purl-spec/blob/master/PURL-SPECIFICATION.rst](https://github.com/package-url/purl-spec/blob/master/PURL-SPECIFICATION.rst) * @summary Namespace not specified * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class NamespaceNotProvidedError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Namespace not specified', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2011', status: 400, errorCode: 'SNYK-OSSI-2011', level: 'warn', instance, }, details, Object.assign({ links: [ 'https://github.com/package-url/purl-spec/blob/master/PURL-SPECIFICATION.rst', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.NamespaceNotProvidedError = NamespaceNotProvidedError; /** * @class * @name UnsupportedEcosystemError * @description The package type is not supported. Check the List issues for a package in Snyk API. * @summary Unsupported ecosystem * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnsupportedEcosystemError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unsupported ecosystem', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2020', status: 400, errorCode: 'SNYK-OSSI-2020', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnsupportedEcosystemError = UnsupportedEcosystemError; /** * @class * @name MissingComponentError * @description A list of components of the purl spec is required. The purl did not specify all the required components. * @summary Purl components required * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class MissingComponentError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Purl components required', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2021', status: 400, errorCode: 'SNYK-OSSI-2021', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.MissingComponentError = MissingComponentError; /** * @class * @name ComponentNotSupportedError * @description Remove the unsupported component and retry the request. * @summary Unsupported purl components * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class ComponentNotSupportedError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unsupported purl components', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2022', status: 400, errorCode: 'SNYK-OSSI-2022', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.ComponentNotSupportedError = ComponentNotSupportedError; /** * @class * @name UnsupportedGoVersionFormatError * @description Go pseudo version not supported. * @summary Go version format not supported * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnsupportedGoVersionFormatError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Go version format not supported', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2023', status: 400, errorCode: 'SNYK-OSSI-2023', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnsupportedGoVersionFormatError = UnsupportedGoVersionFormatError; /** * @class * @name PackageNotFoundError * @description The package you specified in the purl cannot be found in the vulnerability database. Check the package name, ecosystem, and version, then try again. * @summary Requested package not found * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class PackageNotFoundError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Requested package not found', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2030', status: 404, errorCode: 'SNYK-OSSI-2030', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.PackageNotFoundError = PackageNotFoundError; /** * @class * @name VulnerabilityServiceUnavailableError * @description This issue is unexpected, and the service will recover shortly. If the error still occurs, contact support. * @summary Vulnerability service not available * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class VulnerabilityServiceUnavailableError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Vulnerability service not available', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2031', status: 503, errorCode: 'SNYK-OSSI-2031', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.VulnerabilityServiceUnavailableError = VulnerabilityServiceUnavailableError; /** * @class * @name VulnDBInvalidResponseError * @description An unexpected error occurred. Please try again, and if you continue to experience issues please contact support. * @summary This issue is unexpected and the service should recover quickly if not please contact support * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class VulnDBInvalidResponseError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'This issue is unexpected and the service should recover quickly if not please contact support', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2032', status: 500, errorCode: 'SNYK-OSSI-2032', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.VulnDBInvalidResponseError = VulnDBInvalidResponseError; /** * @class * @name VulndbNextError * @description An unexpected error occurred with the vulnerability service. Please try again, and if you continue to experience issues please contact support. * @summary This issue is unexpected and the service should recover quickly if not please contact support * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class VulndbNextError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'This issue is unexpected and the service should recover quickly if not please contact support', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2033', status: 500, errorCode: 'SNYK-OSSI-2033', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.VulndbNextError = VulndbNextError; /** * @class * @name InternalServerError * @description This issue is unexpected, and the service will recover shortly. If the error still occurs, contact support. * @summary Request not processed due to unexpected error * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InternalServerError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Request not processed due to unexpected error', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2040', status: 500, errorCode: 'SNYK-OSSI-2040', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.InternalServerError = InternalServerError; /** * @class * @name InvalidPaginationParametersError * @description The pagination limit is > 1 and ≤ 1000, and the offset is ≥0. * @summary Invalid pagination parameters * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InvalidPaginationParametersError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Invalid pagination parameters', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2041', status: 400, errorCode: 'SNYK-OSSI-2041', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.InvalidPaginationParametersError = InvalidPaginationParametersError; /** * @class * @name TooManyPurlsError * @description The number of purls sent in the request exceeds the limit of 1000 set by the service. * @summary purls exceed limit * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class TooManyPurlsError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'purls exceed limit', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2042', status: 400, errorCode: 'SNYK-OSSI-2042', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.TooManyPurlsError = TooManyPurlsError; /** * @class * @name TooManyIssuesError * @description The number of issues found for the provided purls exceeds the limit defined by the API. Reduce the number of purls sent in a single request. * @summary Number of issues exceeds limit * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class TooManyIssuesError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Number of issues exceeds limit', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2043', status: 400, errorCode: 'SNYK-OSSI-2043', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.TooManyIssuesError = TooManyIssuesError; /** * @class * @name UndefinedContainerDistroError * @description The given Package URL does not have a required distro qualifier. * * See more: * - [https://docs.snyk.io/scan-containers/how-snyk-container-works/supported-operating-system-distributions#debian](https://docs.snyk.io/scan-containers/how-snyk-container-works/supported-operating-system-distributions#debian) * @summary Expected distro to be present * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UndefinedContainerDistroError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Expected distro to be present', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2044', status: 400, errorCode: 'SNYK-OSSI-2044', level: 'warn', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-containers/how-snyk-container-works/supported-operating-system-distributions#debian', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.UndefinedContainerDistroError = UndefinedContainerDistroError; /** * @class * @name UnsupportedDebianDistroError * @description This Debian distro is currently not supported. * @summary Unsupported Debian distro * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnsupportedDebianDistroError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unsupported Debian distro', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2045', status: 400, errorCode: 'SNYK-OSSI-2045', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnsupportedDebianDistroError = UnsupportedDebianDistroError; /** * @class * @name UndefinedContainerVendorError * @description The given Package URL does not have a required namespace. * @summary Expected namespace to be present * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UndefinedContainerVendorError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Expected namespace to be present', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2046', status: 400, errorCode: 'SNYK-OSSI-2046', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UndefinedContainerVendorError = UndefinedContainerVendorError; /** * @class * @name UnsupportedContainerVendorError * @description The given Package URL does not contain a supported vendor. * @summary Unsupported vendor * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnsupportedContainerVendorError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unsupported vendor', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2047', status: 400, errorCode: 'SNYK-OSSI-2047', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnsupportedContainerVendorError = UnsupportedContainerVendorError; //# sourceMappingURL=PurlVulnerabilityFetching-error-catalog.js.map /***/ }), /***/ 85831: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.InvalidDepGraphError = exports.EmptyRequestBodyError = exports.MissingAuthTokenError = exports.DepGraphResponseError = exports.UnsupportedProjectError = exports.IaCOrSASTProjectError = exports.UnexpectedParseDepGraphError = exports.UnexpectedDepGraphResponseError = exports.InternalServerError = void 0; const problem_error_1 = __webpack_require__(45280); /** * @class * @name InternalServerError * @description An unexpected error occurred during the SBOM generation. Review the request, then try again. If the error persists, contact Snyk Support. * @summary SBOM generation export server error * @category SbomExport * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InternalServerError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'SBOM generation export server error', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-9000', status: 500, errorCode: 'SNYK-OS-9000', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.InternalServerError = InternalServerError; /** * @class * @name UnexpectedDepGraphResponseError * @description An unexpected dependency graph error occurred. Review the request, then try again. If the error persists, contact Snyk Support. * @summary Dependency graph error * @category SbomExport * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnexpectedDepGraphResponseError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Dependency graph error', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-9001', status: 500, errorCode: 'SNYK-OS-9001', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnexpectedDepGraphResponseError = UnexpectedDepGraphResponseError; /** * @class * @name UnexpectedParseDepGraphError * @description The dependency graph cannot be parsed due to an unexpected error. Review the request, then try again. If the error persists, contact Snyk Support. * @summary Error parsing dependency graph * @category SbomExport * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnexpectedParseDepGraphError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Error parsing dependency graph', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-9002', status: 500, errorCode: 'SNYK-OS-9002', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnexpectedParseDepGraphError = UnexpectedParseDepGraphError; /** * @class * @name IaCOrSASTProjectError * @description Only SBOMs for Snyk Open Source or Snyk Container projects are supported. * @summary SBOM not supported due to project type * @category SbomExport * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class IaCOrSASTProjectError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'SBOM not supported due to project type', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-9003', status: 404, errorCode: 'SNYK-OS-9003', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.IaCOrSASTProjectError = IaCOrSASTProjectError; /** * @class * @name UnsupportedProjectError * @description Only SBOMs for open source projects are supported (Snyk Open Source). * @summary SBOM not supported * @category SbomExport * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnsupportedProjectError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'SBOM not supported', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-9004', status: 404, errorCode: 'SNYK-OS-9004', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnsupportedProjectError = UnsupportedProjectError; /** * @class * @name DepGraphResponseError * @description The server cannot process the request due to incomplete data. Review the request, then try again. * @summary Dependency graph request cannot be processed * @category SbomExport * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class DepGraphResponseError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Dependency graph request cannot be processed', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-9005', status: 404, errorCode: 'SNYK-OS-9005', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.DepGraphResponseError = DepGraphResponseError; /** * @class * @name MissingAuthTokenError * @description The API token is misconfigured or expired. Configure or generate the API token, then try again. * * See more: * - [https://docs.snyk.io/snyk-api-info/revoking-and-regenerating-snyk-api-tokens](https://docs.snyk.io/snyk-api-info/revoking-and-regenerating-snyk-api-tokens) * @summary Authorization failed due to missing API token * @category SbomExport * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class MissingAuthTokenError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Authorization failed due to missing API token', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-9006', status: 401, errorCode: 'SNYK-OS-9006', level: 'warn', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/snyk-api-info/revoking-and-regenerating-snyk-api-tokens', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.MissingAuthTokenError = MissingAuthTokenError; /** * @class * @name EmptyRequestBodyError * @description The body of the request is empty. Review the request, then try again. * @summary Client request cannot be processed * @category SbomExport * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class EmptyRequestBodyError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Client request cannot be processed', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-9007', status: 400, errorCode: 'SNYK-OS-9007', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.EmptyRequestBodyError = EmptyRequestBodyError; /** * @class * @name InvalidDepGraphError * @description The request cannot be processed due to an internal error. Review the request, then try again. * @summary Invalid dependency graph * @category SbomExport * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InvalidDepGraphError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Invalid dependency graph', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-9008', status: 400, errorCode: 'SNYK-OS-9008', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.InvalidDepGraphError = InvalidDepGraphError; //# sourceMappingURL=SbomExport-error-catalog.js.map /***/ }), /***/ 14769: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ServerError = exports.UnauthorisedError = exports.TimeoutError = exports.BadRequestError = exports.NotImplementedError = exports.TooManyRequestsError = void 0; const problem_error_1 = __webpack_require__(45280); /** * @class * @name TooManyRequestsError * @description The request rate limit has been exceeded. Wait a few minutes, then try again. * @summary Service temporarily throttled * @category Snyk * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class TooManyRequestsError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Service temporarily throttled', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-0001', status: 429, errorCode: 'SNYK-0001', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.TooManyRequestsError = TooManyRequestsError; /** * @class * @name NotImplementedError * @description The server doesn’t recognize the request method, or it cannot fulfill it. Review the request and try again. * * See more: * - [https://docs.snyk.io/snyk-api-info](https://docs.snyk.io/snyk-api-info) * @summary Server error response * @category Snyk * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class NotImplementedError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Server error response', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-0002', status: 501, errorCode: 'SNYK-0002', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/snyk-api-info', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.NotImplementedError = NotImplementedError; /** * @class * @name BadRequestError * @description The server cannot process the request due to a client error, such as malformed request syntax, size too large, invalid request message framing, or deceptive request routing. Review the request and try again. * @summary Client request cannot be processed * @category Snyk * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class BadRequestError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Client request cannot be processed', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-0003', status: 400, errorCode: 'SNYK-0003', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.BadRequestError = BadRequestError; /** * @class * @name TimeoutError * @description The server timed out during the request. Check Snyk status, then try again. * * See more: * - [https://status.snyk.io/](https://status.snyk.io/) * @summary Server communication error * @category Snyk * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class TimeoutError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Server communication error', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-0004', status: 504, errorCode: 'SNYK-0004', level: 'error', instance, }, details, Object.assign({ links: [ 'https://status.snyk.io/', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.TimeoutError = TimeoutError; /** * @class * @name UnauthorisedError * @description Authentication credentials not recognized, or user access is not provisioned. Revise credentials and try again, or request access from your Snyk administrator. * @summary Authentication error * @category Snyk * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnauthorisedError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Authentication error', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-0005', status: 401, errorCode: 'SNYK-0005', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnauthorisedError = UnauthorisedError; /** * @class * @name ServerError * @description The server cannot process the request due to an unexpected error. Check Snyk status, then try again. * * See more: * - [https://status.snyk.io/](https://status.snyk.io/) * @summary Request not fulfilled due to server error * @category Snyk * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class ServerError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Request not fulfilled due to server error ', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-9999', status: 500, errorCode: 'SNYK-9999', level: 'error', instance, }, details, Object.assign({ links: [ 'https://status.snyk.io/', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.ServerError = ServerError; //# sourceMappingURL=Snyk-error-catalog.js.map /***/ }), /***/ 42863: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Fix = exports.SbomExport = exports.OpenSourceUnmanaged = exports.OpenAPI = exports.IsolatedBuilds = exports.PurlVulnerabilityFetching = exports.OpenSourceProjectIssues = exports.OpenSourceProjectSnapshots = exports.OpenSourceEcosystems = exports.Snyk = void 0; exports.Snyk = __webpack_require__(14769); exports.OpenSourceEcosystems = __webpack_require__(45244); exports.OpenSourceProjectSnapshots = __webpack_require__(45996); exports.OpenSourceProjectIssues = __webpack_require__(5410); exports.PurlVulnerabilityFetching = __webpack_require__(18549); exports.IsolatedBuilds = __webpack_require__(97142); exports.OpenAPI = __webpack_require__(16942); exports.OpenSourceUnmanaged = __webpack_require__(41017); exports.SbomExport = __webpack_require__(85831); exports.Fix = __webpack_require__(82608); //# sourceMappingURL=error-catalog.js.map /***/ }), /***/ 52424: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CompositeError = void 0; const types_1 = __webpack_require__(92090); class CompositeError extends Error { constructor(errors) { super('CompositeError'); this.errors = errors; } /** * Convert this CompositeError to JsonApi. * If the error was created with 'instance' metadata then that will be used by default for all errors. * @param instance string the instance to use for the errors in this CompositeError. Overrides 'instance' metadata * @returns JsonApi a JsonApi object representing this CompositeError */ toJsonApi(instance) { const payload = { jsonapi: { version: '1.0', }, errors: this.errors.map((error) => error.toJsonApiErrorObject(instance)), }; return new types_1.JsonApi(payload); } } exports.CompositeError = CompositeError; //# sourceMappingURL=composite-error.js.map /***/ }), /***/ 46171: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __webpack_require__(40737); tslib_1.__exportStar(__webpack_require__(45280), exports); tslib_1.__exportStar(__webpack_require__(42863), exports); tslib_1.__exportStar(__webpack_require__(52424), exports); //# sourceMappingURL=index.js.map /***/ }), /***/ 45280: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProblemError = void 0; const types_1 = __webpack_require__(92090); const uuid_1 = __webpack_require__(70077); const util_1 = __webpack_require__(74064); class ProblemError extends Error { constructor(metadata, detail, additionalData, cause) { super(metadata.title); this.metadata = metadata; this.detail = detail; this.additionalData = additionalData; this.cause = cause; // Since `instanceof` cannot be relied upon for class checks in situations where the `ProblemError` was thrown from a dependency of the executing app, we need a more viable solution. // See: https://stackoverflow.com/questions/41587865/using-instanceof-on-objects-created-with-constructors-from-deep-npm-dependenci/41592087#41592087 this.isErrorCatalogError = true; if (additionalData && additionalData['overrideErrorId']) { this.id = additionalData['overrideErrorId']; } else { this.id = (0, uuid_1.v4)(); } } format(instance, formatType) { switch (formatType) { case types_1.ErrorFormats.JsonApi: return this.toJsonApi(instance); case types_1.ErrorFormats.ProblemJson: return this.toProblemJson(instance); default: throw new Error('invalid format type'); } } toProblemJson(instance) { const payload = Object.assign({ type: this.metadata.type, title: this.metadata.title, status: this.metadata.status, errorCode: this.metadata.errorCode, detail: this.detail, instance }, this.additionalData); return new types_1.ProblemJson(payload); } /** * Convert this ProblemError to a JsonApiErrorObject. * If the error was created with 'instance' metadata then that will be used by default. * @param instance string the instance to use for this error. Overrides 'instance' metadata * @returns JsonApiErrorObject a JsonApiErrorObject representing this ProblemError */ toJsonApiErrorObject(instance) { let source; // Get the instance from either the member or the parameter const theinstance = instance || this.metadata.instance; if (typeof theinstance === 'string') { source = (0, util_1.instanceToJsonApiSource)(theinstance); } const jsonApiErrorObject = { id: this.id, links: { about: this.metadata.type, }, status: String(this.metadata.status), code: this.metadata.errorCode, title: this.metadata.title, detail: this.detail, meta: Object.assign({}, this.additionalData), }; if (source) { jsonApiErrorObject.source = source; } return jsonApiErrorObject; } toJsonApi(instance) { const payload = { jsonapi: { version: '1.0', }, errors: [this.toJsonApiErrorObject(instance)], }; return new types_1.JsonApi(payload); } } exports.ProblemError = ProblemError; //# sourceMappingURL=problem-error.js.map /***/ }), /***/ 92090: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JsonApi = exports.ProblemJson = exports.ErrorFormats = void 0; var ErrorFormats; (function (ErrorFormats) { ErrorFormats[ErrorFormats["JsonApi"] = 0] = "JsonApi"; ErrorFormats[ErrorFormats["ProblemJson"] = 1] = "ProblemJson"; })(ErrorFormats || (exports.ErrorFormats = ErrorFormats = {})); class ProblemJson { constructor(payload) { this.payload = payload; } headers() { return { 'Content-Type': 'application/problem+json;', }; } body() { return this.payload; } } exports.ProblemJson = ProblemJson; class JsonApi { constructor(payload) { this.payload = payload; } headers() { return {}; } body() { return this.payload; } } exports.JsonApi = JsonApi; //# sourceMappingURL=types.js.map /***/ }), /***/ 74064: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __webpack_require__(40737); tslib_1.__exportStar(__webpack_require__(18363), exports); //# sourceMappingURL=index.js.map /***/ }), /***/ 18363: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.instanceToJsonApiSource = void 0; const SOURCE_REGEXP = /^\/(query|params|body|headers)\/.*/; /** * Converts the instance string from an error into a JsonApiErrorSource * @param instance the instance string to convert * @returns A JsonApiErrorSource if appropriate, or undefined if not */ const instanceToJsonApiSource = (instance) => { let source; // See if the instance conforms to one of the source formats const matchErrorPath = instance.match(SOURCE_REGEXP); // If the match captures the path type and parameter, if (matchErrorPath !== null && matchErrorPath.length > 0) { // Convert the instance into a source switch (matchErrorPath[1]) { case 'query': case 'params': source = paramsInstanceToJsonApiSource(instance); break; case 'body': source = bodyInstanceToJsonApiSource(instance); break; case 'headers': source = headerInstanceToJsonApiSource(instance); break; } } return source; }; exports.instanceToJsonApiSource = instanceToJsonApiSource; // For a parameter, do not include the leading slash const PARAMETER_REGEXP = /^\/(?:params|query)\/(.*)/; const paramsInstanceToJsonApiSource = (instance) => { let parameter = ''; // The source is the name of the parameter, and is not a json path const matches = instance.match(PARAMETER_REGEXP); if (matches !== null && matches.length > 0) { parameter = matches[1]; } return { parameter, }; }; // For a pointer, capture the JSON path, including the leading slash const POINTER_REGEXP = /^\/body(\/.*)/; const bodyInstanceToJsonApiSource = (instance) => { let pointer = ''; const matches = instance.match(POINTER_REGEXP); if (matches !== null && matches.length > 0) { pointer = matches[1]; } return { pointer, }; }; // The source is the name of the header, and is not a json path const HEADER_REGEXP = /^\/headers\/(.*)/; const headerInstanceToJsonApiSource = (instance) => { let header = ''; const matches = instance.match(HEADER_REGEXP); if (matches !== null && matches.length > 0) { header = matches[1]; } return { header, }; }; //# sourceMappingURL=json-api.js.map /***/ }), /***/ 55352: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /* eslint-disable @typescript-eslint/strict-boolean-expressions */ function parse(string, encoding, opts) { var _opts$out; if (opts === void 0) { opts = {}; } // Build the character lookup table: if (!encoding.codes) { encoding.codes = {}; for (var i = 0; i < encoding.chars.length; ++i) { encoding.codes[encoding.chars[i]] = i; } } // The string must have a whole number of bytes: if (!opts.loose && string.length * encoding.bits & 7) { throw new SyntaxError('Invalid padding'); } // Count the padding bytes: var end = string.length; while (string[end - 1] === '=') { --end; // If we get a whole number of bytes, there is too much padding: if (!opts.loose && !((string.length - end) * encoding.bits & 7)) { throw new SyntaxError('Invalid padding'); } } // Allocate the output: var out = new ((_opts$out = opts.out) != null ? _opts$out : Uint8Array)(end * encoding.bits / 8 | 0); // Parse the data: var bits = 0; // Number of bits currently in the buffer var buffer = 0; // Bits waiting to be written out, MSB first var written = 0; // Next byte to write for (var _i = 0; _i < end; ++_i) { // Read one character from the string: var value = encoding.codes[string[_i]]; if (value === undefined) { throw new SyntaxError('Invalid character ' + string[_i]); } // Append the bits to the buffer: buffer = buffer << encoding.bits | value; bits += encoding.bits; // Write out some bits if the buffer has a byte's worth: if (bits >= 8) { bits -= 8; out[written++] = 0xff & buffer >> bits; } } // Verify that we have received just enough bits: if (bits >= encoding.bits || 0xff & buffer << 8 - bits) { throw new SyntaxError('Unexpected end of data'); } return out; } function stringify(data, encoding, opts) { if (opts === void 0) { opts = {}; } var _opts = opts, _opts$pad = _opts.pad, pad = _opts$pad === void 0 ? true : _opts$pad; var mask = (1 << encoding.bits) - 1; var out = ''; var bits = 0; // Number of bits currently in the buffer var buffer = 0; // Bits waiting to be written out, MSB first for (var i = 0; i < data.length; ++i) { // Slurp data into the buffer: buffer = buffer << 8 | 0xff & data[i]; bits += 8; // Write out as much as we can: while (bits > encoding.bits) { bits -= encoding.bits; out += encoding.chars[mask & buffer >> bits]; } } // Partial character: if (bits) { out += encoding.chars[mask & buffer << encoding.bits - bits]; } // Add padding characters until we hit a byte boundary: if (pad) { while (out.length * encoding.bits & 7) { out += '='; } } return out; } /* eslint-disable @typescript-eslint/strict-boolean-expressions */ var base16Encoding = { chars: '0123456789ABCDEF', bits: 4 }; var base32Encoding = { chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567', bits: 5 }; var base32HexEncoding = { chars: '0123456789ABCDEFGHIJKLMNOPQRSTUV', bits: 5 }; var base64Encoding = { chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', bits: 6 }; var base64UrlEncoding = { chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_', bits: 6 }; var base16 = { parse: function parse$1(string, opts) { return parse(string.toUpperCase(), base16Encoding, opts); }, stringify: function stringify$1(data, opts) { return stringify(data, base16Encoding, opts); } }; var base32 = { parse: function parse$1(string, opts) { if (opts === void 0) { opts = {}; } return parse(opts.loose ? string.toUpperCase().replace(/0/g, 'O').replace(/1/g, 'L').replace(/8/g, 'B') : string, base32Encoding, opts); }, stringify: function stringify$1(data, opts) { return stringify(data, base32Encoding, opts); } }; var base32hex = { parse: function parse$1(string, opts) { return parse(string, base32HexEncoding, opts); }, stringify: function stringify$1(data, opts) { return stringify(data, base32HexEncoding, opts); } }; var base64 = { parse: function parse$1(string, opts) { return parse(string, base64Encoding, opts); }, stringify: function stringify$1(data, opts) { return stringify(data, base64Encoding, opts); } }; var base64url = { parse: function parse$1(string, opts) { return parse(string, base64UrlEncoding, opts); }, stringify: function stringify$1(data, opts) { return stringify(data, base64UrlEncoding, opts); } }; var codec = { parse: parse, stringify: stringify }; exports.base16 = base16; exports.base32 = base32; exports.base32hex = base32hex; exports.base64 = base64; exports.base64url = base64url; exports.codec = codec; /***/ }), /***/ 79114: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var os = __webpack_require__(22037); var process = __webpack_require__(77282); var fs = __webpack_require__(57147); var path = __webpack_require__(71017); var which = __webpack_require__(53267); function _interopNamespaceDefault(e) { var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); } n.default = e; return Object.freeze(n); } var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs); var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path); /** * @overview Provides functionality related to working with executables. * @license MPL-2.0 */ /** * Resolves the location of an executable given an arbitrary valid string * representation of that executable. * * To obtain the location of the executable this function (if necessary): * - Expands the provided string to a absolute path. * - Follows symbolic links. * * @param {object} args The arguments for this function. * @param {string} args.executable A string representation of the executable. * @param {object} deps The dependencies for this function. * @param {Function} deps.exists A function to check if a file exists. * @param {Function} deps.readlink A function to resolve (sym)links. * @param {Function} deps.which A function to perform a `which(1)`-like lookup. * @returns {string} The full path to the binary of the executable. * @throws {Error} If the `deps` aren't provided. */ function resolveExecutable({ executable }, { exists, readlink, which }) { if (readlink === undefined || which === undefined) { throw new Error(); } try { executable = which(executable); } catch (_) { // For backwards compatibility return the executable even if its location // cannot be obtained return executable; } if (!exists(executable)) { // For backwards compatibility return the executable even if there exists no // file at the specified path return executable; } try { executable = readlink(executable); } catch (_) { // An error will be thrown if the executable is not a (sym)link, this is not // a problem so the error is ignored } return executable; } /** * @overview Provides an API to consistently escape or quote shell arguments * across platforms. * @license MPL-2.0 */ /** * The error message for incorrect parameter types. * * @constant * @type {string} */ const typeError = "Shescape requires strings or values that can be converted into a string using .toString()"; /** * The `typeof` value of functions. * * @constant * @type {string} */ const typeofFunction = "function"; /** * The `typeof` value of strings. * * @constant * @type {string} */ const typeofString = "string"; /** * Checks if a value is a string. * * @param {any} value The value of interest. * @returns {boolean} `true` if `value` is a string, `false` otherwise. */ function isString(value) { return typeof value === typeofString; } /** * Checks if a value can be converted into a string. * * @param {any} value The value of interest. * @returns {boolean} `true` if `value` is stringable, `false` otherwise. */ function isStringable(value) { if (value === undefined || value === null) { return false; } if (typeof value.toString !== typeofFunction) { return false; } const str = value.toString(); return isString(str); } /** * Merges any number of objects into a single object. * * Note: the values of objects appearing later in the list of arguments take * precedence when merging. * * @param {...object} objects The objects to merge. * @returns {object} The merged object. */ function mergeObjects(...objects) { const baseObject = Object.create(null); const mergedObjects = Object.assign(baseObject, ...objects); return mergedObjects; } /** * Parses arguments provided to {@link escapeShellArg} or {@link quoteShellArg}. * * @param {object} args The arguments for this function. * @param {string} args.arg The argument to escape. * @param {object} args.options The options for escaping `arg`. * @param {string} [args.options.shell] The shell to escape `arg` for. * @param {boolean} [args.options.interpolation] Is interpolation enabled. * @param {boolean} [args.options.quoted] Is `arg` being quoted. * @param {object} args.process The `process` values. * @param {object} args.process.env The environment variables. * @param {object} deps The dependencies for this function. * @param {Function} deps.getDefaultShell Get the default shell for the system. * @param {Function} deps.getShellName Get the name of a shell. * @returns {object} The parsed arguments. */ function parseArgs( { arg, options: { interpolation, quoted, shell }, process: { env } }, { getDefaultShell, getShellName } ) { interpolation = interpolation ? true : false; shell = isString(shell) ? shell : getDefaultShell({ env }); const shellName = getShellName({ shell }, { resolveExecutable }); return { arg, interpolation, quoted, shellName }; } /** * Escapes an argument for the given shell. * * @param {object} args The arguments for this function. * @param {string} args.arg The argument to escape. * @param {boolean} args.interpolation Is interpolation enabled. * @param {boolean} args.quoted Is `arg` being quoted. * @param {string} args.shellName The name of the shell to escape `arg` for. * @param {object} deps The dependencies for this function. * @param {Function} deps.getEscapeFunction Get the escape function for a shell. * @returns {string} The escaped argument. * @throws {TypeError} The argument to escape is not stringable. */ function escape$1( { arg, interpolation, quoted, shellName }, { getEscapeFunction } ) { if (!isStringable(arg)) { throw new TypeError(typeError); } const argAsString = arg.toString(); const escape = getEscapeFunction(shellName); const escapedArg = escape(argAsString, interpolation, quoted); return escapedArg; } /** * Quotes and escape an argument for the given shell. * * @param {object} args The arguments for this function. * @param {string} args.arg The argument to escape. * @param {string} args.shellName The name of the shell to escape `arg` for. * @param {object} deps The dependencies for this function. * @param {Function} deps.getEscapeFunction Get the escape function for a shell. * @param {Function} deps.getQuoteFunction Get the quote function for a shell. * @returns {string} The quoted and escaped argument. * @throws {TypeError} The argument to escape is not stringable. */ function quote$1({ arg, shellName }, { getEscapeFunction, getQuoteFunction }) { const escapedArg = escape$1( { arg, interpolation: false, quoted: true, shellName }, { getEscapeFunction } ); const quote = getQuoteFunction(shellName); const escapedAndQuotedArg = quote(escapedArg); return escapedAndQuotedArg; } /** * Escapes an argument for the given shell. * * @param {object} args The arguments for this function. * @param {string} args.arg The argument to escape. * @param {object} args.options The options for escaping `arg`. * @param {object} args.process The `process` values. * @param {object} deps The dependencies for this function. * @param {Function} deps.getDefaultShell Get the default shell for the system. * @param {Function} deps.getEscapeFunction Get an escape function for a shell. * @param {Function} deps.getShellName Get the name of a shell. * @returns {string} The escaped argument. */ function escapeShellArg({ arg, options, process }, deps) { options = mergeObjects(options, { quoted: false }); const escapeArgs = parseArgs({ arg, options, process }, deps); return escape$1(escapeArgs, deps); } /** * Quotes and escape an argument for the given shell. * * @param {object} args The arguments for this function. * @param {string} args.arg The argument to escape. * @param {object} args.options The options for escaping `arg`. * @param {string} [args.options.shell] The shell to escape `arg` for. * @param {object} args.process The `process` values. * @param {object} args.process.env The environment variables. * @param {object} deps The dependencies for this function. * @param {Function} deps.getDefaultShell Get the default shell for the system. * @param {Function} deps.getEscapeFunction Get an escape function for a shell. * @param {Function} deps.getQuoteFunction Get a quote function for a shell. * @param {Function} deps.getShellName Get the name of a shell. * @returns {string} The quoted and escaped argument. */ function quoteShellArg(args, deps) { const quoteArgs = parseArgs(args, deps); return quote$1(quoteArgs, deps); } /** * @overview Provides functionality specifically for Unix systems. * @license MPL-2.0 */ /** * The name of the Bourne-again shell (Bash) binary. * * @constant * @type {string} */ const binBash = "bash"; /** * The name of the Debian Almquist shell (Dash) binary. * * @constant * @type {string} */ const binDash = "dash"; /** * The name of the Z shell (Zsh) binary. * * @constant * @type {string} */ const binZsh = "zsh"; /** * Escapes a shell argument for use in Bash(-like shells). * * @param {string} arg The argument to escape. * @param {boolean} interpolation Is interpolation enabled. * @param {boolean} quoted Is `arg` being quoted. * @returns {string} The escaped argument. */ function escapeArgBash(arg, interpolation, quoted) { let result = arg.replace(/[\0\u0008\u001B\u009B]/gu, ""); if (interpolation) { result = result .replace(/\\/gu, "\\\\") .replace(/\n/gu, " ") .replace(/(^|\s)([#~])/gu, "$1\\$2") .replace(/(["$&'()*;<>?`{|])/gu, "\\$1") .replace(/(?<=[:=])(~)(?=[\s+\-/0:=]|$)/gu, "\\$1"); } else if (quoted) { result = result.replace(/'/gu, `'\\''`); } result = result.replace(/\r(?!\n)/gu, ""); return result; } /** * Escapes a shell argument for use in Dash. * * @param {string} arg The argument to escape. * @param {boolean} interpolation Is interpolation enabled. * @param {boolean} quoted Is `arg` being quoted. * @returns {string} The escaped argument. */ function escapeArgDash(arg, interpolation, quoted) { let result = arg.replace(/[\0\u0008\u001B\u009B]/gu, ""); if (interpolation) { result = result .replace(/\\/gu, "\\\\") .replace(/\n/gu, " ") .replace(/(^|\s)([#~])/gu, "$1\\$2") .replace(/(["$&'()*;<>?`|])/gu, "\\$1"); } else if (quoted) { result = result.replace(/'/gu, `'\\''`); } result = result.replace(/\r(?!\n)/gu, ""); return result; } /** * Escapes a shell argument for use in Zsh. * * @param {string} arg The argument to escape. * @param {boolean} interpolation Is interpolation enabled. * @param {boolean} quoted Is `arg` being quoted. * @returns {string} The escaped argument. */ function escapeArgZsh(arg, interpolation, quoted) { let result = arg.replace(/[\0\u0008\u001B\u009B]/gu, ""); if (interpolation) { result = result .replace(/\\/gu, "\\\\") .replace(/\n/gu, " ") .replace(/(^|\s)([#=~])/gu, "$1\\$2") .replace(/(["$&'()*;<>?[\]`{|}])/gu, "\\$1"); } else if (quoted) { result = result.replace(/'/gu, `'\\''`); } result = result.replace(/\r(?!\n)/gu, ""); return result; } /** * Quotes an argument for use in a Unix shell. * * @param {string} arg The argument to quote. * @returns {string} The quoted argument. */ function quoteArg$1(arg) { return `'${arg}'`; } /** * Returns the basename of a directory or file path on a Unix system. * * @param {string} fullPath A Unix-style directory or file path. * @returns {string} The basename of `fullPath`. */ function getBasename$1(fullPath) { return path__namespace.basename(fullPath); } /** * Returns the default shell for Unix systems. * * For more information, see `options.shell` in: * https://nodejs.org/api/child_process.html#child_processexeccommand-options-callback. * * @returns {string} The default shell. */ function getDefaultShell$1() { return "/bin/sh"; } /** * Returns a function to escape arguments for use in a particular shell. * * @param {string} shellName The name of a Unix shell. * @returns {Function?} A function to escape arguments for use in the shell. */ function getEscapeFunction$1(shellName) { switch (shellName) { case binBash: return escapeArgBash; case binDash: return escapeArgDash; case binZsh: return escapeArgZsh; default: return null; } } /** * Returns a function to quote arguments for use in a particular shell. * * @param {string} shellName The name of a Unix shell. * @returns {Function?} A function to quote arguments for use in the shell. */ function getQuoteFunction$1(shellName) { switch (shellName) { case binBash: case binDash: case binZsh: return quoteArg$1; default: return null; } } /** * Determines the name of the shell identified by a file path or file name. * * @param {object} args The arguments for this function. * @param {string} args.shell The name or path of the shell. * @param {object} deps The dependencies for this function. * @param {Function} deps.resolveExecutable Resolve the path to an executable. * @returns {string} The shell name. */ function getShellName$1({ shell }, { resolveExecutable }) { shell = resolveExecutable( { executable: shell }, { exists: fs__namespace.existsSync, readlink: fs__namespace.readlinkSync, which: which.sync } ); const shellName = getBasename$1(shell); if (getEscapeFunction$1(shellName) === null) { return binBash; } return shellName; } var unix = /*#__PURE__*/Object.freeze({ __proto__: null, getDefaultShell: getDefaultShell$1, getEscapeFunction: getEscapeFunction$1, getQuoteFunction: getQuoteFunction$1, getShellName: getShellName$1 }); /** * @overview Provides functionality specifically for Windows systems. * @license MPL-2.0 */ /** * The name of the Windows Command Prompt binary. * * @constant * @type {string} */ const binCmd = "cmd.exe"; /** * The name of the Windows PowerShell binary. * * @constant * @type {string} */ const binPowerShell = "powershell.exe"; /** * Escapes a shell argument for use in Windows Command Prompt. * * @param {string} arg The argument to escape. * @param {boolean} interpolation Is interpolation enabled. * @param {boolean} quoted Is `arg` being quoted. * @returns {string} The escaped argument. */ function escapeArgCmd(arg, interpolation, quoted) { let result = arg .replace(/[\0\u0008\u001B\u009B]/gu, "") .replace(/\r?\n|\r/gu, " "); if (interpolation) { result = result.replace(/\^/gu, "^^").replace(/(["&<>|])/gu, "^$1"); } else if (quoted) { result = result.replace(/"/gu, `""`); } return result; } /** * Escapes a shell argument for use in Windows PowerShell. * * @param {string} arg The argument to escape. * @param {boolean} interpolation Is interpolation enabled. * @param {boolean} quoted Is `arg` being quoted. * @returns {string} The escaped argument. */ function escapeArgPowerShell(arg, interpolation, quoted) { let result = arg .replace(/[\0\u0008\u001B\u009B]/gu, "") .replace(/`/gu, "``") .replace(/\$/gu, "`$$") .replace(/\r(?!\n)/gu, ""); if (interpolation) { result = result .replace(/\r?\n|\r/gu, " ") .replace(/(^|[\s\u0085])([*1-6]?)(>)/gu, "$1$2`$3") .replace(/(^|[\s\u0085])([#\-:<@\]])/gu, "$1`$2") .replace(/(["&'(),;{|}‘’‚‛“”„])/gu, "`$1"); } else if (quoted) { result = result.replace(/(["“”„])/gu, "$1$1"); } return result; } /** * Quotes an argument for use in a Windows shell. * * @param {string} arg The argument to quote. * @returns {string} The quoted argument. */ function quoteArg(arg) { return `"${arg}"`; } /** * Returns the basename of a directory or file path on a Windows system. * * @param {string} fullPath A Windows-style directory or file path. * @returns {string} The basename of `fullPath`. */ function getBasename(fullPath) { return path__namespace.win32.basename(fullPath); } /** * Returns the default shell for Windows systems. * * For more information, see: * https://nodejs.org/api/child_process.html#default-windows-shell. * * @param {object} args The arguments for this function. * @param {object} args.env The environment variables. * @param {string} [args.env.ComSpec] The %COMSPEC% value. * @returns {string} The default shell. */ function getDefaultShell({ env: { ComSpec } }) { if (ComSpec !== undefined) { return ComSpec; } return binCmd; } /** * Returns a function to escape arguments for use in a particular shell. * * @param {string} shellName The name of a Windows shell. * @returns {Function?} A function to escape arguments for use in the shell. */ function getEscapeFunction(shellName) { switch (shellName) { case binCmd: return escapeArgCmd; case binPowerShell: return escapeArgPowerShell; default: return null; } } /** * Returns a function to quote arguments for use in a particular shell. * * @param {string} shellName The name of a Windows shell. * @returns {Function?} A function to quote arguments for use in the shell. */ function getQuoteFunction(shellName) { switch (shellName) { case binCmd: case binPowerShell: return quoteArg; default: return null; } } /** * Determines the name of the shell identified by a file path or file name. * * @param {object} args The arguments for this function. * @param {string} args.shell The name or path of the shell. * @param {object} deps The dependencies for this function. * @param {Function} deps.resolveExecutable Resolve the path to an executable. * @returns {string} The shell name. */ function getShellName({ shell }, { resolveExecutable }) { shell = resolveExecutable( { executable: shell }, { exists: fs__namespace.existsSync, readlink: fs__namespace.readlinkSync, which: which.sync } ); const shellName = getBasename(shell); if (getEscapeFunction(shellName) === null) { return binCmd; } return shellName; } var win = /*#__PURE__*/Object.freeze({ __proto__: null, getDefaultShell: getDefaultShell, getEscapeFunction: getEscapeFunction, getQuoteFunction: getQuoteFunction, getShellName: getShellName }); /** * @overview Provides functionality related to getting the platform module for * the current system. * @license MPL-2.0 */ /** * The string identifying the OS type Cygwin. * * @constant * @type {string} */ const cygwin = "cygwin"; /** * The string identifying the OS type MSYS. * * @constant * @type {string} */ const msys = "msys"; /** * The string identifying Windows platforms. * * @constant * @type {string} */ const win32 = "win32"; /** * Checks if the current system is a Windows system. * * @param {object} args The arguments for this function. * @param {Object} args.env The environment variables. * @param {string} args.platform The `os.platform()` value. * @returns {boolean} `true` if the system is Windows, `false` otherwise. */ function isWindow({ env, platform }) { return env.OSTYPE === cygwin || env.OSTYPE === msys || platform === win32; } /** * Returns all helper functions for a specific system. * * @param {object} args The arguments for this function. * @param {Object} args.env The environment variables. * @param {string} args.platform The `os.platform()` value. * @returns {object} The helper functions for the current system. */ function getHelpersByPlatform(args) { if (isWindow(args)) { return win; } return unix; } /** * A simple shell escape package. Use it to escape user-controlled inputs to * shell commands to prevent shell injection. * * @example * import cp from "child_process"; * import * as shescape from "shescape"; * cp.spawn("command", shescape.escapeAll(userInput), options); * @overview Entrypoint for the package. * @module shescape * @version 1.6.1 * @license MPL-2.0 */ /** * Get the helper functions for the current platform. * * @returns {object} The helper functions for the current platform. */ function getPlatformHelpers() { const platform = os.platform(); const helpers = getHelpersByPlatform({ env: process.env, platform }); return helpers; } /** * Converts the provided value into an array if it is not already an array and * returns the array. * * @param {Array | any} x The value to convert to an array if necessary. * @returns {Array} An array containing `x` or `x` itself. */ function toArrayIfNecessary(x) { return Array.isArray(x) ? x : [x]; } /** * Take a single value, the argument, and escape any dangerous characters. * * Non-string inputs will be converted to strings using a `toString()` method. * * @param {string} arg The argument to escape. * @param {object} [options] The escape options. * @param {boolean} [options.interpolation=false] Is interpolation enabled. * @param {boolean | string} [options.shell] The shell to escape for. * @returns {string} The escaped argument. * @throws {TypeError} The argument is not stringable. * @since 0.1.0 */ function escape(arg, options = {}) { const helpers = getPlatformHelpers(); return escapeShellArg({ arg, options, process }, helpers); } /** * Take a array of values, the arguments, and escape any dangerous characters in * every argument. * * Non-array inputs will be converted to one-value arrays and non-string values * will be converted to strings using a `toString()` method. * * @param {string[]} args The arguments to escape. * @param {object} [options] The escape options. * @param {boolean} [options.interpolation=false] Is interpolation enabled. * @param {boolean | string} [options.shell] The shell to escape for. * @returns {string[]} The escaped arguments. * @throws {TypeError} One of the arguments is not stringable. * @since 1.1.0 */ function escapeAll(args, options = {}) { args = toArrayIfNecessary(args); return args.map((arg) => escape(arg, options)); } /** * Take a single value, the argument, put OS-specific quotes around it and * escape any dangerous characters. * * Non-string inputs will be converted to strings using a `toString()` method. * * @param {string} arg The argument to quote and escape. * @param {object} [options] The escape and quote options. * @param {boolean | string} [options.shell] The shell to escape for. * @returns {string} The quoted and escaped argument. * @throws {TypeError} The argument is not stringable. * @since 0.3.0 */ function quote(arg, options = {}) { const helpers = getPlatformHelpers(); return quoteShellArg({ arg, options, process }, helpers); } /** * Take an array of values, the arguments, put OS-specific quotes around every * argument and escape any dangerous characters in every argument. * * Non-array inputs will be converted to one-value arrays and non-string values * will be converted to strings using a `toString()` method. * * @param {string[]} args The arguments to quote and escape. * @param {object} [options] The escape and quote options. * @param {boolean | string} [options.shell] The shell to escape for. * @returns {string[]} The quoted and escaped arguments. * @throws {TypeError} One of the arguments is not stringable. * @since 0.4.0 */ function quoteAll(args, options = {}) { args = toArrayIfNecessary(args); return args.map((arg) => quote(arg, options)); } exports.escape = escape; exports.escapeAll = escapeAll; exports.quote = quote; exports.quoteAll = quoteAll; /***/ }), /***/ 66710: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var os = __webpack_require__(22037); var process = __webpack_require__(77282); var fs = __webpack_require__(57147); var path = __webpack_require__(71017); var which = __webpack_require__(81918); var util = __webpack_require__(73837); function _interopNamespaceDefault(e) { var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); } n.default = e; return Object.freeze(n); } var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs); var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path); /** * @overview Provides functionality related to working with executables. * @license MPL-2.0 */ /** * Resolves the location of an executable given an arbitrary valid string * representation of that executable. * * To obtain the location of the executable this function (if necessary): * - Expands the provided string to an absolute path. * - Follows symbolic links. * * @param {object} args The arguments for this function. * @param {object} args.env The environment variables. * @param {string} args.executable A string representation of the executable. * @param {object} deps The dependencies for this function. * @param {Function} deps.exists A function to check if a file exists. * @param {Function} deps.readlink A function to resolve (sym)links. * @param {Function} deps.which A function to perform a `which(1)`-like lookup. * @returns {string} The full path to the binary of the executable. */ function resolveExecutable( { env, executable }, { exists, readlink, which }, ) { try { executable = which(executable, { path: env.PATH || env.Path }); } catch (_) { // For backwards compatibility return the executable even if its location // cannot be obtained return executable; } if (!exists(executable)) { // For backwards compatibility return the executable even if there exists no // file at the specified path return executable; } try { executable = readlink(executable); } catch (_) { // An error will be thrown if the executable is not a (sym)link, this is not // a problem so the error is ignored } return executable; } /** * @overview Provides reflection functionality. * @license MPL-2.0 */ /** * The error message for incorrect parameter types. * * @constant * @type {string} */ const typeError = "Shescape requires strings or values that can be converted into a string using .toString()"; /** * The `typeof` value of functions. * * @constant * @type {string} */ const typeofFunction = "function"; /** * The `typeof` value of strings. * * @constant * @type {string} */ const typeofString = "string"; /** * Checks if a value can be converted into a string and converts it if possible. * * @param {any} value The value of interest. * @returns {string | null} If possible the string of `value`, otherwise `null`. */ function maybeToString(value) { if (value === undefined || value === null) { return null; } if (typeof value.toString !== typeofFunction) { return null; } const maybeStr = value.toString(); if (isString(maybeStr)) { return maybeStr; } else { return null; } } /** * Convert a value into a string if that is possible. * * @param {any} value The value to convert into a string. * @returns {string} The `value` as a string. * @throws {TypeError} The `value` is not stringable. */ function checkedToString(value) { if (isString(value)) { return value; } const maybeStr = maybeToString(value); if (maybeStr === null) { throw new TypeError(typeError); } return maybeStr; } /** * Checks if a value is a string. * * @param {any} value The value of interest. * @returns {boolean} `true` if `value` is a string, `false` otherwise. */ function isString(value) { return typeof value === typeofString; } /** * Converts the provided value into an array if it is not already an array and * returns the array. * * @param {Array | any} value The value to convert to an array if necessary. * @returns {Array} An array containing `value` or `value` itself. */ function toArrayIfNecessary(value) { return Array.isArray(value) ? value : [value]; } /** * @overview Provides functionality for parsing shescape options. * @license MPL-2.0 */ /** * Parses options provided to shescape. * * @param {object} args The arguments for this function. * @param {object} args.env The environment variables. * @param {object} args.options The options for escaping. * @param {boolean} [args.options.flagProtection] Is flag protection enabled. * @param {boolean} [args.options.interpolation] Is interpolation enabled. * @param {boolean | string} [args.options.shell] The shell to escape for. * @param {object} deps The dependencies for this function. * @param {Function} deps.getDefaultShell Function to get the default shell. * @param {Function} deps.getShellName Function to get the name of a shell. * @returns {object} The parsed arguments. */ function parseOptions( { env, options: { flagProtection, interpolation, shell } }, { getDefaultShell, getShellName }, ) { flagProtection = flagProtection ? true : false; interpolation = interpolation ? true : false; shell = isString(shell) ? shell : getDefaultShell({ env }); const shellName = getShellName({ env, shell }, { resolveExecutable }); return { flagProtection, interpolation, shellName }; } /** * @overview Provides functionality for the Bourne-again shell (Bash). * @license MPL-2.0 */ /** * Escape an argument for use in Bash when interpolation is active. * * @param {string} arg The argument to escape. * @returns {string} The escaped argument. */ function escapeArgForInterpolation$5(arg) { return arg .replace(/[\0\u0008\r\u001B\u009B]/gu, "") .replace(/\n/gu, " ") .replace(/\\/gu, "\\\\") .replace(/(?<=^|\s)([#~])/gu, "\\$1") .replace(/(["$&'()*;<>?`{|])/gu, "\\$1") .replace(/(?<=[:=])(~)(?=[\s+\-/0:=]|$)/gu, "\\$1") .replace(/([\t ])/gu, "\\$1"); } /** * Escape an argument for use in Bash when the argument is not being quoted (but * interpolation is inactive). * * @param {string} arg The argument to escape. * @returns {string} The escaped argument. */ function escapeArgForNoInterpolation$5(arg) { return arg.replace(/[\0\u0008\u001B\u009B]/gu, "").replace(/\r(?!\n)/gu, ""); } /** * Returns a function to escape arguments for use in Bash for the given use * case. * * @param {object} options The options for escaping arguments. * @param {boolean} options.interpolation Is interpolation enabled. * @returns {Function} A function to escape arguments. */ function getEscapeFunction$7(options) { if (options.interpolation) { return escapeArgForInterpolation$5; } else { return escapeArgForNoInterpolation$5; } } /** * Escape an argument for use in Bash when the argument is being quoted. * * @param {string} arg The argument to escape. * @returns {string} The escaped argument. */ function escapeArgForQuoted$5(arg) { return arg .replace(/[\0\u0008\u001B\u009B]/gu, "") .replace(/\r(?!\n)/gu, "") .replace(/'/gu, "'\\''"); } /** * Quotes an argument for use in Bash. * * @param {string} arg The argument to quote. * @returns {string} The quoted argument. */ function quoteArg$5(arg) { return `'${arg}'`; } /** * Returns a pair of functions to escape and quote arguments for use in Bash. * * @returns {Function[]} A function pair to escape & quote arguments. */ function getQuoteFunction$7() { return [escapeArgForQuoted$5, quoteArg$5]; } /** * Remove any prefix from the provided argument that might be interpreted as a * flag on Unix systems for Bash. * * @param {string} arg The argument to update. * @returns {string} The updated argument. */ function stripFlagPrefix$5(arg) { return arg.replace(/^-+/gu, ""); } /** * Returns a function to protect against flag injection for Bash. * * @returns {Function} A function to protect against flag injection. */ function getFlagProtectionFunction$7() { return stripFlagPrefix$5; } /** * @overview Provides functionality for the C shell (csh). * @license MPL-2.0 */ /** * Escape an argument for use in csh when interpolation is active. * * @param {string} arg The argument to escape. * @returns {string} The escaped argument. */ function escapeArgForInterpolation$4(arg) { const textEncoder = new util.TextEncoder(); return arg .replace(/[\0\u0008\r\u001B\u009B]/gu, "") .replace(/\n/gu, " ") .replace(/\\/gu, "\\\\") .replace(/(?<=^|\s)(~)/gu, "\\$1") .replace(/!(?!$)/gu, "\\!") .replace(/(["#$&'()*;<>?[`{|])/gu, "\\$1") .replace(/([\t ])/gu, "\\$1") .split("") .map( // Due to a bug in C shell version 20110502-7, when a character whose // utf-8 encoding includes the bytes 0xA0 (160 in decimal) appears in // an argument after an escaped character, it will hang and endlessly // consume memory unless the character is escaped with quotes. // ref: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=995013 (char) => (textEncoder.encode(char).includes(160) ? `'${char}'` : char), ) .join(""); } /** * Escape an argument for use in csh when the argument is not being quoted (but * interpolation is inactive). * * @param {string} arg The argument to escape. * @returns {string} The escaped argument. */ function escapeArgForNoInterpolation$4(arg) { return arg .replace(/[\0\u0008\r\u001B\u009B]/gu, "") .replace(/\n/gu, " ") .replace(/\\!$/gu, "\\\\!") .replace(/!(?!$)/gu, "\\!"); } /** * Returns a function to escape arguments for use in csh for the given use case. * * @param {object} options The options for escaping arguments. * @param {boolean} options.interpolation Is interpolation enabled. * @returns {Function} A function to escape arguments. */ function getEscapeFunction$6(options) { if (options.interpolation) { return escapeArgForInterpolation$4; } else { return escapeArgForNoInterpolation$4; } } /** * Escape an argument for use in csh when the argument is being quoted. * * @param {string} arg The argument to escape. * @returns {string} The escaped argument. */ function escapeArgForQuoted$4(arg) { return arg .replace(/[\0\u0008\r\u001B\u009B]/gu, "") .replace(/\n/gu, " ") .replace(/'/gu, "'\\''") .replace(/\\!$/gu, "\\\\!") .replace(/!(?!$)/gu, "\\!"); } /** * Quotes an argument for use in csh. * * @param {string} arg The argument to quote. * @returns {string} The quoted argument. */ function quoteArg$4(arg) { return `'${arg}'`; } /** * Returns a pair of functions to escape and quote arguments for use in csh. * * @returns {Function[]} A function pair to escape & quote arguments. */ function getQuoteFunction$6() { return [escapeArgForQuoted$4, quoteArg$4]; } /** * Remove any prefix from the provided argument that might be interpreted as a * flag on Unix systems for csh. * * @param {string} arg The argument to update. * @returns {string} The updated argument. */ function stripFlagPrefix$4(arg) { return arg.replace(/^-+/gu, ""); } /** * Returns a function to protect against flag injection for csh. * * @returns {Function} A function to protect against flag injection. */ function getFlagProtectionFunction$6() { return stripFlagPrefix$4; } /** * @overview Provides functionality for the Debian Almquist shell (Dash). * @license MPL-2.0 */ /** * Escape an argument for use in Dash when interpolation is active. * * @param {string} arg The argument to escape. * @returns {string} The escaped argument. */ function escapeArgForInterpolation$3(arg) { return arg .replace(/[\0\u0008\r\u001B\u009B]/gu, "") .replace(/\n/gu, " ") .replace(/\\/gu, "\\\\") .replace(/(?<=^|\s)([#~])/gu, "\\$1") .replace(/(["$&'()*;<>?`|])/gu, "\\$1") .replace(/([\t ])/gu, "\\$1"); } /** * Escape an argument for use in Dash when the argument is not being quoted (but * interpolation is inactive). * * @param {string} arg The argument to escape. * @returns {string} The escaped argument. */ function escapeArgForNoInterpolation$3(arg) { return arg.replace(/[\0\u0008\u001B\u009B]/gu, "").replace(/\r(?!\n)/gu, ""); } /** * Returns a function to escape arguments for use in Dash for the given use * case. * * @param {object} options The options for escaping arguments. * @param {boolean} options.interpolation Is interpolation enabled. * @returns {Function} A function to escape arguments. */ function getEscapeFunction$5(options) { if (options.interpolation) { return escapeArgForInterpolation$3; } else { return escapeArgForNoInterpolation$3; } } /** * Escape an argument for use in Dash when the argument is being quoted. * * @param {string} arg The argument to escape. * @returns {string} The escaped argument. */ function escapeArgForQuoted$3(arg) { return arg .replace(/[\0\u0008\u001B\u009B]/gu, "") .replace(/\r(?!\n)/gu, "") .replace(/'/gu, "'\\''"); } /** * Quotes an argument for use in Dash. * * @param {string} arg The argument to quote. * @returns {string} The quoted argument. */ function quoteArg$3(arg) { return `'${arg}'`; } /** * Returns a pair of functions to escape and quote arguments for use in Dash. * * @returns {Function[]} A function pair to escape & quote arguments. */ function getQuoteFunction$5() { return [escapeArgForQuoted$3, quoteArg$3]; } /** * Remove any prefix from the provided argument that might be interpreted as a * flag on Unix systems for Dash. * * @param {string} arg The argument to update. * @returns {string} The updated argument. */ function stripFlagPrefix$3(arg) { return arg.replace(/^-+/gu, ""); } /** * Returns a function to protect against flag injection for Dash. * * @returns {Function} A function to protect against flag injection. */ function getFlagProtectionFunction$5() { return stripFlagPrefix$3; } /** * @overview Provides functionality for the Z shell (Zsh). * @license MPL-2.0 */ /** * Escape an argument for use in Zsh when interpolation is active. * * @param {string} arg The argument to escape. * @returns {string} The escaped argument. */ function escapeArgForInterpolation$2(arg) { return arg .replace(/[\0\u0008\r\u001B\u009B]/gu, "") .replace(/\n/gu, " ") .replace(/\\/gu, "\\\\") .replace(/(?<=^|\s)([#=~])/gu, "\\$1") .replace(/(["$&'()*;<>?[\]`{|}])/gu, "\\$1") .replace(/([\t ])/gu, "\\$1"); } /** * Escape an argument for use in Zsh when the argument is not being quoted (but * interpolation is inactive). * * @param {string} arg The argument to escape. * @returns {string} The escaped argument. */ function escapeArgForNoInterpolation$2(arg) { return arg.replace(/[\0\u0008\u001B\u009B]/gu, "").replace(/\r(?!\n)/gu, ""); } /** * Returns a function to escape arguments for use in Zsh for the given use case. * * @param {object} options The options for escaping arguments. * @param {boolean} options.interpolation Is interpolation enabled. * @returns {Function} A function to escape arguments. */ function getEscapeFunction$4(options) { if (options.interpolation) { return escapeArgForInterpolation$2; } else { return escapeArgForNoInterpolation$2; } } /** * Escape an argument for use in Zsh when the argument is being quoted. * * @param {string} arg The argument to escape. * @returns {string} The escaped argument. */ function escapeArgForQuoted$2(arg) { return arg .replace(/[\0\u0008\u001B\u009B]/gu, "") .replace(/\r(?!\n)/gu, "") .replace(/'/gu, "'\\''"); } /** * Quotes an argument for use in Zsh. * * @param {string} arg The argument to quote. * @returns {string} The quoted argument. */ function quoteArg$2(arg) { return `'${arg}'`; } /** * Returns a pair of functions to escape and quote arguments for use in Zsh. * * @returns {Function[]} A function pair to escape & quote arguments. */ function getQuoteFunction$4() { return [escapeArgForQuoted$2, quoteArg$2]; } /** * Remove any prefix from the provided argument that might be interpreted as a * flag on Unix systems for Zsh. * * @param {string} arg The argument to update. * @returns {string} The updated argument. */ function stripFlagPrefix$2(arg) { return arg.replace(/^-+/gu, ""); } /** * Returns a function to protect against flag injection for Zsh. * * @returns {Function} A function to protect against flag injection. */ function getFlagProtectionFunction$4() { return stripFlagPrefix$2; } /** * @overview Provides functionality for Unix systems. * @license MPL-2.0 */ /** * The name of the Bourne-again shell (Bash) binary. * * @constant * @type {string} */ const binBash = "bash"; /** * The name of the C shell (csh) binary. * * @constant * @type {string} */ const binCsh = "csh"; /** * The name of the Debian Almquist shell (Dash) binary. * * @constant * @type {string} */ const binDash = "dash"; /** * The name of the Z shell (Zsh) binary. * * @constant * @type {string} */ const binZsh = "zsh"; /** * Returns the default shell for Unix systems. * * For more information, see `options.shell` in: * https://nodejs.org/api/child_process.html#child_processexeccommand-options-callback. * * @returns {string} The default shell. */ function getDefaultShell$1() { return "/bin/sh"; } /** * Returns a function to escape arguments for use in a particular shell. * * @param {string} shellName The name of a Unix shell. * @param {object} options The options for escaping arguments. * @param {boolean} options.interpolation Is interpolation enabled. * @returns {Function | undefined} A function to escape arguments. */ function getEscapeFunction$3(shellName, options) { switch (shellName) { case binBash: return getEscapeFunction$7(options); case binCsh: return getEscapeFunction$6(options); case binDash: return getEscapeFunction$5(options); case binZsh: return getEscapeFunction$4(options); } } /** * Returns a pair of functions to escape and quote arguments for use in a * particular shell. * * @param {string} shellName The name of a Unix shell. * @returns {Function[] | undefined} A function pair to escape & quote arguments. */ function getQuoteFunction$3(shellName) { switch (shellName) { case binBash: return getQuoteFunction$7(); case binCsh: return getQuoteFunction$6(); case binDash: return getQuoteFunction$5(); case binZsh: return getQuoteFunction$4(); } } /** * Returns a function to protect against flag injection. * * @param {string} shellName The name of a Unix shell. * @returns {Function | undefined} A function to protect against flag injection. */ function getFlagProtectionFunction$3(shellName) { switch (shellName) { case binBash: return getFlagProtectionFunction$7(); case binCsh: return getFlagProtectionFunction$6(); case binDash: return getFlagProtectionFunction$5(); case binZsh: return getFlagProtectionFunction$4(); } } /** * Determines the name of the shell identified by a file path or file name. * * @param {object} args The arguments for this function. * @param {object} args.env The environment variables. * @param {string} args.shell The name or path of the shell. * @param {object} deps The dependencies for this function. * @param {Function} deps.resolveExecutable Resolve the path to an executable. * @returns {string} The shell name. */ function getShellName$1({ env, shell }, { resolveExecutable }) { shell = resolveExecutable( { env, executable: shell }, { exists: fs__namespace.existsSync, readlink: fs__namespace.readlinkSync, which: which.sync }, ); const shellName = path__namespace.basename(shell); if (getEscapeFunction$3(shellName, {}) === undefined) { return binBash; } return shellName; } var unix = /*#__PURE__*/Object.freeze({ __proto__: null, getDefaultShell: getDefaultShell$1, getEscapeFunction: getEscapeFunction$3, getFlagProtectionFunction: getFlagProtectionFunction$3, getQuoteFunction: getQuoteFunction$3, getShellName: getShellName$1 }); /** * @overview Provides functionality for the Windows Command Prompt. * @license MPL-2.0 */ /** * Escape an argument for use in CMD when interpolation is active. * * @param {string} arg The argument to escape. * @returns {string} The escaped argument. */ function escapeArgForInterpolation$1(arg) { let shouldEscapeSpecialChar = true; return arg .replace(/[\0\u0008\r\u001B\u009B]/gu, "") .replace(/\n/gu, " ") .replace(/(? { if (char === '"') { shouldEscapeSpecialChar = !shouldEscapeSpecialChar; } else if (shouldEscapeSpecialChar && /[%&<>^|]/u.test(char)) { return `^${char}`; } return char; }, ) .join(""); } /** * Escape an argument for use in CMD when the argument is not being quoted (but * interpolation is inactive). * * @param {string} arg The argument to escape. * @returns {string} The escaped argument. */ function escapeArgForNoInterpolation$1(arg) { return arg.replace(/[\0\u0008\r\u001B\u009B]/gu, "").replace(/\n/gu, " "); } /** * Returns a function to escape arguments for use in CMD for the given use case. * * @param {object} options The options for escaping arguments. * @param {boolean} options.interpolation Is interpolation enabled. * @returns {Function} A function to escape arguments. */ function getEscapeFunction$2(options) { if (options.interpolation) { return escapeArgForInterpolation$1; } else { return escapeArgForNoInterpolation$1; } } /** * Escape an argument for use in CMD when the argument is being quoted. * * @param {string} arg The argument to escape. * @returns {string} The escaped argument. */ function escapeArgForQuoted$1(arg) { return escapeArgForInterpolation$1(arg).replace( /(?)/gu, "$1`$2") .replace(/(?<=^|[\s\u0085])([#\-:<@\]])/gu, "`$1") .replace(/([$&'(),;{|}‘’‚‛“”„])/gu, "`$1"); if (/[\s\u0085]/u.test(arg.replace(/^[\s\u0085]+/gu, ""))) { arg = arg .replace(/(?} args.env The environment variables. * @param {string} args.platform The `os.platform()` value. * @returns {boolean} `true` if the system is Windows, `false` otherwise. */ function isWindow({ env, platform }) { return env.OSTYPE === cygwin || env.OSTYPE === msys || platform === win32; } /** * Returns all helper functions for a specific system. * * @param {object} args The arguments for this function. * @param {Object} args.env The environment variables. * @param {string} args.platform The `os.platform()` value. * @returns {object} The helper functions for the current system. */ function getHelpersByPlatform({ env, platform }) { if (isWindow({ env, platform })) { return win; } return unix; } /** * A simple shell escape library. Use it to escape user-controlled inputs to * shell commands to prevent shell injection. * * @overview Entrypoint for the library. * @module shescape * @version 1.7.4 * @license MPL-2.0 */ /** * Get the helper functions for the current platform. * * @returns {object} The helper functions for the current platform. */ function getPlatformHelpers() { const platform = os.platform(); const helpers = getHelpersByPlatform({ env: process.env, platform }); return helpers; } /** * Take a single value, the argument, and escape any dangerous characters. * * Non-string inputs will be converted to strings using a `toString()` method. * * NOTE: when the `interpolation` option is set to `true`, whitespace is escaped * to prevent argument splitting except for cmd.exe (which does not support it). * * @example * import { spawn } from "node:child_process"; * spawn( * "echo", * ["Hello", shescape.escape(userInput)], * null // `options.shell` MUST be falsy * ); * @param {string} arg The argument to escape. * @param {object} [options] The escape options. * @param {boolean} [options.flagProtection=false] Is flag protection enabled. * @param {boolean} [options.interpolation=false] Is interpolation enabled. * @param {boolean | string} [options.shell] The shell to escape for. * @returns {string} The escaped argument. * @throws {TypeError} The argument is not stringable. * @since 0.1.0 */ function escape(arg, options = {}) { const helpers = getPlatformHelpers(); const { flagProtection, interpolation, shellName } = parseOptions( { env: process.env, options }, helpers, ); const argAsString = checkedToString(arg); const escape = helpers.getEscapeFunction(shellName, { interpolation }); const escapedArg = escape(argAsString); if (flagProtection) { const flagProtect = helpers.getFlagProtectionFunction(shellName); return flagProtect(escapedArg); } else { return escapedArg; } } /** * Take an array of values, the arguments, and escape any dangerous characters * in every argument. * * Non-array inputs will be converted to one-value arrays and non-string values * will be converted to strings using a `toString()` method. * * @example * import { spawn } from "node:child_process"; * spawn( * "echo", * shescape.escapeAll(["Hello", userInput]), * null // `options.shell` MUST be falsy * ); * @param {string[]} args The arguments to escape. * @param {object} [options] The escape options. * @param {boolean} [options.flagProtection=false] Is flag protection enabled. * @param {boolean} [options.interpolation=false] Is interpolation enabled. * @param {boolean | string} [options.shell] The shell to escape for. * @returns {string[]} The escaped arguments. * @throws {TypeError} One of the arguments is not stringable. * @since 1.1.0 */ function escapeAll(args, options = {}) { args = toArrayIfNecessary(args); return args.map((arg) => escape(arg, options)); } /** * Take a single value, the argument, put shell-specific quotes around it and * escape any dangerous characters. * * Non-string inputs will be converted to strings using a `toString()` method. * * @example * import { spawn } from "node:child_process"; * const spawnOptions = { shell: true }; // `options.shell` SHOULD be truthy * const shescapeOptions = { shell: spawnOptions.shell }; * spawn( * "echo", * ["Hello", shescape.quote(userInput, shescapeOptions)], * spawnOptions * ); * @example * import { exec } from "node:child_process"; * const execOptions = null || { }; * const shescapeOptions = { shell: execOptions.shell }; * exec( * `echo Hello ${shescape.quote(userInput, shescapeOptions)}`, * execOptions * ); * @param {string} arg The argument to quote and escape. * @param {object} [options] The escape and quote options. * @param {boolean} [options.flagProtection=false] Is flag protection enabled. * @param {boolean | string} [options.shell] The shell to escape for. * @returns {string} The quoted and escaped argument. * @throws {TypeError} The argument is not stringable. * @since 0.3.0 */ function quote(arg, options = {}) { const helpers = getPlatformHelpers(); const { flagProtection, shellName } = parseOptions( { env: process.env, options }, helpers, ); const argAsString = checkedToString(arg); const [escape, quote] = helpers.getQuoteFunction(shellName); const escapedArg = escape(argAsString); if (flagProtection) { const flagProtect = helpers.getFlagProtectionFunction(shellName); return quote(flagProtect(escapedArg)); } else { return quote(escapedArg); } } /** * Take an array of values, the arguments, put shell-specific quotes around * every argument and escape any dangerous characters in every argument. * * Non-array inputs will be converted to one-value arrays and non-string values * will be converted to strings using a `toString()` method. * * @example * import { spawn } from "node:child_process"; * const spawnOptions = { shell: true }; // `options.shell` SHOULD be truthy * const shescapeOptions = { shell: spawnOptions.shell }; * spawn( * "echo", * shescape.quoteAll(["Hello", userInput], shescapeOptions), * spawnOptions * ); * @param {string[]} args The arguments to quote and escape. * @param {object} [options] The escape and quote options. * @param {boolean} [options.flagProtection=false] Is flag protection enabled. * @param {boolean | string} [options.shell] The shell to escape for. * @returns {string[]} The quoted and escaped arguments. * @throws {TypeError} One of the arguments is not stringable. * @since 0.4.0 */ function quoteAll(args, options = {}) { args = toArrayIfNecessary(args); return args.map((arg) => quote(arg, options)); } exports.escape = escape; exports.escapeAll = escapeAll; exports.quote = quote; exports.quoteAll = quoteAll; /***/ }), /***/ 5717: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PRTemplateInvalidPayloadError = exports.FailedToDeletePRTemplateError = exports.FailedToReadPRTemplateError = exports.FailedToCreatePRTemplateError = exports.FailedToGenerateHashError = exports.FailedToLoadCompiledYamlError = exports.FailedToParsePullRequestAttributesError = exports.FailedToCompilePrTemplateError = exports.PullRequestTemplateNotFoundError = exports.FailedToGetPullRequestAttributesError = void 0; const problem_error_1 = __webpack_require__(66255); /** * @class * @name FailedToGetPullRequestAttributesError * @description Snyk could not get the custom pull request template attributes, using the given variables and the fetched pr template. * * See more: * - [https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta](https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta) * @summary Failed to get pull request attributes * @category Fix * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class FailedToGetPullRequestAttributesError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Failed to get pull request attributes', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-pr-template-0001', status: 500, errorCode: 'SNYK-PR-TEMPLATE-0001', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.FailedToGetPullRequestAttributesError = FailedToGetPullRequestAttributesError; /** * @class * @name PullRequestTemplateNotFoundError * @description Could not find pull request template. * @summary Not found * @category Fix * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class PullRequestTemplateNotFoundError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Not found', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-pr-template-0002', status: 404, errorCode: 'SNYK-PR-TEMPLATE-0002', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.PullRequestTemplateNotFoundError = PullRequestTemplateNotFoundError; /** * @class * @name FailedToCompilePrTemplateError * @description Could not compile your customize pull request template, using Handlebars compilation and Snyk variables in place. * * See more: * - [https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta](https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta) * @summary Failed to compile pull request template * @category Fix * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class FailedToCompilePrTemplateError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Failed to compile pull request template', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-pr-template-0003', status: 400, errorCode: 'SNYK-PR-TEMPLATE-0003', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.FailedToCompilePrTemplateError = FailedToCompilePrTemplateError; /** * @class * @name FailedToParsePullRequestAttributesError * @description Snyk could not parse the custom pull request template, using the given variables and assigning them to the fetched pr template. * * See more: * - [https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta](https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta) * @summary Failed to parse pull request attributes * @category Fix * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class FailedToParsePullRequestAttributesError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Failed to parse pull request attributes', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-pr-template-0004', status: 500, errorCode: 'SNYK-PR-TEMPLATE-0004', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.FailedToParsePullRequestAttributesError = FailedToParsePullRequestAttributesError; /** * @class * @name FailedToLoadCompiledYamlError * @description Could not load YAML file after substituting Snyk variables into the custom PR template. * * See more: * - [https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta](https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta) * @summary Failed to load YAML file after substituting Snyk variables * @category Fix * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class FailedToLoadCompiledYamlError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Failed to load YAML file after substituting Snyk variables', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-pr-template-0005', status: 400, errorCode: 'SNYK-PR-TEMPLATE-0005', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.FailedToLoadCompiledYamlError = FailedToLoadCompiledYamlError; /** * @class * @name FailedToGenerateHashError * @description Snyk could not generate hash using the customer PR files and projects vulnIds. * * See more: * - [https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta](https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta) * @summary Failed to generate hash for custom PR template * @category Fix * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class FailedToGenerateHashError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Failed to generate hash for custom PR template', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-pr-template-0006', status: 500, errorCode: 'SNYK-PR-TEMPLATE-0006', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.FailedToGenerateHashError = FailedToGenerateHashError; /** * @class * @name FailedToCreatePRTemplateError * @description Snyk could not create pull request template. * * See more: * - [https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta](https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta) * @summary Unable to create pull request template * @category Fix * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class FailedToCreatePRTemplateError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unable to create pull request template', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-pr-template-0007', status: 500, errorCode: 'SNYK-PR-TEMPLATE-0007', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.FailedToCreatePRTemplateError = FailedToCreatePRTemplateError; /** * @class * @name FailedToReadPRTemplateError * @description Snyk could not get pull request template. * * See more: * - [https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta](https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta) * @summary Unable to get pull request template * @category Fix * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class FailedToReadPRTemplateError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unable to get pull request template', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-pr-template-0008', status: 500, errorCode: 'SNYK-PR-TEMPLATE-0008', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.FailedToReadPRTemplateError = FailedToReadPRTemplateError; /** * @class * @name FailedToDeletePRTemplateError * @description Snyk could not delete pull request template. * * See more: * - [https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta](https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta) * @summary Unable to delete pull request template * @category Fix * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class FailedToDeletePRTemplateError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unable to delete pull request template', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-pr-template-0009', status: 500, errorCode: 'SNYK-PR-TEMPLATE-0009', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-application-code/snyk-open-source/open-source-basics/customize-pr-templates-closed-beta', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.FailedToDeletePRTemplateError = FailedToDeletePRTemplateError; /** * @class * @name PRTemplateInvalidPayloadError * @description The pull request template payload is invalid. * @summary Invalid payload * @category Fix * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class PRTemplateInvalidPayloadError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Invalid payload', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-pr-template-0010', status: 400, errorCode: 'SNYK-PR-TEMPLATE-0010', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.PRTemplateInvalidPayloadError = PRTemplateInvalidPayloadError; //# sourceMappingURL=Fix-error-catalog.js.map /***/ }), /***/ 47270: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UnsupportedEcosystemError = exports.BuildEnvironmentNotFoundError = exports.InvalidRequestError = void 0; const problem_error_1 = __webpack_require__(66255); /** * @class * @name InvalidRequestError * @description The provided request payload is not valid for the selected ecosystem. Please review the API documentation. * * See more: * - [https://apidocs.snyk.io/](https://apidocs.snyk.io/) * @summary Invalid request * @category IsolatedBuilds * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InvalidRequestError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Invalid request', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-8001', status: 400, errorCode: 'SNYK-OS-8001', level: 'error', instance, }, details, Object.assign({ links: [ 'https://apidocs.snyk.io/', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.InvalidRequestError = InvalidRequestError; /** * @class * @name BuildEnvironmentNotFoundError * @description The build environment for the provided context could not be found. Please ensure you have created the build environment first. * @summary Build environment not found * @category IsolatedBuilds * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class BuildEnvironmentNotFoundError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Build environment not found', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-8002', status: 404, errorCode: 'SNYK-OS-8002', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.BuildEnvironmentNotFoundError = BuildEnvironmentNotFoundError; /** * @class * @name UnsupportedEcosystemError * @description The language or package manager is not supported. * * See more: * - [https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/supported-languages-frameworks-and-feature-availability-overview#open-source-and-licensing-snyk-open-source](https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/supported-languages-frameworks-and-feature-availability-overview#open-source-and-licensing-snyk-open-source) * @summary Unsupported Ecosystem * @category IsolatedBuilds * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnsupportedEcosystemError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unsupported Ecosystem', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-8003', status: 400, errorCode: 'SNYK-OS-8003', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/supported-languages-frameworks-and-feature-availability-overview#open-source-and-licensing-snyk-open-source', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnsupportedEcosystemError = UnsupportedEcosystemError; //# sourceMappingURL=IsolatedBuilds-error-catalog.js.map /***/ }), /***/ 62699: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UnsupportedMediaTypeError = exports.UnauthorizedError = exports.RequestEntityTooLargeError = exports.MethodNotAllowedError = exports.NotFoundError = exports.NotAcceptableError = exports.ForbiddenError = exports.BadRequestError = void 0; const problem_error_1 = __webpack_require__(66255); /** * @class * @name BadRequestError * @description The server cannot process the request due to invalid or corrupt data. Review the request, then try again. * * See more: * - [https://docs.snyk.io/snyk-api-info/getting-started-using-snyk-rest-api ](https://docs.snyk.io/snyk-api-info/getting-started-using-snyk-rest-api ) * @summary Bad request * @category OpenAPI * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class BadRequestError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Bad request', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-openapi-0001', status: 400, errorCode: 'SNYK-OPENAPI-0001', level: 'warn', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/snyk-api-info/getting-started-using-snyk-rest-api ', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.BadRequestError = BadRequestError; /** * @class * @name ForbiddenError * @description Access to the requested resource is forbidden. * @summary Forbidden * @category OpenAPI * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class ForbiddenError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Forbidden', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-openapi-0002', status: 403, errorCode: 'SNYK-OPENAPI-0002', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.ForbiddenError = ForbiddenError; /** * @class * @name NotAcceptableError * @description The server cannot provide a response that matches the provided accept headers. Review the request, then try again. * @summary Not acceptable * @category OpenAPI * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class NotAcceptableError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Not acceptable', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-openapi-0003', status: 406, errorCode: 'SNYK-OPENAPI-0003', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.NotAcceptableError = NotAcceptableError; /** * @class * @name NotFoundError * @description The server cannot find the requested resource. * @summary Not found * @category OpenAPI * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class NotFoundError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Not found', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-openapi-0004', status: 404, errorCode: 'SNYK-OPENAPI-0004', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.NotFoundError = NotFoundError; /** * @class * @name MethodNotAllowedError * @description The target endpoint does not support your request method. Review the request, then try again. * @summary Method not allowed * @category OpenAPI * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class MethodNotAllowedError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Method not allowed', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-openapi-0005', status: 405, errorCode: 'SNYK-OPENAPI-0005', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.MethodNotAllowedError = MethodNotAllowedError; /** * @class * @name RequestEntityTooLargeError * @description The request entity exceeds server limitations. * @summary Request entity too large * @category OpenAPI * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class RequestEntityTooLargeError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Request entity too large', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-openapi-0006', status: 413, errorCode: 'SNYK-OPENAPI-0006', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.RequestEntityTooLargeError = RequestEntityTooLargeError; /** * @class * @name UnauthorizedError * @description The request lacks authentication credentials for the requested resource. * * See more: * - [https://docs.snyk.io/snyk-api-info/authentication-for-api ](https://docs.snyk.io/snyk-api-info/authentication-for-api ) * @summary Unauthorized * @category OpenAPI * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnauthorizedError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unauthorized', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-openapi-0007', status: 401, errorCode: 'SNYK-OPENAPI-0007', level: 'warn', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/snyk-api-info/authentication-for-api ', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnauthorizedError = UnauthorizedError; /** * @class * @name UnsupportedMediaTypeError * @description The media format of the request is not supported. * @summary Unsupported media type * @category OpenAPI * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnsupportedMediaTypeError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unsupported media type', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-openapi-0008', status: 415, errorCode: 'SNYK-OPENAPI-0008', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnsupportedMediaTypeError = UnsupportedMediaTypeError; //# sourceMappingURL=OpenAPI-error-catalog.js.map /***/ }), /***/ 50890: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UnsupportedRequirementsFileError = exports.InvalidConfigurationError = exports.MissingSupportedFileError = exports.Base64DecodeError = exports.Base64EncodeError = exports.CouldNotParseJSONFileError = exports.NoDependencyUpdatesError = exports.NoValidPackageUpgradesError = exports.ChildProcessExecutionError = exports.NoResultsFromForkerProcessesError = exports.UnknownBlobEncodingOnGithubError = exports.BadNPMVersionError = exports.UnableToReplaceBrokerURLError = exports.CouldNotFindBrokerURLError = exports.CouldNotParseNPMRegistryURLError = exports.NoRepoFoundForTheNPMPackageError = exports.TimeoutWhenProcessingTheDepTreeError = exports.SourceNotSupportedError = exports.NoReleasedVersionForVersionsRangeError = exports.CannotCreateGitHostError = exports.CannotGetBuildFileFromRepoError = exports.CannotResolveTargetPomFromRepoError = exports.CannotResolveTargetPomFromXmlError = exports.MissingProjectFromPomError = exports.PomFileNotFoundError = exports.SkippedGroupError = exports.InvalidCoordinatesError = exports.UnableToParseXMLError = exports.CyclicPropertyDetectedInPomFileError = exports.UnableToResolveVersionForPropertyError = exports.UnableToResolveValueForPropertyError = exports.MissingRequirementFromPomError = exports.UnsupportedExternalFileGenerationSCMError = exports.InconsistentVendoringError = exports.IncompleteProjectError = exports.SsoReAuthRequiredError = exports.GoModFileMissingError = exports.PrivateModuleError = exports.PublishFailedError = exports.MissingStaticMainFunctionError = exports.UnsupportedTargetFrameworkError = exports.UnsupportedManifestFileError = exports.MissingEnvironmentVariableError = exports.CannotGetFileFromSourceError = exports.UnprocessableFileError = exports.MissingPayloadError = exports.MissingHeaderError = exports.UnknownDependencyVersionError = exports.UnparseableLockFileError = exports.UnparseableManifestError = void 0; exports.FailedToApplyDependencyUpdatesError = exports.TooManyManifestFilesError = void 0; const problem_error_1 = __webpack_require__(66255); /** * @class * @name UnparseableManifestError * @description The provided manifest file could not be parsed as it has invalid syntax or does not match the expected schema. Review the manifest file, then try again. * @summary Unable to parse manifest file * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnparseableManifestError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unable to parse manifest file', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-0001', status: 400, errorCode: 'SNYK-OS-0001', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnparseableManifestError = UnparseableManifestError; /** * @class * @name UnparseableLockFileError * @description The provided lock file could not be parsed as it has invalid syntax or does not match the expected schema. Review the lock file, then try again. * @summary Unable to parse lock file * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnparseableLockFileError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unable to parse lock file', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-0002', status: 400, errorCode: 'SNYK-OS-0002', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnparseableLockFileError = UnparseableLockFileError; /** * @class * @name UnknownDependencyVersionError * @description Dependency version could not be resolved. * * See more: * - [https://support.snyk.io/hc/en-us/articles/360001373178-Could-not-determine-version-for-dependencies](https://support.snyk.io/hc/en-us/articles/360001373178-Could-not-determine-version-for-dependencies) * @summary Unknown dependency version * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnknownDependencyVersionError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unknown dependency version', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-0003', status: 404, errorCode: 'SNYK-OS-0003', level: 'warn', instance, }, details, Object.assign({ links: [ 'https://support.snyk.io/hc/en-us/articles/360001373178-Could-not-determine-version-for-dependencies', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnknownDependencyVersionError = UnknownDependencyVersionError; /** * @class * @name MissingHeaderError * @description The server encountered a request that is missing a mandatory request header. * @summary Missing required request header * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class MissingHeaderError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Missing required request header', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-0004', status: 422, errorCode: 'SNYK-OS-0004', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.MissingHeaderError = MissingHeaderError; /** * @class * @name MissingPayloadError * @description The server could not process the request. * @summary Payload missing required elements * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class MissingPayloadError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Payload missing required elements', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-0005', status: 422, errorCode: 'SNYK-OS-0005', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.MissingPayloadError = MissingPayloadError; /** * @class * @name UnprocessableFileError * @description The dependency service could not process the files. * @summary Files cannot be processed * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnprocessableFileError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Files cannot be processed', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-0006', status: 422, errorCode: 'SNYK-OS-0006', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnprocessableFileError = UnprocessableFileError; /** * @class * @name CannotGetFileFromSourceError * @description Could not get the file from the source URL. * @summary Cannot get file from source * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class CannotGetFileFromSourceError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Cannot get file from source', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-0007', status: 500, errorCode: 'SNYK-OS-0007', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.CannotGetFileFromSourceError = CannotGetFileFromSourceError; /** * @class * @name MissingEnvironmentVariableError * @description The server encountered a critical operation that requires a specific environment variable, but the variable is not set or is not accessible within the current environment. * @summary Missing environment variable * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class MissingEnvironmentVariableError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Missing environment variable', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-0008', status: 500, errorCode: 'SNYK-OS-0008', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.MissingEnvironmentVariableError = MissingEnvironmentVariableError; /** * @class * @name UnsupportedManifestFileError * @description The provided manifest file is not supported by Snyk for .NET. * * See more: * - [https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/.net](https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/.net) * @summary Unsupported manifest file type for remediation * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnsupportedManifestFileError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unsupported manifest file type for remediation', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-dotnet-0001', status: 400, errorCode: 'SNYK-OS-DOTNET-0001', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/.net', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnsupportedManifestFileError = UnsupportedManifestFileError; /** * @class * @name UnsupportedTargetFrameworkError * @description The provided manifest file defines a `` or `` that is not currently supported by Snyk's .NET scanning solution. * @summary Target framework not supported * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnsupportedTargetFrameworkError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Target framework not supported', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-dotnet-0002', status: 422, errorCode: 'SNYK-OS-DOTNET-0002', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnsupportedTargetFrameworkError = UnsupportedTargetFrameworkError; /** * @class * @name MissingStaticMainFunctionError * @description This error occurs when no static Main method with a correct signature is found in the code that produces an executable file. * It also occurs if the entry point function, `Main`, is defined with the wrong case, such as lower-case main. * * In order to fix this issue, ensure that your program has a .cs file that contains a main function, such as * ```c# * namespace Example * { * class Program * { * static void Main(string[] args) * { * Console.WriteLine("hello world"); * } * } * } * ``` * * See more: * - [https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs5001](https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs5001) * @summary Your C# code is missing a static Main function * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class MissingStaticMainFunctionError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Your C# code is missing a static Main function', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-dotnet-0003', status: 422, errorCode: 'SNYK-OS-DOTNET-0003', level: 'error', instance, }, details, Object.assign({ links: [ 'https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs5001', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.MissingStaticMainFunctionError = MissingStaticMainFunctionError; /** * @class * @name PublishFailedError * @description This error occurs when running `dotnet publish --sc --framework ` fails to generate a * self-contained binary. Snyk needs to run this command in order to adequately determine the dependency tree for your project. If this command fails, Snyk cannot continue. * * Steps to determine why this happened: * * * Checkout a clean version of your project in a temporary folder * * Run `dotnet publish --sc --framework ` on your project, and confirm this step fails. * * If this step is successful locally, it is possible that Snyk is running another version of the .NET SDK. To tell Snyk which version of the .NET SDK to use, consider using the [global.json](https://learn.microsoft.com/en-us/dotnet/core/tools/global-json) solution provided by Microsoft. * * See more: * - [https://learn.microsoft.com/en-us/dotnet/core/tools/sdk-errors/](https://learn.microsoft.com/en-us/dotnet/core/tools/sdk-errors/) * - [https://learn.microsoft.com/en-us/dotnet/core/tools/global-json](https://learn.microsoft.com/en-us/dotnet/core/tools/global-json) * - [https://github.com/snyk/snyk-nuget-plugin/blob/885486aa656c28d3db465c8d22710770d5cc6773/lib/nuget-parser/cli/dotnet.ts#L67](https://github.com/snyk/snyk-nuget-plugin/blob/885486aa656c28d3db465c8d22710770d5cc6773/lib/nuget-parser/cli/dotnet.ts#L67) * @summary The dotnet CLI is unable to generate a self-contained binary * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class PublishFailedError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'The dotnet CLI is unable to generate a self-contained binary', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-dotnet-0004', status: 422, errorCode: 'SNYK-OS-DOTNET-0004', level: 'error', instance, }, details, Object.assign({ links: [ 'https://learn.microsoft.com/en-us/dotnet/core/tools/sdk-errors/', 'https://learn.microsoft.com/en-us/dotnet/core/tools/global-json', 'https://github.com/snyk/snyk-nuget-plugin/blob/885486aa656c28d3db465c8d22710770d5cc6773/lib/nuget-parser/cli/dotnet.ts#L67', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.PublishFailedError = PublishFailedError; /** * @class * @name PrivateModuleError * @description Snyk could not access the private modules within your go.mod files. * * See more: * - [https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/go](https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/go) * @summary Failed to access private module * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class PrivateModuleError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Failed to access private module', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-go-0001', status: 400, errorCode: 'SNYK-OS-GO-0001', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/go', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.PrivateModuleError = PrivateModuleError; /** * @class * @name GoModFileMissingError * @description A go.mod file was not found in the current directory or any parent directory. * * See more: * - [https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/go](https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/go) * @summary Go mod file not found * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class GoModFileMissingError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Go mod file not found', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-go-0002', status: 400, errorCode: 'SNYK-OS-GO-0002', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/go', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.GoModFileMissingError = GoModFileMissingError; /** * @class * @name SsoReAuthRequiredError * @description Your code is cloned on an isolated environment using Git as it is required by Snyk to analyze its dependencies. * * Your Organization has enabled or enforced SAML SSO after you authorized Snyk to access your code, and a re-authentication is therefore required. * * The error you're seeing is usually reproducible by attempting to do a `git clone` of your repository with incorrectly configured credentials. * Verify your authentication configuration with your Git cloud provider and try again. * * See more: * - [https://docs.github.com/en/enterprise-cloud@latest/authentication/authenticating-with-saml-single-sign-on/about-authentication-with-saml-single-sign-on#about-oauth-apps-github-apps-and-saml-sso](https://docs.github.com/en/enterprise-cloud@latest/authentication/authenticating-with-saml-single-sign-on/about-authentication-with-saml-single-sign-on#about-oauth-apps-github-apps-and-saml-sso) * @summary OAuth re-authorization required * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class SsoReAuthRequiredError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'OAuth re-authorization required', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-go-0003', status: 422, errorCode: 'SNYK-OS-GO-0003', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.github.com/en/enterprise-cloud@latest/authentication/authenticating-with-saml-single-sign-on/about-authentication-with-saml-single-sign-on#about-oauth-apps-github-apps-and-saml-sso', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.SsoReAuthRequiredError = SsoReAuthRequiredError; /** * @class * @name IncompleteProjectError * @description Generating the dependency graph requires Snyk to run go list `go list -deps -json` inside the project. If the operation fails, creating a full dependency graph cannot continue. * * This error means that you need some cleanup, such as `go mod tidy`) or your project deployment process contains a code generation step such as `protobuf` or similar that is not currently supported by Snyk. * * To verify if this is the case, clone your project in a clean environment, run go list `go list -deps -json` and verify whether the operation fails. * * If Snyk cannot process your code successfully, insert the Snyk CLI as part of your deployment pipeline. * * See more: * - [https://docs.snyk.io/snyk-cli](https://docs.snyk.io/snyk-cli) * - [https://github.com/snyk/snyk-go-plugin](https://github.com/snyk/snyk-go-plugin) * - [https://github.com/golang/go/blob/master/src/cmd/go/internal/list/list.go](https://github.com/golang/go/blob/master/src/cmd/go/internal/list/list.go) * @summary Your project repository is missing required files * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class IncompleteProjectError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Your project repository is missing required files', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-go-0004', status: 422, errorCode: 'SNYK-OS-GO-0004', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/snyk-cli', 'https://github.com/snyk/snyk-go-plugin', 'https://github.com/golang/go/blob/master/src/cmd/go/internal/list/list.go', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.IncompleteProjectError = IncompleteProjectError; /** * @class * @name InconsistentVendoringError * @description Generating the dependency graph requires Snyk to run `go list -deps -json` inside the project. If the operation fails, creating a full dependency graph cannot continue. * * This error means that there is inconsistency between your `vendor/modules.txt` file and your `go.mod` file. To remediate, you need to: * * * `go mod vendor` * * `go mod tidy` * * Next, commit those changes to your repo. Snyk does not manipulate with your code on our end by design, which is why this is not done automatically. * * To verify if this is the case, clone your project in a clean environment, run go list `go list -deps -json` and verify whether the operation fails. * Then try and run the above mentioned commands and see if your SCM system reports changes in files. * * See more: * - [https://go.dev/ref/mod#go-mod-vendor](https://go.dev/ref/mod#go-mod-vendor) * @summary Your project repository has inconsistent vendoring information * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InconsistentVendoringError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Your project repository has inconsistent vendoring information', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-go-0005', status: 422, errorCode: 'SNYK-OS-GO-0005', level: 'error', instance, }, details, Object.assign({ links: [ 'https://go.dev/ref/mod#go-mod-vendor', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.InconsistentVendoringError = InconsistentVendoringError; /** * @class * @name UnsupportedExternalFileGenerationSCMError * @description Snyk currently does not support external file generation in your project. This limitation is due to Snyk's lack of visibility into the third-party generator tools you may be using and the specific commands required to generate these files. * * Snyk can only work with the files available in your repository and does not have insight into the generation process for external files. * @summary Unsupported external file generation * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnsupportedExternalFileGenerationSCMError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unsupported external file generation', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-go-0006', status: 422, errorCode: 'SNYK-OS-GO-0006', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnsupportedExternalFileGenerationSCMError = UnsupportedExternalFileGenerationSCMError; /** * @class * @name MissingRequirementFromPomError * @description The required property is missing from the pom object. * @summary Missing property * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class MissingRequirementFromPomError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Missing property', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0001', status: 422, errorCode: 'SNYK-OS-MAVEN-0001', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.MissingRequirementFromPomError = MissingRequirementFromPomError; /** * @class * @name UnableToResolveValueForPropertyError * @description The targeted property could not be resolved with a valid value. * @summary Unable to resolve value for property * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnableToResolveValueForPropertyError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unable to resolve value for property', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0002', status: 422, errorCode: 'SNYK-OS-MAVEN-0002', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnableToResolveValueForPropertyError = UnableToResolveValueForPropertyError; /** * @class * @name UnableToResolveVersionForPropertyError * @description The targeted property could not be resolved with a valid version. * @summary Unable to resolve version for property * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnableToResolveVersionForPropertyError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unable to resolve version for property', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0003', status: 422, errorCode: 'SNYK-OS-MAVEN-0003', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnableToResolveVersionForPropertyError = UnableToResolveVersionForPropertyError; /** * @class * @name CyclicPropertyDetectedInPomFileError * @description There is circular dependency among properties in the Maven project's configuration file (POM), preventing proper resolution and causing an error. * @summary Cyclic property detected in POM file * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class CyclicPropertyDetectedInPomFileError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Cyclic property detected in POM file', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0004', status: 422, errorCode: 'SNYK-OS-MAVEN-0004', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.CyclicPropertyDetectedInPomFileError = CyclicPropertyDetectedInPomFileError; /** * @class * @name UnableToParseXMLError * @description There is an error parsing the XML file. This could be referring to either pom.xml or maven-metadata.xml. * @summary Error parsing the XML file * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnableToParseXMLError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Error parsing the XML file', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0005', status: 500, errorCode: 'SNYK-OS-MAVEN-0005', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnableToParseXMLError = UnableToParseXMLError; /** * @class * @name InvalidCoordinatesError * @description The coordinates provided for a project were invalid. * @summary Invalid coordinates provided * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InvalidCoordinatesError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Invalid coordinates provided', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0006', status: 422, errorCode: 'SNYK-OS-MAVEN-0006', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.InvalidCoordinatesError = InvalidCoordinatesError; /** * @class * @name SkippedGroupError * @description Skipping a specific groupId starting due to remapped coordinates. * @summary Skipping group * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class SkippedGroupError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Skipping group', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0007', status: 422, errorCode: 'SNYK-OS-MAVEN-0007', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.SkippedGroupError = SkippedGroupError; /** * @class * @name PomFileNotFoundError * @description The pom file was not found in Maven repository. * @summary Pom file not found * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class PomFileNotFoundError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Pom file not found', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0008', status: 422, errorCode: 'SNYK-OS-MAVEN-0008', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.PomFileNotFoundError = PomFileNotFoundError; /** * @class * @name MissingProjectFromPomError * @description A project element is missing from POM. * @summary Missing project from POM * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class MissingProjectFromPomError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Missing project from POM', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0009', status: 422, errorCode: 'SNYK-OS-MAVEN-0009', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.MissingProjectFromPomError = MissingProjectFromPomError; /** * @class * @name CannotResolveTargetPomFromXmlError * @description Cannot resolve the targeted POM from the input XML. * @summary Cannot resolve the target POM from the input XML * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class CannotResolveTargetPomFromXmlError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Cannot resolve the target POM from the input XML', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0010', status: 422, errorCode: 'SNYK-OS-MAVEN-0010', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.CannotResolveTargetPomFromXmlError = CannotResolveTargetPomFromXmlError; /** * @class * @name CannotResolveTargetPomFromRepoError * @description Cannot resolve the targeted POM from the repository. * @summary Cannot resolve the target POM from the repository * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class CannotResolveTargetPomFromRepoError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Cannot resolve the target POM from the repository', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0011', status: 404, errorCode: 'SNYK-OS-MAVEN-0011', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.CannotResolveTargetPomFromRepoError = CannotResolveTargetPomFromRepoError; /** * @class * @name CannotGetBuildFileFromRepoError * @description Cannot get the build file repository. * @summary Cannot get the build file repository * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class CannotGetBuildFileFromRepoError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Cannot get the build file repository', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0012', status: 404, errorCode: 'SNYK-OS-MAVEN-0012', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.CannotGetBuildFileFromRepoError = CannotGetBuildFileFromRepoError; /** * @class * @name CannotCreateGitHostError * @description Cannot create source URL. * @summary Unable to create hosted git info * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class CannotCreateGitHostError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unable to create hosted git info', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0013', status: 500, errorCode: 'SNYK-OS-MAVEN-0013', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.CannotCreateGitHostError = CannotCreateGitHostError; /** * @class * @name NoReleasedVersionForVersionsRangeError * @description There was no version released for the specified versions range. * @summary No released version for versions range * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class NoReleasedVersionForVersionsRangeError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'No released version for versions range', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0014', status: 422, errorCode: 'SNYK-OS-MAVEN-0014', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.NoReleasedVersionForVersionsRangeError = NoReleasedVersionForVersionsRangeError; /** * @class * @name SourceNotSupportedError * @description The source used is not supported by fetcher. The supported sources are: github, bitbucket, gitlab. * @summary Source is not supported * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class SourceNotSupportedError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Source is not supported', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0015', status: 422, errorCode: 'SNYK-OS-MAVEN-0015', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.SourceNotSupportedError = SourceNotSupportedError; /** * @class * @name TimeoutWhenProcessingTheDepTreeError * @description There was an timeout when processing the dependecy tree. * @summary Timeout when processing the dependency tree * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class TimeoutWhenProcessingTheDepTreeError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Timeout when processing the dependency tree', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-maven-0016', status: 422, errorCode: 'SNYK-OS-MAVEN-0016', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.TimeoutWhenProcessingTheDepTreeError = TimeoutWhenProcessingTheDepTreeError; /** * @class * @name NoRepoFoundForTheNPMPackageError * @description No repository found for the NPM package. * @summary No repository found for A NPM package * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class NoRepoFoundForTheNPMPackageError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'No repository found for A NPM package', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0001', status: 422, errorCode: 'SNYK-OS-NODEJS-0001', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.NoRepoFoundForTheNPMPackageError = NoRepoFoundForTheNPMPackageError; /** * @class * @name CouldNotParseNPMRegistryURLError * @description Could not parse NPM registry URL. * @summary Could not parse NPM registry URL * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class CouldNotParseNPMRegistryURLError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Could not parse NPM registry URL', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0002', status: 422, errorCode: 'SNYK-OS-NODEJS-0002', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.CouldNotParseNPMRegistryURLError = CouldNotParseNPMRegistryURLError; /** * @class * @name CouldNotFindBrokerURLError * @description Could not find a broker resolved URL. * @summary Could not find a broker resolved URL * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class CouldNotFindBrokerURLError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Could not find a broker resolved URL', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0003', status: 422, errorCode: 'SNYK-OS-NODEJS-0003', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.CouldNotFindBrokerURLError = CouldNotFindBrokerURLError; /** * @class * @name UnableToReplaceBrokerURLError * @description Unable to replace all broker urls in lock file. * @summary Unable to replace broker URL * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnableToReplaceBrokerURLError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unable to replace broker URL', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0004', status: 422, errorCode: 'SNYK-OS-NODEJS-0004', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnableToReplaceBrokerURLError = UnableToReplaceBrokerURLError; /** * @class * @name BadNPMVersionError * @description The NPM version is not supported. * @summary Bad NPM version * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class BadNPMVersionError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Bad NPM version', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0005', status: 422, errorCode: 'SNYK-OS-NODEJS-0005', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.BadNPMVersionError = BadNPMVersionError; /** * @class * @name UnknownBlobEncodingOnGithubError * @description Unknown blob encoding on Github. * @summary Unknown blob encoding on Github * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnknownBlobEncodingOnGithubError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unknown blob encoding on Github', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0006', status: 422, errorCode: 'SNYK-OS-NODEJS-0006', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnknownBlobEncodingOnGithubError = UnknownBlobEncodingOnGithubError; /** * @class * @name NoResultsFromForkerProcessesError * @description No result from forked process. * @summary No result from forked process * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class NoResultsFromForkerProcessesError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'No result from forked process', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0007', status: 500, errorCode: 'SNYK-OS-NODEJS-0007', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.NoResultsFromForkerProcessesError = NoResultsFromForkerProcessesError; /** * @class * @name ChildProcessExecutionError * @description The child process encountered an error during execution. * @summary Child Process Execution Error * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class ChildProcessExecutionError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Child Process Execution Error', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0008', status: 500, errorCode: 'SNYK-OS-NODEJS-0008', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.ChildProcessExecutionError = ChildProcessExecutionError; /** * @class * @name NoValidPackageUpgradesError * @description The system attempted to find valid upgrades for the packages specified in the lock file, but none were available. * @summary No valid package upgrades * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class NoValidPackageUpgradesError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'No valid package upgrades', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0009', status: 422, errorCode: 'SNYK-OS-NODEJS-0009', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.NoValidPackageUpgradesError = NoValidPackageUpgradesError; /** * @class * @name NoDependencyUpdatesError * @description There are no available updates for the dependencies. * @summary No dependency updates * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class NoDependencyUpdatesError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'No dependency updates', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0010', status: 422, errorCode: 'SNYK-OS-NODEJS-0010', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.NoDependencyUpdatesError = NoDependencyUpdatesError; /** * @class * @name CouldNotParseJSONFileError * @description An error occurred while attempting to parse a JSON file. * @summary Could not parse JSON file * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class CouldNotParseJSONFileError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Could not parse JSON file', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0011', status: 422, errorCode: 'SNYK-OS-NODEJS-0011', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.CouldNotParseJSONFileError = CouldNotParseJSONFileError; /** * @class * @name Base64EncodeError * @description An error occurred while attempting to perform Base64 encoding. * @summary Could not Base64 encode * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class Base64EncodeError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Could not Base64 encode', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0012', status: 422, errorCode: 'SNYK-OS-NODEJS-0012', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.Base64EncodeError = Base64EncodeError; /** * @class * @name Base64DecodeError * @description An error occurred while attempting to perform Base64 decoding. * @summary Could not Base64 decode * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class Base64DecodeError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Could not Base64 decode', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0013', status: 422, errorCode: 'SNYK-OS-NODEJS-0013', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.Base64DecodeError = Base64DecodeError; /** * @class * @name MissingSupportedFileError * @description Could not find supported file. * @summary Missing supported file * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class MissingSupportedFileError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Missing supported file', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0014', status: 400, errorCode: 'SNYK-OS-NODEJS-0014', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.MissingSupportedFileError = MissingSupportedFileError; /** * @class * @name InvalidConfigurationError * @description The configuration parameter does not meet the expected data type. Please ensure the provided value is of the correct data type. * @summary Invalid configuration * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InvalidConfigurationError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Invalid configuration', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-nodejs-0015', status: 400, errorCode: 'SNYK-OS-NODEJS-0015', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.InvalidConfigurationError = InvalidConfigurationError; /** * @class * @name UnsupportedRequirementsFileError * @description The provided requirements file is not supported by Snyk for Python. * * See more: * - [https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/python](https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/python) * @summary Unsupported manifest file type for remediation * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnsupportedRequirementsFileError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unsupported manifest file type for remediation', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-pip-0001', status: 422, errorCode: 'SNYK-OS-PIP-0001', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-applications/supported-languages-and-frameworks/python', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnsupportedRequirementsFileError = UnsupportedRequirementsFileError; /** * @class * @name TooManyManifestFilesError * @description Too many manifest files were provided in the request body. * @summary Received more manifests than expected * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class TooManyManifestFilesError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Received more manifests than expected', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-pip-0002', status: 422, errorCode: 'SNYK-OS-PIP-0002', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.TooManyManifestFilesError = TooManyManifestFilesError; /** * @class * @name FailedToApplyDependencyUpdatesError * @description An error occured while updating dependencies. * @summary Failed to apply dependency updates * @category OpenSourceEcosystems * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class FailedToApplyDependencyUpdatesError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Failed to apply dependency updates', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-pip-0003', status: 422, errorCode: 'SNYK-OS-PIP-0003', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.FailedToApplyDependencyUpdatesError = FailedToApplyDependencyUpdatesError; //# sourceMappingURL=OpenSourceEcosystems-error-catalog.js.map /***/ }), /***/ 73601: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.InternalServerError = exports.StorageFailureError = exports.DataTransformationError = exports.InvalidResponseError = exports.InvalidRequestError = void 0; const problem_error_1 = __webpack_require__(66255); /** * @class * @name InvalidRequestError * @description Check the body of your request and try again. * @summary Invalid request * @category OpenSourceProjectIssues * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InvalidRequestError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Invalid request', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-ospi-1001', status: 400, errorCode: 'SNYK-OSSI-OSPI-1001', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.InvalidRequestError = InvalidRequestError; /** * @class * @name InvalidResponseError * @description This issue is unexpected, and the service will recover shortly. If the error still occurs, contact support. * @summary Unable to return valid API response * @category OpenSourceProjectIssues * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InvalidResponseError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unable to return valid API response', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-ospi-1002', status: 500, errorCode: 'SNYK-OSSI-OSPI-1002', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.InvalidResponseError = InvalidResponseError; /** * @class * @name DataTransformationError * @description This issue is unexpected, and the service will recover shortly. If the error still occurs, contact support. * @summary Failed to process data * @category OpenSourceProjectIssues * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class DataTransformationError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Failed to process data', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-ospi-2001', status: 500, errorCode: 'SNYK-OSSI-OSPI-2001', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.DataTransformationError = DataTransformationError; /** * @class * @name StorageFailureError * @description Check inputs and then try again. If the error still occurs, contact support. * @summary Failed to store issue data * @category OpenSourceProjectIssues * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class StorageFailureError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Failed to store issue data', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-ospi-3001', status: 500, errorCode: 'SNYK-OSSI-OSPI-3001', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.StorageFailureError = StorageFailureError; /** * @class * @name InternalServerError * @description This issue is unexpected, and the service will recover shortly. If the error still occurs, contact support. * @summary Internal server error * @category OpenSourceProjectIssues * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InternalServerError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Internal server error', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-ospi-4001', status: 500, errorCode: 'SNYK-OSSI-OSPI-4001', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.InternalServerError = InternalServerError; //# sourceMappingURL=OpenSourceProjectIssues-error-catalog.js.map /***/ }), /***/ 79395: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.InternalServerError = exports.StorageFailureError = exports.DataTransformationError = exports.InvalidResponseError = exports.InvalidRequestError = void 0; const problem_error_1 = __webpack_require__(66255); /** * @class * @name InvalidRequestError * @description Check the body of your request and try again. * @summary Invalid request * @category OpenSourceProjectSnapshots * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InvalidRequestError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Invalid request', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-ospss-1001', status: 400, errorCode: 'SNYK-OSSI-OSPSS-1001', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.InvalidRequestError = InvalidRequestError; /** * @class * @name InvalidResponseError * @description This issue is unexpected, and the service will recover shortly. If the error still occurs, contact support. * @summary Unable to return valid API response * @category OpenSourceProjectSnapshots * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InvalidResponseError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unable to return valid API response', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-ospss-1002', status: 500, errorCode: 'SNYK-OSSI-OSPSS-1002', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.InvalidResponseError = InvalidResponseError; /** * @class * @name DataTransformationError * @description This issue is unexpected, and the service will recover shortly. If the error still occurs, contact support. * @summary Failed to process data * @category OpenSourceProjectSnapshots * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class DataTransformationError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Failed to process data', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-ospss-2001', status: 500, errorCode: 'SNYK-OSSI-OSPSS-2001', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.DataTransformationError = DataTransformationError; /** * @class * @name StorageFailureError * @description Check inputs and then try again. If the error still occurs, contact support. * @summary Failed to store snapshot data * @category OpenSourceProjectSnapshots * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class StorageFailureError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Failed to store snapshot data', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-ospss-3001', status: 500, errorCode: 'SNYK-OSSI-OSPSS-3001', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.StorageFailureError = StorageFailureError; /** * @class * @name InternalServerError * @description This issue is unexpected, and the service will recover shortly. If the error still occurs, contact support. * @summary Internal server error * @category OpenSourceProjectSnapshots * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InternalServerError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Internal server error', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-ospss-4001', status: 500, errorCode: 'SNYK-OSSI-OSPSS-4001', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.InternalServerError = InternalServerError; //# sourceMappingURL=OpenSourceProjectSnapshots-error-catalog.js.map /***/ }), /***/ 74290: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Sha1NotFoundError = exports.MavenSearchServiceUnavailableError = void 0; const problem_error_1 = __webpack_require__(66255); /** * @class * @name MavenSearchServiceUnavailableError * @description The upstream Maven search service is not available. * * See more: * - [https://search.maven.org](https://search.maven.org) * - [https://status.maven.org](https://status.maven.org) * @summary Maven search service unavailable * @category OpenSourceUnmanaged * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class MavenSearchServiceUnavailableError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Maven search service unavailable', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-osjvm-001', status: 503, errorCode: 'SNYK-OSJVM-001', level: 'warn', instance, }, details, Object.assign({ links: [ 'https://search.maven.org', 'https://status.maven.org', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.MavenSearchServiceUnavailableError = MavenSearchServiceUnavailableError; /** * @class * @name Sha1NotFoundError * @description Unable to find the coordinates for the provided SHA1. * * See more: * - [https://docs.snyk.io/snyk-cli/test-for-vulnerabilities/scan-all-unmanaged-jar-files](https://docs.snyk.io/snyk-cli/test-for-vulnerabilities/scan-all-unmanaged-jar-files) * @summary SHA1 not found * @category OpenSourceUnmanaged * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class Sha1NotFoundError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'SHA1 not found', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-osjvm-002', status: 404, errorCode: 'SNYK-OSJVM-002', level: 'warn', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/snyk-cli/test-for-vulnerabilities/scan-all-unmanaged-jar-files', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.Sha1NotFoundError = Sha1NotFoundError; //# sourceMappingURL=OpenSourceUnmanaged-error-catalog.js.map /***/ }), /***/ 47585: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UnsupportedContainerVendorError = exports.UndefinedContainerVendorError = exports.UnsupportedDebianDistroError = exports.UndefinedContainerDistroError = exports.TooManyIssuesError = exports.TooManyPurlsError = exports.InvalidPaginationParametersError = exports.InternalServerError = exports.VulndbNextError = exports.VulnDBInvalidResponseError = exports.VulnerabilityServiceUnavailableError = exports.PackageNotFoundError = exports.UnsupportedGoVersionFormatError = exports.ComponentNotSupportedError = exports.MissingComponentError = exports.UnsupportedEcosystemError = exports.NamespaceNotProvidedError = exports.InvalidPurlError = exports.AuthorizationRequestFailureError = exports.OrganizationNotWhitelistedError = void 0; const problem_error_1 = __webpack_require__(66255); /** * @class * @name OrganizationNotWhitelistedError * @description You likely don’t have access to the features in Beta. To get access, you can request access to features in Beta through your account manager or team. * @summary Your Organisation is not authorized to perform this action * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class OrganizationNotWhitelistedError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Your Organisation is not authorized to perform this action', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-1040', status: 403, errorCode: 'SNYK-OSSI-1040', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.OrganizationNotWhitelistedError = OrganizationNotWhitelistedError; /** * @class * @name AuthorizationRequestFailureError * @description Unexpected error when authenticating. Try again, and if the error still occurs, contact support. * @summary Authorization request failure * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class AuthorizationRequestFailureError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Authorization request failure', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-1050', status: 500, errorCode: 'SNYK-OSSI-1050', level: 'fatal', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.AuthorizationRequestFailureError = AuthorizationRequestFailureError; /** * @class * @name InvalidPurlError * @description Make sure that the purl is valid. See the Package URL specification link for further information. * * See more: * - [https://github.com/package-url/purl-spec/blob/master/PURL-SPECIFICATION.rst](https://github.com/package-url/purl-spec/blob/master/PURL-SPECIFICATION.rst) * @summary Invalid purl * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InvalidPurlError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Invalid purl', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2010', status: 400, errorCode: 'SNYK-OSSI-2010', level: 'warn', instance, }, details, Object.assign({ links: [ 'https://github.com/package-url/purl-spec/blob/master/PURL-SPECIFICATION.rst', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.InvalidPurlError = InvalidPurlError; /** * @class * @name NamespaceNotProvidedError * @description You have requested a package type that requires a namespace (e.g. maven group id). Provide the namespace to retrieve the package. * * See more: * - [https://github.com/package-url/purl-spec/blob/master/PURL-SPECIFICATION.rst](https://github.com/package-url/purl-spec/blob/master/PURL-SPECIFICATION.rst) * @summary Namespace not specified * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class NamespaceNotProvidedError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Namespace not specified', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2011', status: 400, errorCode: 'SNYK-OSSI-2011', level: 'warn', instance, }, details, Object.assign({ links: [ 'https://github.com/package-url/purl-spec/blob/master/PURL-SPECIFICATION.rst', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.NamespaceNotProvidedError = NamespaceNotProvidedError; /** * @class * @name UnsupportedEcosystemError * @description The package type is not supported. Check the List issues for a package in Snyk API. * @summary Unsupported ecosystem * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnsupportedEcosystemError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unsupported ecosystem', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2020', status: 400, errorCode: 'SNYK-OSSI-2020', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnsupportedEcosystemError = UnsupportedEcosystemError; /** * @class * @name MissingComponentError * @description A list of components of the purl spec is required. The purl did not specify all the required components. * @summary Purl components required * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class MissingComponentError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Purl components required', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2021', status: 400, errorCode: 'SNYK-OSSI-2021', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.MissingComponentError = MissingComponentError; /** * @class * @name ComponentNotSupportedError * @description Remove the unsupported component and retry the request. * @summary Unsupported purl components * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class ComponentNotSupportedError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unsupported purl components', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2022', status: 400, errorCode: 'SNYK-OSSI-2022', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.ComponentNotSupportedError = ComponentNotSupportedError; /** * @class * @name UnsupportedGoVersionFormatError * @description Go pseudo version not supported. * @summary Go version format not supported * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnsupportedGoVersionFormatError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Go version format not supported', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2023', status: 400, errorCode: 'SNYK-OSSI-2023', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnsupportedGoVersionFormatError = UnsupportedGoVersionFormatError; /** * @class * @name PackageNotFoundError * @description The package you specified in the purl cannot be found in the vulnerability database. Check the package name, ecosystem, and version, then try again. * @summary Requested package not found * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class PackageNotFoundError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Requested package not found', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2030', status: 404, errorCode: 'SNYK-OSSI-2030', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.PackageNotFoundError = PackageNotFoundError; /** * @class * @name VulnerabilityServiceUnavailableError * @description This issue is unexpected, and the service will recover shortly. If the error still occurs, contact support. * @summary Vulnerability service not available * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class VulnerabilityServiceUnavailableError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Vulnerability service not available', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2031', status: 503, errorCode: 'SNYK-OSSI-2031', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.VulnerabilityServiceUnavailableError = VulnerabilityServiceUnavailableError; /** * @class * @name VulnDBInvalidResponseError * @description An unexpected error occurred. Please try again, and if you continue to experience issues please contact support. * @summary This issue is unexpected and the service should recover quickly if not please contact support * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class VulnDBInvalidResponseError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'This issue is unexpected and the service should recover quickly if not please contact support', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2032', status: 500, errorCode: 'SNYK-OSSI-2032', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.VulnDBInvalidResponseError = VulnDBInvalidResponseError; /** * @class * @name VulndbNextError * @description An unexpected error occurred with the vulnerability service. Please try again, and if you continue to experience issues please contact support. * @summary This issue is unexpected and the service should recover quickly if not please contact support * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class VulndbNextError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'This issue is unexpected and the service should recover quickly if not please contact support', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2033', status: 500, errorCode: 'SNYK-OSSI-2033', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.VulndbNextError = VulndbNextError; /** * @class * @name InternalServerError * @description This issue is unexpected, and the service will recover shortly. If the error still occurs, contact support. * @summary Request not processed due to unexpected error * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InternalServerError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Request not processed due to unexpected error', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2040', status: 500, errorCode: 'SNYK-OSSI-2040', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.InternalServerError = InternalServerError; /** * @class * @name InvalidPaginationParametersError * @description The pagination limit is > 1 and ≤ 1000, and the offset is ≥0. * @summary Invalid pagination parameters * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InvalidPaginationParametersError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Invalid pagination parameters', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2041', status: 400, errorCode: 'SNYK-OSSI-2041', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.InvalidPaginationParametersError = InvalidPaginationParametersError; /** * @class * @name TooManyPurlsError * @description The number of purls sent in the request exceeds the limit of 1000 set by the service. * @summary purls exceed limit * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class TooManyPurlsError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'purls exceed limit', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2042', status: 400, errorCode: 'SNYK-OSSI-2042', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.TooManyPurlsError = TooManyPurlsError; /** * @class * @name TooManyIssuesError * @description The number of issues found for the provided purls exceeds the limit defined by the API. Reduce the number of purls sent in a single request. * @summary Number of issues exceeds limit * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class TooManyIssuesError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Number of issues exceeds limit', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2043', status: 400, errorCode: 'SNYK-OSSI-2043', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.TooManyIssuesError = TooManyIssuesError; /** * @class * @name UndefinedContainerDistroError * @description The given Package URL does not have a required distro qualifier. * * See more: * - [https://docs.snyk.io/scan-containers/how-snyk-container-works/supported-operating-system-distributions#debian](https://docs.snyk.io/scan-containers/how-snyk-container-works/supported-operating-system-distributions#debian) * @summary Expected distro to be present * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UndefinedContainerDistroError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Expected distro to be present', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2044', status: 400, errorCode: 'SNYK-OSSI-2044', level: 'warn', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/scan-containers/how-snyk-container-works/supported-operating-system-distributions#debian', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.UndefinedContainerDistroError = UndefinedContainerDistroError; /** * @class * @name UnsupportedDebianDistroError * @description This Debian distro is currently not supported. * @summary Unsupported Debian distro * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnsupportedDebianDistroError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unsupported Debian distro', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2045', status: 400, errorCode: 'SNYK-OSSI-2045', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnsupportedDebianDistroError = UnsupportedDebianDistroError; /** * @class * @name UndefinedContainerVendorError * @description The given Package URL does not have a required namespace. * @summary Expected namespace to be present * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UndefinedContainerVendorError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Expected namespace to be present', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2046', status: 400, errorCode: 'SNYK-OSSI-2046', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UndefinedContainerVendorError = UndefinedContainerVendorError; /** * @class * @name UnsupportedContainerVendorError * @description The given Package URL does not contain a supported vendor. * @summary Unsupported vendor * @category PurlVulnerabilityFetching * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnsupportedContainerVendorError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Unsupported vendor', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-ossi-2047', status: 400, errorCode: 'SNYK-OSSI-2047', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnsupportedContainerVendorError = UnsupportedContainerVendorError; //# sourceMappingURL=PurlVulnerabilityFetching-error-catalog.js.map /***/ }), /***/ 68415: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.InvalidDepGraphError = exports.EmptyRequestBodyError = exports.MissingAuthTokenError = exports.DepGraphResponseError = exports.UnsupportedProjectError = exports.IaCOrSASTProjectError = exports.UnexpectedParseDepGraphError = exports.UnexpectedDepGraphResponseError = exports.InternalServerError = void 0; const problem_error_1 = __webpack_require__(66255); /** * @class * @name InternalServerError * @description An unexpected error occurred during the SBOM generation. Review the request, then try again. If the error persists, contact Snyk Support. * @summary SBOM generation export server error * @category SbomExport * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InternalServerError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'SBOM generation export server error', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-9000', status: 500, errorCode: 'SNYK-OS-9000', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.InternalServerError = InternalServerError; /** * @class * @name UnexpectedDepGraphResponseError * @description An unexpected dependency graph error occurred. Review the request, then try again. If the error persists, contact Snyk Support. * @summary Dependency graph error * @category SbomExport * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnexpectedDepGraphResponseError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Dependency graph error', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-9001', status: 500, errorCode: 'SNYK-OS-9001', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnexpectedDepGraphResponseError = UnexpectedDepGraphResponseError; /** * @class * @name UnexpectedParseDepGraphError * @description The dependency graph cannot be parsed due to an unexpected error. Review the request, then try again. If the error persists, contact Snyk Support. * @summary Error parsing dependency graph * @category SbomExport * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnexpectedParseDepGraphError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Error parsing dependency graph', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-9002', status: 500, errorCode: 'SNYK-OS-9002', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnexpectedParseDepGraphError = UnexpectedParseDepGraphError; /** * @class * @name IaCOrSASTProjectError * @description Only SBOMs for Snyk Open Source or Snyk Container projects are supported. * @summary SBOM not supported due to project type * @category SbomExport * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class IaCOrSASTProjectError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'SBOM not supported due to project type', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-9003', status: 404, errorCode: 'SNYK-OS-9003', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.IaCOrSASTProjectError = IaCOrSASTProjectError; /** * @class * @name UnsupportedProjectError * @description Only SBOMs for open source projects are supported (Snyk Open Source). * @summary SBOM not supported * @category SbomExport * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnsupportedProjectError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'SBOM not supported', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-9004', status: 404, errorCode: 'SNYK-OS-9004', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnsupportedProjectError = UnsupportedProjectError; /** * @class * @name DepGraphResponseError * @description The server cannot process the request due to incomplete data. Review the request, then try again. * @summary Dependency graph request cannot be processed * @category SbomExport * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class DepGraphResponseError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Dependency graph request cannot be processed', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-9005', status: 404, errorCode: 'SNYK-OS-9005', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.DepGraphResponseError = DepGraphResponseError; /** * @class * @name MissingAuthTokenError * @description The API token is misconfigured or expired. Configure or generate the API token, then try again. * * See more: * - [https://docs.snyk.io/snyk-api-info/revoking-and-regenerating-snyk-api-tokens](https://docs.snyk.io/snyk-api-info/revoking-and-regenerating-snyk-api-tokens) * @summary Authorization failed due to missing API token * @category SbomExport * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class MissingAuthTokenError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Authorization failed due to missing API token', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-9006', status: 401, errorCode: 'SNYK-OS-9006', level: 'warn', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/snyk-api-info/revoking-and-regenerating-snyk-api-tokens', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.MissingAuthTokenError = MissingAuthTokenError; /** * @class * @name EmptyRequestBodyError * @description The body of the request is empty. Review the request, then try again. * @summary Client request cannot be processed * @category SbomExport * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class EmptyRequestBodyError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Client request cannot be processed', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-9007', status: 400, errorCode: 'SNYK-OS-9007', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.EmptyRequestBodyError = EmptyRequestBodyError; /** * @class * @name InvalidDepGraphError * @description The request cannot be processed due to an internal error. Review the request, then try again. * @summary Invalid dependency graph * @category SbomExport * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class InvalidDepGraphError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Invalid dependency graph', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-os-9008', status: 400, errorCode: 'SNYK-OS-9008', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.InvalidDepGraphError = InvalidDepGraphError; //# sourceMappingURL=SbomExport-error-catalog.js.map /***/ }), /***/ 14802: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ServerError = exports.UnauthorisedError = exports.TimeoutError = exports.BadRequestError = exports.NotImplementedError = exports.TooManyRequestsError = void 0; const problem_error_1 = __webpack_require__(66255); /** * @class * @name TooManyRequestsError * @description The request rate limit has been exceeded. Wait a few minutes, then try again. * @summary Service temporarily throttled * @category Snyk * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class TooManyRequestsError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Service temporarily throttled', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-0001', status: 429, errorCode: 'SNYK-0001', level: 'warn', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.TooManyRequestsError = TooManyRequestsError; /** * @class * @name NotImplementedError * @description The server doesn’t recognize the request method, or it cannot fulfill it. Review the request and try again. * * See more: * - [https://docs.snyk.io/snyk-api-info](https://docs.snyk.io/snyk-api-info) * @summary Server error response * @category Snyk * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class NotImplementedError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Server error response', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-0002', status: 501, errorCode: 'SNYK-0002', level: 'error', instance, }, details, Object.assign({ links: [ 'https://docs.snyk.io/snyk-api-info', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.NotImplementedError = NotImplementedError; /** * @class * @name BadRequestError * @description The server cannot process the request due to a client error, such as malformed request syntax, size too large, invalid request message framing, or deceptive request routing. Review the request and try again. * @summary Client request cannot be processed * @category Snyk * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class BadRequestError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Client request cannot be processed', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-0003', status: 400, errorCode: 'SNYK-0003', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.BadRequestError = BadRequestError; /** * @class * @name TimeoutError * @description The server timed out during the request. Check Snyk status, then try again. * * See more: * - [https://status.snyk.io/](https://status.snyk.io/) * @summary Server communication error * @category Snyk * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class TimeoutError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Server communication error', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-0004', status: 504, errorCode: 'SNYK-0004', level: 'error', instance, }, details, Object.assign({ links: [ 'https://status.snyk.io/', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.TimeoutError = TimeoutError; /** * @class * @name UnauthorisedError * @description Authentication credentials not recognized, or user access is not provisioned. Revise credentials and try again, or request access from your Snyk administrator. * @summary Authentication error * @category Snyk * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class UnauthorisedError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Authentication error', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-0005', status: 401, errorCode: 'SNYK-0005', level: 'error', instance, }, details, Object.assign({ links: [] }, additionalData), cause); this.name = this.constructor.name; } } exports.UnauthorisedError = UnauthorisedError; /** * @class * @name ServerError * @description The server cannot process the request due to an unexpected error. Check Snyk status, then try again. * * See more: * - [https://status.snyk.io/](https://status.snyk.io/) * @summary Request not fulfilled due to server error * @category Snyk * @param {string} details the specific details that causes this error * @param {Record} [additionalData] a collection of relevant data specific to this error * @param {Error} [cause] the `Error` type that caused this error to be thrown * @param {string} [instance] the instance to use for this error. Overrides 'instance' metadata */ class ServerError extends problem_error_1.ProblemError { constructor(details, additionalData, cause, instance) { super({ title: 'Request not fulfilled due to server error ', type: 'https://docs.snyk.io/more-info/error-catalog#snyk-9999', status: 500, errorCode: 'SNYK-9999', level: 'error', instance, }, details, Object.assign({ links: [ 'https://status.snyk.io/', ] }, additionalData), cause); this.name = this.constructor.name; } } exports.ServerError = ServerError; //# sourceMappingURL=Snyk-error-catalog.js.map /***/ }), /***/ 69880: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Fix = exports.SbomExport = exports.OpenSourceUnmanaged = exports.OpenAPI = exports.IsolatedBuilds = exports.PurlVulnerabilityFetching = exports.OpenSourceProjectIssues = exports.OpenSourceProjectSnapshots = exports.OpenSourceEcosystems = exports.Snyk = void 0; exports.Snyk = __webpack_require__(14802); exports.OpenSourceEcosystems = __webpack_require__(50890); exports.OpenSourceProjectSnapshots = __webpack_require__(79395); exports.OpenSourceProjectIssues = __webpack_require__(73601); exports.PurlVulnerabilityFetching = __webpack_require__(47585); exports.IsolatedBuilds = __webpack_require__(47270); exports.OpenAPI = __webpack_require__(62699); exports.OpenSourceUnmanaged = __webpack_require__(74290); exports.SbomExport = __webpack_require__(68415); exports.Fix = __webpack_require__(5717); //# sourceMappingURL=error-catalog.js.map /***/ }), /***/ 28760: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CompositeError = void 0; const types_1 = __webpack_require__(20923); class CompositeError extends Error { constructor(errors) { super('CompositeError'); this.errors = errors; } /** * Convert this CompositeError to JsonApi. * If the error was created with 'instance' metadata then that will be used by default for all errors. * @param instance string the instance to use for the errors in this CompositeError. Overrides 'instance' metadata * @returns JsonApi a JsonApi object representing this CompositeError */ toJsonApi(instance) { const payload = { jsonapi: { version: '1.0', }, errors: this.errors.map((error) => error.toJsonApiErrorObject(instance)), }; return new types_1.JsonApi(payload); } } exports.CompositeError = CompositeError; //# sourceMappingURL=composite-error.js.map /***/ }), /***/ 82073: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __webpack_require__(2550); tslib_1.__exportStar(__webpack_require__(66255), exports); tslib_1.__exportStar(__webpack_require__(69880), exports); tslib_1.__exportStar(__webpack_require__(28760), exports); //# sourceMappingURL=index.js.map /***/ }), /***/ 66255: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProblemError = void 0; const types_1 = __webpack_require__(20923); const uuid_1 = __webpack_require__(73901); const util_1 = __webpack_require__(59686); class ProblemError extends Error { constructor(metadata, detail, additionalData, cause) { super(metadata.title); this.metadata = metadata; this.detail = detail; this.additionalData = additionalData; this.cause = cause; // Since `instanceof` cannot be relied upon for class checks in situations where the `ProblemError` was thrown from a dependency of the executing app, we need a more viable solution. // See: https://stackoverflow.com/questions/41587865/using-instanceof-on-objects-created-with-constructors-from-deep-npm-dependenci/41592087#41592087 this.isErrorCatalogError = true; if (additionalData && additionalData['overrideErrorId']) { this.id = additionalData['overrideErrorId']; } else { this.id = (0, uuid_1.v4)(); } } format(instance, formatType) { switch (formatType) { case types_1.ErrorFormats.JsonApi: return this.toJsonApi(instance); case types_1.ErrorFormats.ProblemJson: return this.toProblemJson(instance); default: throw new Error('invalid format type'); } } toProblemJson(instance) { const payload = Object.assign({ type: this.metadata.type, title: this.metadata.title, status: this.metadata.status, errorCode: this.metadata.errorCode, detail: this.detail, instance }, this.additionalData); return new types_1.ProblemJson(payload); } /** * Convert this ProblemError to a JsonApiErrorObject. * If the error was created with 'instance' metadata then that will be used by default. * @param instance string the instance to use for this error. Overrides 'instance' metadata * @returns JsonApiErrorObject a JsonApiErrorObject representing this ProblemError */ toJsonApiErrorObject(instance) { let source; // Get the instance from either the member or the parameter const theinstance = instance || this.metadata.instance; if (typeof theinstance === 'string') { source = (0, util_1.instanceToJsonApiSource)(theinstance); } const jsonApiErrorObject = { id: this.id, links: { about: this.metadata.type, }, status: String(this.metadata.status), code: this.metadata.errorCode, title: this.metadata.title, detail: this.detail, meta: Object.assign({}, this.additionalData), }; if (source) { jsonApiErrorObject.source = source; } return jsonApiErrorObject; } toJsonApi(instance) { const payload = { jsonapi: { version: '1.0', }, errors: [this.toJsonApiErrorObject(instance)], }; return new types_1.JsonApi(payload); } } exports.ProblemError = ProblemError; //# sourceMappingURL=problem-error.js.map /***/ }), /***/ 20923: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JsonApi = exports.ProblemJson = exports.ErrorFormats = void 0; var ErrorFormats; (function (ErrorFormats) { ErrorFormats[ErrorFormats["JsonApi"] = 0] = "JsonApi"; ErrorFormats[ErrorFormats["ProblemJson"] = 1] = "ProblemJson"; })(ErrorFormats || (exports.ErrorFormats = ErrorFormats = {})); class ProblemJson { constructor(payload) { this.payload = payload; } headers() { return { 'Content-Type': 'application/problem+json;', }; } body() { return this.payload; } } exports.ProblemJson = ProblemJson; class JsonApi { constructor(payload) { this.payload = payload; } headers() { return {}; } body() { return this.payload; } } exports.JsonApi = JsonApi; //# sourceMappingURL=types.js.map /***/ }), /***/ 59686: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __webpack_require__(2550); tslib_1.__exportStar(__webpack_require__(17612), exports); //# sourceMappingURL=index.js.map /***/ }), /***/ 17612: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * © 2023 Snyk Limited * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.instanceToJsonApiSource = void 0; const SOURCE_REGEXP = /^\/(query|params|body|headers)\/.*/; /** * Converts the instance string from an error into a JsonApiErrorSource * @param instance the instance string to convert * @returns A JsonApiErrorSource if appropriate, or undefined if not */ const instanceToJsonApiSource = (instance) => { let source; // See if the instance conforms to one of the source formats const matchErrorPath = instance.match(SOURCE_REGEXP); // If the match captures the path type and parameter, if (matchErrorPath !== null && matchErrorPath.length > 0) { // Convert the instance into a source switch (matchErrorPath[1]) { case 'query': case 'params': source = paramsInstanceToJsonApiSource(instance); break; case 'body': source = bodyInstanceToJsonApiSource(instance); break; case 'headers': source = headerInstanceToJsonApiSource(instance); break; } } return source; }; exports.instanceToJsonApiSource = instanceToJsonApiSource; // For a parameter, do not include the leading slash const PARAMETER_REGEXP = /^\/(?:params|query)\/(.*)/; const paramsInstanceToJsonApiSource = (instance) => { let parameter = ''; // The source is the name of the parameter, and is not a json path const matches = instance.match(PARAMETER_REGEXP); if (matches !== null && matches.length > 0) { parameter = matches[1]; } return { parameter, }; }; // For a pointer, capture the JSON path, including the leading slash const POINTER_REGEXP = /^\/body(\/.*)/; const bodyInstanceToJsonApiSource = (instance) => { let pointer = ''; const matches = instance.match(POINTER_REGEXP); if (matches !== null && matches.length > 0) { pointer = matches[1]; } return { pointer, }; }; // The source is the name of the header, and is not a json path const HEADER_REGEXP = /^\/headers\/(.*)/; const headerInstanceToJsonApiSource = (instance) => { let header = ''; const matches = instance.match(HEADER_REGEXP); if (matches !== null && matches.length > 0) { header = matches[1]; } return { header, }; }; //# sourceMappingURL=json-api.js.map /***/ }), /***/ 53966: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var PlainValue = __webpack_require__(51937); var resolveSeq = __webpack_require__(63970); var Schema = __webpack_require__(5533); const defaultOptions = { anchorPrefix: 'a', customTags: null, indent: 2, indentSeq: true, keepCstNodes: false, keepNodeTypes: true, keepBlobsInJSON: true, mapAsMap: false, maxAliasCount: 100, prettyErrors: false, // TODO Set true in v2 simpleKeys: false, version: '1.2' }; const scalarOptions = { get binary() { return resolveSeq.binaryOptions; }, set binary(opt) { Object.assign(resolveSeq.binaryOptions, opt); }, get bool() { return resolveSeq.boolOptions; }, set bool(opt) { Object.assign(resolveSeq.boolOptions, opt); }, get int() { return resolveSeq.intOptions; }, set int(opt) { Object.assign(resolveSeq.intOptions, opt); }, get null() { return resolveSeq.nullOptions; }, set null(opt) { Object.assign(resolveSeq.nullOptions, opt); }, get str() { return resolveSeq.strOptions; }, set str(opt) { Object.assign(resolveSeq.strOptions, opt); } }; const documentOptions = { '1.0': { schema: 'yaml-1.1', merge: true, tagPrefixes: [{ handle: '!', prefix: PlainValue.defaultTagPrefix }, { handle: '!!', prefix: 'tag:private.yaml.org,2002:' }] }, 1.1: { schema: 'yaml-1.1', merge: true, tagPrefixes: [{ handle: '!', prefix: '!' }, { handle: '!!', prefix: PlainValue.defaultTagPrefix }] }, 1.2: { schema: 'core', merge: false, tagPrefixes: [{ handle: '!', prefix: '!' }, { handle: '!!', prefix: PlainValue.defaultTagPrefix }] } }; function stringifyTag(doc, tag) { if ((doc.version || doc.options.version) === '1.0') { const priv = tag.match(/^tag:private\.yaml\.org,2002:([^:/]+)$/); if (priv) return '!' + priv[1]; const vocab = tag.match(/^tag:([a-zA-Z0-9-]+)\.yaml\.org,2002:(.*)/); return vocab ? `!${vocab[1]}/${vocab[2]}` : `!${tag.replace(/^tag:/, '')}`; } let p = doc.tagPrefixes.find(p => tag.indexOf(p.prefix) === 0); if (!p) { const dtp = doc.getDefaults().tagPrefixes; p = dtp && dtp.find(p => tag.indexOf(p.prefix) === 0); } if (!p) return tag[0] === '!' ? tag : `!<${tag}>`; const suffix = tag.substr(p.prefix.length).replace(/[!,[\]{}]/g, ch => ({ '!': '%21', ',': '%2C', '[': '%5B', ']': '%5D', '{': '%7B', '}': '%7D' })[ch]); return p.handle + suffix; } function getTagObject(tags, item) { if (item instanceof resolveSeq.Alias) return resolveSeq.Alias; if (item.tag) { const match = tags.filter(t => t.tag === item.tag); if (match.length > 0) return match.find(t => t.format === item.format) || match[0]; } let tagObj, obj; if (item instanceof resolveSeq.Scalar) { obj = item.value; // TODO: deprecate/remove class check const match = tags.filter(t => t.identify && t.identify(obj) || t.class && obj instanceof t.class); tagObj = match.find(t => t.format === item.format) || match.find(t => !t.format); } else { obj = item; tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass); } if (!tagObj) { const name = obj && obj.constructor ? obj.constructor.name : typeof obj; throw new Error(`Tag not resolved for ${name} value`); } return tagObj; } // needs to be called before value stringifier to allow for circular anchor refs function stringifyProps(node, tagObj, { anchors, doc }) { const props = []; const anchor = doc.anchors.getName(node); if (anchor) { anchors[anchor] = node; props.push(`&${anchor}`); } if (node.tag) { props.push(stringifyTag(doc, node.tag)); } else if (!tagObj.default) { props.push(stringifyTag(doc, tagObj.tag)); } return props.join(' '); } function stringify(item, ctx, onComment, onChompKeep) { const { anchors, schema } = ctx.doc; let tagObj; if (!(item instanceof resolveSeq.Node)) { const createCtx = { aliasNodes: [], onTagObj: o => tagObj = o, prevObjects: new Map() }; item = schema.createNode(item, true, null, createCtx); for (const alias of createCtx.aliasNodes) { alias.source = alias.source.node; let name = anchors.getName(alias.source); if (!name) { name = anchors.newName(); anchors.map[name] = alias.source; } } } if (item instanceof resolveSeq.Pair) return item.toString(ctx, onComment, onChompKeep); if (!tagObj) tagObj = getTagObject(schema.tags, item); const props = stringifyProps(item, tagObj, ctx); if (props.length > 0) ctx.indentAtStart = (ctx.indentAtStart || 0) + props.length + 1; const str = typeof tagObj.stringify === 'function' ? tagObj.stringify(item, ctx, onComment, onChompKeep) : item instanceof resolveSeq.Scalar ? resolveSeq.stringifyString(item, ctx, onComment, onChompKeep) : item.toString(ctx, onComment, onChompKeep); if (!props) return str; return item instanceof resolveSeq.Scalar || str[0] === '{' || str[0] === '[' ? `${props} ${str}` : `${props}\n${ctx.indent}${str}`; } class Anchors { static validAnchorNode(node) { return node instanceof resolveSeq.Scalar || node instanceof resolveSeq.YAMLSeq || node instanceof resolveSeq.YAMLMap; } constructor(prefix) { PlainValue._defineProperty(this, "map", Object.create(null)); this.prefix = prefix; } createAlias(node, name) { this.setAnchor(node, name); return new resolveSeq.Alias(node); } createMergePair(...sources) { const merge = new resolveSeq.Merge(); merge.value.items = sources.map(s => { if (s instanceof resolveSeq.Alias) { if (s.source instanceof resolveSeq.YAMLMap) return s; } else if (s instanceof resolveSeq.YAMLMap) { return this.createAlias(s); } throw new Error('Merge sources must be Map nodes or their Aliases'); }); return merge; } getName(node) { const { map } = this; return Object.keys(map).find(a => map[a] === node); } getNames() { return Object.keys(this.map); } getNode(name) { return this.map[name]; } newName(prefix) { if (!prefix) prefix = this.prefix; const names = Object.keys(this.map); for (let i = 1; true; ++i) { const name = `${prefix}${i}`; if (!names.includes(name)) return name; } } // During parsing, map & aliases contain CST nodes resolveNodes() { const { map, _cstAliases } = this; Object.keys(map).forEach(a => { map[a] = map[a].resolved; }); _cstAliases.forEach(a => { a.source = a.source.resolved; }); delete this._cstAliases; } setAnchor(node, name) { if (node != null && !Anchors.validAnchorNode(node)) { throw new Error('Anchors may only be set for Scalar, Seq and Map nodes'); } if (name && /[\x00-\x19\s,[\]{}]/.test(name)) { throw new Error('Anchor names must not contain whitespace or control characters'); } const { map } = this; const prev = node && Object.keys(map).find(a => map[a] === node); if (prev) { if (!name) { return prev; } else if (prev !== name) { delete map[prev]; map[name] = node; } } else { if (!name) { if (!node) return null; name = this.newName(); } map[name] = node; } return name; } } const visit = (node, tags) => { if (node && typeof node === 'object') { const { tag } = node; if (node instanceof resolveSeq.Collection) { if (tag) tags[tag] = true; node.items.forEach(n => visit(n, tags)); } else if (node instanceof resolveSeq.Pair) { visit(node.key, tags); visit(node.value, tags); } else if (node instanceof resolveSeq.Scalar) { if (tag) tags[tag] = true; } } return tags; }; const listTagNames = node => Object.keys(visit(node, {})); function parseContents(doc, contents) { const comments = { before: [], after: [] }; let body = undefined; let spaceBefore = false; for (const node of contents) { if (node.valueRange) { if (body !== undefined) { const msg = 'Document contains trailing content not separated by a ... or --- line'; doc.errors.push(new PlainValue.YAMLSyntaxError(node, msg)); break; } const res = resolveSeq.resolveNode(doc, node); if (spaceBefore) { res.spaceBefore = true; spaceBefore = false; } body = res; } else if (node.comment !== null) { const cc = body === undefined ? comments.before : comments.after; cc.push(node.comment); } else if (node.type === PlainValue.Type.BLANK_LINE) { spaceBefore = true; if (body === undefined && comments.before.length > 0 && !doc.commentBefore) { // space-separated comments at start are parsed as document comments doc.commentBefore = comments.before.join('\n'); comments.before = []; } } } doc.contents = body || null; if (!body) { doc.comment = comments.before.concat(comments.after).join('\n') || null; } else { const cb = comments.before.join('\n'); if (cb) { const cbNode = body instanceof resolveSeq.Collection && body.items[0] ? body.items[0] : body; cbNode.commentBefore = cbNode.commentBefore ? `${cb}\n${cbNode.commentBefore}` : cb; } doc.comment = comments.after.join('\n') || null; } } function resolveTagDirective({ tagPrefixes }, directive) { const [handle, prefix] = directive.parameters; if (!handle || !prefix) { const msg = 'Insufficient parameters given for %TAG directive'; throw new PlainValue.YAMLSemanticError(directive, msg); } if (tagPrefixes.some(p => p.handle === handle)) { const msg = 'The %TAG directive must only be given at most once per handle in the same document.'; throw new PlainValue.YAMLSemanticError(directive, msg); } return { handle, prefix }; } function resolveYamlDirective(doc, directive) { let [version] = directive.parameters; if (directive.name === 'YAML:1.0') version = '1.0'; if (!version) { const msg = 'Insufficient parameters given for %YAML directive'; throw new PlainValue.YAMLSemanticError(directive, msg); } if (!documentOptions[version]) { const v0 = doc.version || doc.options.version; const msg = `Document will be parsed as YAML ${v0} rather than YAML ${version}`; doc.warnings.push(new PlainValue.YAMLWarning(directive, msg)); } return version; } function parseDirectives(doc, directives, prevDoc) { const directiveComments = []; let hasDirectives = false; for (const directive of directives) { const { comment, name } = directive; switch (name) { case 'TAG': try { doc.tagPrefixes.push(resolveTagDirective(doc, directive)); } catch (error) { doc.errors.push(error); } hasDirectives = true; break; case 'YAML': case 'YAML:1.0': if (doc.version) { const msg = 'The %YAML directive must only be given at most once per document.'; doc.errors.push(new PlainValue.YAMLSemanticError(directive, msg)); } try { doc.version = resolveYamlDirective(doc, directive); } catch (error) { doc.errors.push(error); } hasDirectives = true; break; default: if (name) { const msg = `YAML only supports %TAG and %YAML directives, and not %${name}`; doc.warnings.push(new PlainValue.YAMLWarning(directive, msg)); } } if (comment) directiveComments.push(comment); } if (prevDoc && !hasDirectives && '1.1' === (doc.version || prevDoc.version || doc.options.version)) { const copyTagPrefix = ({ handle, prefix }) => ({ handle, prefix }); doc.tagPrefixes = prevDoc.tagPrefixes.map(copyTagPrefix); doc.version = prevDoc.version; } doc.commentBefore = directiveComments.join('\n') || null; } function assertCollection(contents) { if (contents instanceof resolveSeq.Collection) return true; throw new Error('Expected a YAML collection as document contents'); } class Document { constructor(options) { this.anchors = new Anchors(options.anchorPrefix); this.commentBefore = null; this.comment = null; this.contents = null; this.directivesEndMarker = null; this.errors = []; this.options = options; this.schema = null; this.tagPrefixes = []; this.version = null; this.warnings = []; } add(value) { assertCollection(this.contents); return this.contents.add(value); } addIn(path, value) { assertCollection(this.contents); this.contents.addIn(path, value); } delete(key) { assertCollection(this.contents); return this.contents.delete(key); } deleteIn(path) { if (resolveSeq.isEmptyPath(path)) { if (this.contents == null) return false; this.contents = null; return true; } assertCollection(this.contents); return this.contents.deleteIn(path); } getDefaults() { return Document.defaults[this.version] || Document.defaults[this.options.version] || {}; } get(key, keepScalar) { return this.contents instanceof resolveSeq.Collection ? this.contents.get(key, keepScalar) : undefined; } getIn(path, keepScalar) { if (resolveSeq.isEmptyPath(path)) return !keepScalar && this.contents instanceof resolveSeq.Scalar ? this.contents.value : this.contents; return this.contents instanceof resolveSeq.Collection ? this.contents.getIn(path, keepScalar) : undefined; } has(key) { return this.contents instanceof resolveSeq.Collection ? this.contents.has(key) : false; } hasIn(path) { if (resolveSeq.isEmptyPath(path)) return this.contents !== undefined; return this.contents instanceof resolveSeq.Collection ? this.contents.hasIn(path) : false; } set(key, value) { assertCollection(this.contents); this.contents.set(key, value); } setIn(path, value) { if (resolveSeq.isEmptyPath(path)) this.contents = value;else { assertCollection(this.contents); this.contents.setIn(path, value); } } setSchema(id, customTags) { if (!id && !customTags && this.schema) return; if (typeof id === 'number') id = id.toFixed(1); if (id === '1.0' || id === '1.1' || id === '1.2') { if (this.version) this.version = id;else this.options.version = id; delete this.options.schema; } else if (id && typeof id === 'string') { this.options.schema = id; } if (Array.isArray(customTags)) this.options.customTags = customTags; const opt = Object.assign({}, this.getDefaults(), this.options); this.schema = new Schema.Schema(opt); } parse(node, prevDoc) { if (this.options.keepCstNodes) this.cstNode = node; if (this.options.keepNodeTypes) this.type = 'DOCUMENT'; const { directives = [], contents = [], directivesEndMarker, error, valueRange } = node; if (error) { if (!error.source) error.source = this; this.errors.push(error); } parseDirectives(this, directives, prevDoc); if (directivesEndMarker) this.directivesEndMarker = true; this.range = valueRange ? [valueRange.start, valueRange.end] : null; this.setSchema(); this.anchors._cstAliases = []; parseContents(this, contents); this.anchors.resolveNodes(); if (this.options.prettyErrors) { for (const error of this.errors) if (error instanceof PlainValue.YAMLError) error.makePretty(); for (const warn of this.warnings) if (warn instanceof PlainValue.YAMLError) warn.makePretty(); } return this; } listNonDefaultTags() { return listTagNames(this.contents).filter(t => t.indexOf(Schema.Schema.defaultPrefix) !== 0); } setTagPrefix(handle, prefix) { if (handle[0] !== '!' || handle[handle.length - 1] !== '!') throw new Error('Handle must start and end with !'); if (prefix) { const prev = this.tagPrefixes.find(p => p.handle === handle); if (prev) prev.prefix = prefix;else this.tagPrefixes.push({ handle, prefix }); } else { this.tagPrefixes = this.tagPrefixes.filter(p => p.handle !== handle); } } toJSON(arg, onAnchor) { const { keepBlobsInJSON, mapAsMap, maxAliasCount } = this.options; const keep = keepBlobsInJSON && (typeof arg !== 'string' || !(this.contents instanceof resolveSeq.Scalar)); const ctx = { doc: this, indentStep: ' ', keep, mapAsMap: keep && !!mapAsMap, maxAliasCount, stringify // Requiring directly in Pair would create circular dependencies }; const anchorNames = Object.keys(this.anchors.map); if (anchorNames.length > 0) ctx.anchors = new Map(anchorNames.map(name => [this.anchors.map[name], { alias: [], aliasCount: 0, count: 1 }])); const res = resolveSeq.toJSON(this.contents, arg, ctx); if (typeof onAnchor === 'function' && ctx.anchors) for (const { count, res } of ctx.anchors.values()) onAnchor(res, count); return res; } toString() { if (this.errors.length > 0) throw new Error('Document with errors cannot be stringified'); const indentSize = this.options.indent; if (!Number.isInteger(indentSize) || indentSize <= 0) { const s = JSON.stringify(indentSize); throw new Error(`"indent" option must be a positive integer, not ${s}`); } this.setSchema(); const lines = []; let hasDirectives = false; if (this.version) { let vd = '%YAML 1.2'; if (this.schema.name === 'yaml-1.1') { if (this.version === '1.0') vd = '%YAML:1.0';else if (this.version === '1.1') vd = '%YAML 1.1'; } lines.push(vd); hasDirectives = true; } const tagNames = this.listNonDefaultTags(); this.tagPrefixes.forEach(({ handle, prefix }) => { if (tagNames.some(t => t.indexOf(prefix) === 0)) { lines.push(`%TAG ${handle} ${prefix}`); hasDirectives = true; } }); if (hasDirectives || this.directivesEndMarker) lines.push('---'); if (this.commentBefore) { if (hasDirectives || !this.directivesEndMarker) lines.unshift(''); lines.unshift(this.commentBefore.replace(/^/gm, '#')); } const ctx = { anchors: Object.create(null), doc: this, indent: '', indentStep: ' '.repeat(indentSize), stringify // Requiring directly in nodes would create circular dependencies }; let chompKeep = false; let contentComment = null; if (this.contents) { if (this.contents instanceof resolveSeq.Node) { if (this.contents.spaceBefore && (hasDirectives || this.directivesEndMarker)) lines.push(''); if (this.contents.commentBefore) lines.push(this.contents.commentBefore.replace(/^/gm, '#')); // top-level block scalars need to be indented if followed by a comment ctx.forceBlockIndent = !!this.comment; contentComment = this.contents.comment; } const onChompKeep = contentComment ? null : () => chompKeep = true; const body = stringify(this.contents, ctx, () => contentComment = null, onChompKeep); lines.push(resolveSeq.addComment(body, '', contentComment)); } else if (this.contents !== undefined) { lines.push(stringify(this.contents, ctx)); } if (this.comment) { if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '') lines.push(''); lines.push(this.comment.replace(/^/gm, '#')); } return lines.join('\n') + '\n'; } } PlainValue._defineProperty(Document, "defaults", documentOptions); exports.Document = Document; exports.defaultOptions = defaultOptions; exports.scalarOptions = scalarOptions; /***/ }), /***/ 51937: /***/ ((__unused_webpack_module, exports) => { "use strict"; const Char = { ANCHOR: '&', COMMENT: '#', TAG: '!', DIRECTIVES_END: '-', DOCUMENT_END: '.' }; const Type = { ALIAS: 'ALIAS', BLANK_LINE: 'BLANK_LINE', BLOCK_FOLDED: 'BLOCK_FOLDED', BLOCK_LITERAL: 'BLOCK_LITERAL', COMMENT: 'COMMENT', DIRECTIVE: 'DIRECTIVE', DOCUMENT: 'DOCUMENT', FLOW_MAP: 'FLOW_MAP', FLOW_SEQ: 'FLOW_SEQ', MAP: 'MAP', MAP_KEY: 'MAP_KEY', MAP_VALUE: 'MAP_VALUE', PLAIN: 'PLAIN', QUOTE_DOUBLE: 'QUOTE_DOUBLE', QUOTE_SINGLE: 'QUOTE_SINGLE', SEQ: 'SEQ', SEQ_ITEM: 'SEQ_ITEM' }; const defaultTagPrefix = 'tag:yaml.org,2002:'; const defaultTags = { MAP: 'tag:yaml.org,2002:map', SEQ: 'tag:yaml.org,2002:seq', STR: 'tag:yaml.org,2002:str' }; function findLineStarts(src) { const ls = [0]; let offset = src.indexOf('\n'); while (offset !== -1) { offset += 1; ls.push(offset); offset = src.indexOf('\n', offset); } return ls; } function getSrcInfo(cst) { let lineStarts, src; if (typeof cst === 'string') { lineStarts = findLineStarts(cst); src = cst; } else { if (Array.isArray(cst)) cst = cst[0]; if (cst && cst.context) { if (!cst.lineStarts) cst.lineStarts = findLineStarts(cst.context.src); lineStarts = cst.lineStarts; src = cst.context.src; } } return { lineStarts, src }; } /** * @typedef {Object} LinePos - One-indexed position in the source * @property {number} line * @property {number} col */ /** * Determine the line/col position matching a character offset. * * Accepts a source string or a CST document as the second parameter. With * the latter, starting indices for lines are cached in the document as * `lineStarts: number[]`. * * Returns a one-indexed `{ line, col }` location if found, or * `undefined` otherwise. * * @param {number} offset * @param {string|Document|Document[]} cst * @returns {?LinePos} */ function getLinePos(offset, cst) { if (typeof offset !== 'number' || offset < 0) return null; const { lineStarts, src } = getSrcInfo(cst); if (!lineStarts || !src || offset > src.length) return null; for (let i = 0; i < lineStarts.length; ++i) { const start = lineStarts[i]; if (offset < start) { return { line: i, col: offset - lineStarts[i - 1] + 1 }; } if (offset === start) return { line: i + 1, col: 1 }; } const line = lineStarts.length; return { line, col: offset - lineStarts[line - 1] + 1 }; } /** * Get a specified line from the source. * * Accepts a source string or a CST document as the second parameter. With * the latter, starting indices for lines are cached in the document as * `lineStarts: number[]`. * * Returns the line as a string if found, or `null` otherwise. * * @param {number} line One-indexed line number * @param {string|Document|Document[]} cst * @returns {?string} */ function getLine(line, cst) { const { lineStarts, src } = getSrcInfo(cst); if (!lineStarts || !(line >= 1) || line > lineStarts.length) return null; const start = lineStarts[line - 1]; let end = lineStarts[line]; // undefined for last line; that's ok for slice() while (end && end > start && src[end - 1] === '\n') --end; return src.slice(start, end); } /** * Pretty-print the starting line from the source indicated by the range `pos` * * Trims output to `maxWidth` chars while keeping the starting column visible, * using `…` at either end to indicate dropped characters. * * Returns a two-line string (or `null`) with `\n` as separator; the second line * will hold appropriately indented `^` marks indicating the column range. * * @param {Object} pos * @param {LinePos} pos.start * @param {LinePos} [pos.end] * @param {string|Document|Document[]*} cst * @param {number} [maxWidth=80] * @returns {?string} */ function getPrettyContext({ start, end }, cst, maxWidth = 80) { let src = getLine(start.line, cst); if (!src) return null; let { col } = start; if (src.length > maxWidth) { if (col <= maxWidth - 10) { src = src.substr(0, maxWidth - 1) + '…'; } else { const halfWidth = Math.round(maxWidth / 2); if (src.length > col + halfWidth) src = src.substr(0, col + halfWidth - 1) + '…'; col -= src.length - maxWidth; src = '…' + src.substr(1 - maxWidth); } } let errLen = 1; let errEnd = ''; if (end) { if (end.line === start.line && col + (end.col - start.col) <= maxWidth + 1) { errLen = end.col - start.col; } else { errLen = Math.min(src.length + 1, maxWidth) - col; errEnd = '…'; } } const offset = col > 1 ? ' '.repeat(col - 1) : ''; const err = '^'.repeat(errLen); return `${src}\n${offset}${err}${errEnd}`; } class Range { static copy(orig) { return new Range(orig.start, orig.end); } constructor(start, end) { this.start = start; this.end = end || start; } isEmpty() { return typeof this.start !== 'number' || !this.end || this.end <= this.start; } /** * Set `origStart` and `origEnd` to point to the original source range for * this node, which may differ due to dropped CR characters. * * @param {number[]} cr - Positions of dropped CR characters * @param {number} offset - Starting index of `cr` from the last call * @returns {number} - The next offset, matching the one found for `origStart` */ setOrigRange(cr, offset) { const { start, end } = this; if (cr.length === 0 || end <= cr[0]) { this.origStart = start; this.origEnd = end; return offset; } let i = offset; while (i < cr.length) { if (cr[i] > start) break;else ++i; } this.origStart = start + i; const nextOffset = i; while (i < cr.length) { // if end was at \n, it should now be at \r if (cr[i] >= end) break;else ++i; } this.origEnd = end + i; return nextOffset; } } /** Root class of all nodes */ class Node { static addStringTerminator(src, offset, str) { if (str[str.length - 1] === '\n') return str; const next = Node.endOfWhiteSpace(src, offset); return next >= src.length || src[next] === '\n' ? str + '\n' : str; } // ^(---|...) static atDocumentBoundary(src, offset, sep) { const ch0 = src[offset]; if (!ch0) return true; const prev = src[offset - 1]; if (prev && prev !== '\n') return false; if (sep) { if (ch0 !== sep) return false; } else { if (ch0 !== Char.DIRECTIVES_END && ch0 !== Char.DOCUMENT_END) return false; } const ch1 = src[offset + 1]; const ch2 = src[offset + 2]; if (ch1 !== ch0 || ch2 !== ch0) return false; const ch3 = src[offset + 3]; return !ch3 || ch3 === '\n' || ch3 === '\t' || ch3 === ' '; } static endOfIdentifier(src, offset) { let ch = src[offset]; const isVerbatim = ch === '<'; const notOk = isVerbatim ? ['\n', '\t', ' ', '>'] : ['\n', '\t', ' ', '[', ']', '{', '}', ',']; while (ch && notOk.indexOf(ch) === -1) ch = src[offset += 1]; if (isVerbatim && ch === '>') offset += 1; return offset; } static endOfIndent(src, offset) { let ch = src[offset]; while (ch === ' ') ch = src[offset += 1]; return offset; } static endOfLine(src, offset) { let ch = src[offset]; while (ch && ch !== '\n') ch = src[offset += 1]; return offset; } static endOfWhiteSpace(src, offset) { let ch = src[offset]; while (ch === '\t' || ch === ' ') ch = src[offset += 1]; return offset; } static startOfLine(src, offset) { let ch = src[offset - 1]; if (ch === '\n') return offset; while (ch && ch !== '\n') ch = src[offset -= 1]; return offset + 1; } /** * End of indentation, or null if the line's indent level is not more * than `indent` * * @param {string} src * @param {number} indent * @param {number} lineStart * @returns {?number} */ static endOfBlockIndent(src, indent, lineStart) { const inEnd = Node.endOfIndent(src, lineStart); if (inEnd > lineStart + indent) { return inEnd; } else { const wsEnd = Node.endOfWhiteSpace(src, inEnd); const ch = src[wsEnd]; if (!ch || ch === '\n') return wsEnd; } return null; } static atBlank(src, offset, endAsBlank) { const ch = src[offset]; return ch === '\n' || ch === '\t' || ch === ' ' || endAsBlank && !ch; } static nextNodeIsIndented(ch, indentDiff, indicatorAsIndent) { if (!ch || indentDiff < 0) return false; if (indentDiff > 0) return true; return indicatorAsIndent && ch === '-'; } // should be at line or string end, or at next non-whitespace char static normalizeOffset(src, offset) { const ch = src[offset]; return !ch ? offset : ch !== '\n' && src[offset - 1] === '\n' ? offset - 1 : Node.endOfWhiteSpace(src, offset); } // fold single newline into space, multiple newlines to N - 1 newlines // presumes src[offset] === '\n' static foldNewline(src, offset, indent) { let inCount = 0; let error = false; let fold = ''; let ch = src[offset + 1]; while (ch === ' ' || ch === '\t' || ch === '\n') { switch (ch) { case '\n': inCount = 0; offset += 1; fold += '\n'; break; case '\t': if (inCount <= indent) error = true; offset = Node.endOfWhiteSpace(src, offset + 2) - 1; break; case ' ': inCount += 1; offset += 1; break; } ch = src[offset + 1]; } if (!fold) fold = ' '; if (ch && inCount <= indent) error = true; return { fold, offset, error }; } constructor(type, props, context) { Object.defineProperty(this, 'context', { value: context || null, writable: true }); this.error = null; this.range = null; this.valueRange = null; this.props = props || []; this.type = type; this.value = null; } getPropValue(idx, key, skipKey) { if (!this.context) return null; const { src } = this.context; const prop = this.props[idx]; return prop && src[prop.start] === key ? src.slice(prop.start + (skipKey ? 1 : 0), prop.end) : null; } get anchor() { for (let i = 0; i < this.props.length; ++i) { const anchor = this.getPropValue(i, Char.ANCHOR, true); if (anchor != null) return anchor; } return null; } get comment() { const comments = []; for (let i = 0; i < this.props.length; ++i) { const comment = this.getPropValue(i, Char.COMMENT, true); if (comment != null) comments.push(comment); } return comments.length > 0 ? comments.join('\n') : null; } commentHasRequiredWhitespace(start) { const { src } = this.context; if (this.header && start === this.header.end) return false; if (!this.valueRange) return false; const { end } = this.valueRange; return start !== end || Node.atBlank(src, end - 1); } get hasComment() { if (this.context) { const { src } = this.context; for (let i = 0; i < this.props.length; ++i) { if (src[this.props[i].start] === Char.COMMENT) return true; } } return false; } get hasProps() { if (this.context) { const { src } = this.context; for (let i = 0; i < this.props.length; ++i) { if (src[this.props[i].start] !== Char.COMMENT) return true; } } return false; } get includesTrailingLines() { return false; } get jsonLike() { const jsonLikeTypes = [Type.FLOW_MAP, Type.FLOW_SEQ, Type.QUOTE_DOUBLE, Type.QUOTE_SINGLE]; return jsonLikeTypes.indexOf(this.type) !== -1; } get rangeAsLinePos() { if (!this.range || !this.context) return undefined; const start = getLinePos(this.range.start, this.context.root); if (!start) return undefined; const end = getLinePos(this.range.end, this.context.root); return { start, end }; } get rawValue() { if (!this.valueRange || !this.context) return null; const { start, end } = this.valueRange; return this.context.src.slice(start, end); } get tag() { for (let i = 0; i < this.props.length; ++i) { const tag = this.getPropValue(i, Char.TAG, false); if (tag != null) { if (tag[1] === '<') { return { verbatim: tag.slice(2, -1) }; } else { // eslint-disable-next-line no-unused-vars const [_, handle, suffix] = tag.match(/^(.*!)([^!]*)$/); return { handle, suffix }; } } } return null; } get valueRangeContainsNewline() { if (!this.valueRange || !this.context) return false; const { start, end } = this.valueRange; const { src } = this.context; for (let i = start; i < end; ++i) { if (src[i] === '\n') return true; } return false; } parseComment(start) { const { src } = this.context; if (src[start] === Char.COMMENT) { const end = Node.endOfLine(src, start + 1); const commentRange = new Range(start, end); this.props.push(commentRange); return end; } return start; } /** * Populates the `origStart` and `origEnd` values of all ranges for this * node. Extended by child classes to handle descendant nodes. * * @param {number[]} cr - Positions of dropped CR characters * @param {number} offset - Starting index of `cr` from the last call * @returns {number} - The next offset, matching the one found for `origStart` */ setOrigRanges(cr, offset) { if (this.range) offset = this.range.setOrigRange(cr, offset); if (this.valueRange) this.valueRange.setOrigRange(cr, offset); this.props.forEach(prop => prop.setOrigRange(cr, offset)); return offset; } toString() { const { context: { src }, range, value } = this; if (value != null) return value; const str = src.slice(range.start, range.end); return Node.addStringTerminator(src, range.end, str); } } class YAMLError extends Error { constructor(name, source, message) { if (!message || !(source instanceof Node)) throw new Error(`Invalid arguments for new ${name}`); super(); this.name = name; this.message = message; this.source = source; } makePretty() { if (!this.source) return; this.nodeType = this.source.type; const cst = this.source.context && this.source.context.root; if (typeof this.offset === 'number') { this.range = new Range(this.offset, this.offset + 1); const start = cst && getLinePos(this.offset, cst); if (start) { const end = { line: start.line, col: start.col + 1 }; this.linePos = { start, end }; } delete this.offset; } else { this.range = this.source.range; this.linePos = this.source.rangeAsLinePos; } if (this.linePos) { const { line, col } = this.linePos.start; this.message += ` at line ${line}, column ${col}`; const ctx = cst && getPrettyContext(this.linePos, cst); if (ctx) this.message += `:\n\n${ctx}\n`; } delete this.source; } } class YAMLReferenceError extends YAMLError { constructor(source, message) { super('YAMLReferenceError', source, message); } } class YAMLSemanticError extends YAMLError { constructor(source, message) { super('YAMLSemanticError', source, message); } } class YAMLSyntaxError extends YAMLError { constructor(source, message) { super('YAMLSyntaxError', source, message); } } class YAMLWarning extends YAMLError { constructor(source, message) { super('YAMLWarning', source, message); } } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } class PlainValue extends Node { static endOfLine(src, start, inFlow) { let ch = src[start]; let offset = start; while (ch && ch !== '\n') { if (inFlow && (ch === '[' || ch === ']' || ch === '{' || ch === '}' || ch === ',')) break; const next = src[offset + 1]; if (ch === ':' && (!next || next === '\n' || next === '\t' || next === ' ' || inFlow && next === ',')) break; if ((ch === ' ' || ch === '\t') && next === '#') break; offset += 1; ch = next; } return offset; } get strValue() { if (!this.valueRange || !this.context) return null; let { start, end } = this.valueRange; const { src } = this.context; let ch = src[end - 1]; while (start < end && (ch === '\n' || ch === '\t' || ch === ' ')) ch = src[--end - 1]; let str = ''; for (let i = start; i < end; ++i) { const ch = src[i]; if (ch === '\n') { const { fold, offset } = Node.foldNewline(src, i, -1); str += fold; i = offset; } else if (ch === ' ' || ch === '\t') { // trim trailing whitespace const wsStart = i; let next = src[i + 1]; while (i < end && (next === ' ' || next === '\t')) { i += 1; next = src[i + 1]; } if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch; } else { str += ch; } } const ch0 = src[start]; switch (ch0) { case '\t': { const msg = 'Plain value cannot start with a tab character'; const errors = [new YAMLSemanticError(this, msg)]; return { errors, str }; } case '@': case '`': { const msg = `Plain value cannot start with reserved character ${ch0}`; const errors = [new YAMLSemanticError(this, msg)]; return { errors, str }; } default: return str; } } parseBlockValue(start) { const { indent, inFlow, src } = this.context; let offset = start; let valueEnd = start; for (let ch = src[offset]; ch === '\n'; ch = src[offset]) { if (Node.atDocumentBoundary(src, offset + 1)) break; const end = Node.endOfBlockIndent(src, indent, offset + 1); if (end === null || src[end] === '#') break; if (src[end] === '\n') { offset = end; } else { valueEnd = PlainValue.endOfLine(src, end, inFlow); offset = valueEnd; } } if (this.valueRange.isEmpty()) this.valueRange.start = start; this.valueRange.end = valueEnd; return valueEnd; } /** * Parses a plain value from the source * * Accepted forms are: * ``` * #comment * * first line * * first line #comment * * first line * block * lines * * #comment * block * lines * ``` * where block lines are empty or have an indent level greater than `indent`. * * @param {ParseContext} context * @param {number} start - Index of first character * @returns {number} - Index of the character after this scalar, may be `\n` */ parse(context, start) { this.context = context; const { inFlow, src } = context; let offset = start; const ch = src[offset]; if (ch && ch !== '#' && ch !== '\n') { offset = PlainValue.endOfLine(src, start, inFlow); } this.valueRange = new Range(start, offset); offset = Node.endOfWhiteSpace(src, offset); offset = this.parseComment(offset); if (!this.hasComment || this.valueRange.isEmpty()) { offset = this.parseBlockValue(offset); } return offset; } } exports.Char = Char; exports.Node = Node; exports.PlainValue = PlainValue; exports.Range = Range; exports.Type = Type; exports.YAMLError = YAMLError; exports.YAMLReferenceError = YAMLReferenceError; exports.YAMLSemanticError = YAMLSemanticError; exports.YAMLSyntaxError = YAMLSyntaxError; exports.YAMLWarning = YAMLWarning; exports._defineProperty = _defineProperty; exports.defaultTagPrefix = defaultTagPrefix; exports.defaultTags = defaultTags; /***/ }), /***/ 5533: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var PlainValue = __webpack_require__(51937); var resolveSeq = __webpack_require__(63970); var warnings = __webpack_require__(1758); function createMap(schema, obj, ctx) { const map = new resolveSeq.YAMLMap(schema); if (obj instanceof Map) { for (const [key, value] of obj) map.items.push(schema.createPair(key, value, ctx)); } else if (obj && typeof obj === 'object') { for (const key of Object.keys(obj)) map.items.push(schema.createPair(key, obj[key], ctx)); } if (typeof schema.sortMapEntries === 'function') { map.items.sort(schema.sortMapEntries); } return map; } const map = { createNode: createMap, default: true, nodeClass: resolveSeq.YAMLMap, tag: 'tag:yaml.org,2002:map', resolve: resolveSeq.resolveMap }; function createSeq(schema, obj, ctx) { const seq = new resolveSeq.YAMLSeq(schema); if (obj && obj[Symbol.iterator]) { for (const it of obj) { const v = schema.createNode(it, ctx.wrapScalars, null, ctx); seq.items.push(v); } } return seq; } const seq = { createNode: createSeq, default: true, nodeClass: resolveSeq.YAMLSeq, tag: 'tag:yaml.org,2002:seq', resolve: resolveSeq.resolveSeq }; const string = { identify: value => typeof value === 'string', default: true, tag: 'tag:yaml.org,2002:str', resolve: resolveSeq.resolveString, stringify(item, ctx, onComment, onChompKeep) { ctx = Object.assign({ actualString: true }, ctx); return resolveSeq.stringifyString(item, ctx, onComment, onChompKeep); }, options: resolveSeq.strOptions }; const failsafe = [map, seq, string]; /* global BigInt */ const intIdentify$2 = value => typeof value === 'bigint' || Number.isInteger(value); const intResolve$1 = (src, part, radix) => resolveSeq.intOptions.asBigInt ? BigInt(src) : parseInt(part, radix); function intStringify$1(node, radix, prefix) { const { value } = node; if (intIdentify$2(value) && value >= 0) return prefix + value.toString(radix); return resolveSeq.stringifyNumber(node); } const nullObj = { identify: value => value == null, createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq.Scalar(null) : null, default: true, tag: 'tag:yaml.org,2002:null', test: /^(?:~|[Nn]ull|NULL)?$/, resolve: () => null, options: resolveSeq.nullOptions, stringify: () => resolveSeq.nullOptions.nullStr }; const boolObj = { identify: value => typeof value === 'boolean', default: true, tag: 'tag:yaml.org,2002:bool', test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, resolve: str => str[0] === 't' || str[0] === 'T', options: resolveSeq.boolOptions, stringify: ({ value }) => value ? resolveSeq.boolOptions.trueStr : resolveSeq.boolOptions.falseStr }; const octObj = { identify: value => intIdentify$2(value) && value >= 0, default: true, tag: 'tag:yaml.org,2002:int', format: 'OCT', test: /^0o([0-7]+)$/, resolve: (str, oct) => intResolve$1(str, oct, 8), options: resolveSeq.intOptions, stringify: node => intStringify$1(node, 8, '0o') }; const intObj = { identify: intIdentify$2, default: true, tag: 'tag:yaml.org,2002:int', test: /^[-+]?[0-9]+$/, resolve: str => intResolve$1(str, str, 10), options: resolveSeq.intOptions, stringify: resolveSeq.stringifyNumber }; const hexObj = { identify: value => intIdentify$2(value) && value >= 0, default: true, tag: 'tag:yaml.org,2002:int', format: 'HEX', test: /^0x([0-9a-fA-F]+)$/, resolve: (str, hex) => intResolve$1(str, hex, 16), options: resolveSeq.intOptions, stringify: node => intStringify$1(node, 16, '0x') }; const nanObj = { identify: value => typeof value === 'number', default: true, tag: 'tag:yaml.org,2002:float', test: /^(?:[-+]?\.inf|(\.nan))$/i, resolve: (str, nan) => nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, stringify: resolveSeq.stringifyNumber }; const expObj = { identify: value => typeof value === 'number', default: true, tag: 'tag:yaml.org,2002:float', format: 'EXP', test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, resolve: str => parseFloat(str), stringify: ({ value }) => Number(value).toExponential() }; const floatObj = { identify: value => typeof value === 'number', default: true, tag: 'tag:yaml.org,2002:float', test: /^[-+]?(?:\.([0-9]+)|[0-9]+\.([0-9]*))$/, resolve(str, frac1, frac2) { const frac = frac1 || frac2; const node = new resolveSeq.Scalar(parseFloat(str)); if (frac && frac[frac.length - 1] === '0') node.minFractionDigits = frac.length; return node; }, stringify: resolveSeq.stringifyNumber }; const core = failsafe.concat([nullObj, boolObj, octObj, intObj, hexObj, nanObj, expObj, floatObj]); /* global BigInt */ const intIdentify$1 = value => typeof value === 'bigint' || Number.isInteger(value); const stringifyJSON = ({ value }) => JSON.stringify(value); const json = [map, seq, { identify: value => typeof value === 'string', default: true, tag: 'tag:yaml.org,2002:str', resolve: resolveSeq.resolveString, stringify: stringifyJSON }, { identify: value => value == null, createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq.Scalar(null) : null, default: true, tag: 'tag:yaml.org,2002:null', test: /^null$/, resolve: () => null, stringify: stringifyJSON }, { identify: value => typeof value === 'boolean', default: true, tag: 'tag:yaml.org,2002:bool', test: /^true|false$/, resolve: str => str === 'true', stringify: stringifyJSON }, { identify: intIdentify$1, default: true, tag: 'tag:yaml.org,2002:int', test: /^-?(?:0|[1-9][0-9]*)$/, resolve: str => resolveSeq.intOptions.asBigInt ? BigInt(str) : parseInt(str, 10), stringify: ({ value }) => intIdentify$1(value) ? value.toString() : JSON.stringify(value) }, { identify: value => typeof value === 'number', default: true, tag: 'tag:yaml.org,2002:float', test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, resolve: str => parseFloat(str), stringify: stringifyJSON }]; json.scalarFallback = str => { throw new SyntaxError(`Unresolved plain scalar ${JSON.stringify(str)}`); }; /* global BigInt */ const boolStringify = ({ value }) => value ? resolveSeq.boolOptions.trueStr : resolveSeq.boolOptions.falseStr; const intIdentify = value => typeof value === 'bigint' || Number.isInteger(value); function intResolve(sign, src, radix) { let str = src.replace(/_/g, ''); if (resolveSeq.intOptions.asBigInt) { switch (radix) { case 2: str = `0b${str}`; break; case 8: str = `0o${str}`; break; case 16: str = `0x${str}`; break; } const n = BigInt(str); return sign === '-' ? BigInt(-1) * n : n; } const n = parseInt(str, radix); return sign === '-' ? -1 * n : n; } function intStringify(node, radix, prefix) { const { value } = node; if (intIdentify(value)) { const str = value.toString(radix); return value < 0 ? '-' + prefix + str.substr(1) : prefix + str; } return resolveSeq.stringifyNumber(node); } const yaml11 = failsafe.concat([{ identify: value => value == null, createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq.Scalar(null) : null, default: true, tag: 'tag:yaml.org,2002:null', test: /^(?:~|[Nn]ull|NULL)?$/, resolve: () => null, options: resolveSeq.nullOptions, stringify: () => resolveSeq.nullOptions.nullStr }, { identify: value => typeof value === 'boolean', default: true, tag: 'tag:yaml.org,2002:bool', test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, resolve: () => true, options: resolveSeq.boolOptions, stringify: boolStringify }, { identify: value => typeof value === 'boolean', default: true, tag: 'tag:yaml.org,2002:bool', test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i, resolve: () => false, options: resolveSeq.boolOptions, stringify: boolStringify }, { identify: intIdentify, default: true, tag: 'tag:yaml.org,2002:int', format: 'BIN', test: /^([-+]?)0b([0-1_]+)$/, resolve: (str, sign, bin) => intResolve(sign, bin, 2), stringify: node => intStringify(node, 2, '0b') }, { identify: intIdentify, default: true, tag: 'tag:yaml.org,2002:int', format: 'OCT', test: /^([-+]?)0([0-7_]+)$/, resolve: (str, sign, oct) => intResolve(sign, oct, 8), stringify: node => intStringify(node, 8, '0') }, { identify: intIdentify, default: true, tag: 'tag:yaml.org,2002:int', test: /^([-+]?)([0-9][0-9_]*)$/, resolve: (str, sign, abs) => intResolve(sign, abs, 10), stringify: resolveSeq.stringifyNumber }, { identify: intIdentify, default: true, tag: 'tag:yaml.org,2002:int', format: 'HEX', test: /^([-+]?)0x([0-9a-fA-F_]+)$/, resolve: (str, sign, hex) => intResolve(sign, hex, 16), stringify: node => intStringify(node, 16, '0x') }, { identify: value => typeof value === 'number', default: true, tag: 'tag:yaml.org,2002:float', test: /^(?:[-+]?\.inf|(\.nan))$/i, resolve: (str, nan) => nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, stringify: resolveSeq.stringifyNumber }, { identify: value => typeof value === 'number', default: true, tag: 'tag:yaml.org,2002:float', format: 'EXP', test: /^[-+]?([0-9][0-9_]*)?(\.[0-9_]*)?[eE][-+]?[0-9]+$/, resolve: str => parseFloat(str.replace(/_/g, '')), stringify: ({ value }) => Number(value).toExponential() }, { identify: value => typeof value === 'number', default: true, tag: 'tag:yaml.org,2002:float', test: /^[-+]?(?:[0-9][0-9_]*)?\.([0-9_]*)$/, resolve(str, frac) { const node = new resolveSeq.Scalar(parseFloat(str.replace(/_/g, ''))); if (frac) { const f = frac.replace(/_/g, ''); if (f[f.length - 1] === '0') node.minFractionDigits = f.length; } return node; }, stringify: resolveSeq.stringifyNumber }], warnings.binary, warnings.omap, warnings.pairs, warnings.set, warnings.intTime, warnings.floatTime, warnings.timestamp); const schemas = { core, failsafe, json, yaml11 }; const tags = { binary: warnings.binary, bool: boolObj, float: floatObj, floatExp: expObj, floatNaN: nanObj, floatTime: warnings.floatTime, int: intObj, intHex: hexObj, intOct: octObj, intTime: warnings.intTime, map, null: nullObj, omap: warnings.omap, pairs: warnings.pairs, seq, set: warnings.set, timestamp: warnings.timestamp }; function findTagObject(value, tagName, tags) { if (tagName) { const match = tags.filter(t => t.tag === tagName); const tagObj = match.find(t => !t.format) || match[0]; if (!tagObj) throw new Error(`Tag ${tagName} not found`); return tagObj; } // TODO: deprecate/remove class check return tags.find(t => (t.identify && t.identify(value) || t.class && value instanceof t.class) && !t.format); } function createNode(value, tagName, ctx) { if (value instanceof resolveSeq.Node) return value; const { defaultPrefix, onTagObj, prevObjects, schema, wrapScalars } = ctx; if (tagName && tagName.startsWith('!!')) tagName = defaultPrefix + tagName.slice(2); let tagObj = findTagObject(value, tagName, schema.tags); if (!tagObj) { if (typeof value.toJSON === 'function') value = value.toJSON(); if (!value || typeof value !== 'object') return wrapScalars ? new resolveSeq.Scalar(value) : value; tagObj = value instanceof Map ? map : value[Symbol.iterator] ? seq : map; } if (onTagObj) { onTagObj(tagObj); delete ctx.onTagObj; } // Detect duplicate references to the same object & use Alias nodes for all // after first. The `obj` wrapper allows for circular references to resolve. const obj = { value: undefined, node: undefined }; if (value && typeof value === 'object' && prevObjects) { const prev = prevObjects.get(value); if (prev) { const alias = new resolveSeq.Alias(prev); // leaves source dirty; must be cleaned by caller ctx.aliasNodes.push(alias); // defined along with prevObjects return alias; } obj.value = value; prevObjects.set(value, obj); } obj.node = tagObj.createNode ? tagObj.createNode(ctx.schema, value, ctx) : wrapScalars ? new resolveSeq.Scalar(value) : value; if (tagName && obj.node instanceof resolveSeq.Node) obj.node.tag = tagName; return obj.node; } function getSchemaTags(schemas, knownTags, customTags, schemaId) { let tags = schemas[schemaId.replace(/\W/g, '')]; // 'yaml-1.1' -> 'yaml11' if (!tags) { const keys = Object.keys(schemas).map(key => JSON.stringify(key)).join(', '); throw new Error(`Unknown schema "${schemaId}"; use one of ${keys}`); } if (Array.isArray(customTags)) { for (const tag of customTags) tags = tags.concat(tag); } else if (typeof customTags === 'function') { tags = customTags(tags.slice()); } for (let i = 0; i < tags.length; ++i) { const tag = tags[i]; if (typeof tag === 'string') { const tagObj = knownTags[tag]; if (!tagObj) { const keys = Object.keys(knownTags).map(key => JSON.stringify(key)).join(', '); throw new Error(`Unknown custom tag "${tag}"; use one of ${keys}`); } tags[i] = tagObj; } } return tags; } const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; class Schema { // TODO: remove in v2 // TODO: remove in v2 constructor({ customTags, merge, schema, sortMapEntries, tags: deprecatedCustomTags }) { this.merge = !!merge; this.name = schema; this.sortMapEntries = sortMapEntries === true ? sortMapEntriesByKey : sortMapEntries || null; if (!customTags && deprecatedCustomTags) warnings.warnOptionDeprecation('tags', 'customTags'); this.tags = getSchemaTags(schemas, tags, customTags || deprecatedCustomTags, schema); } createNode(value, wrapScalars, tagName, ctx) { const baseCtx = { defaultPrefix: Schema.defaultPrefix, schema: this, wrapScalars }; const createCtx = ctx ? Object.assign(ctx, baseCtx) : baseCtx; return createNode(value, tagName, createCtx); } createPair(key, value, ctx) { if (!ctx) ctx = { wrapScalars: true }; const k = this.createNode(key, ctx.wrapScalars, null, ctx); const v = this.createNode(value, ctx.wrapScalars, null, ctx); return new resolveSeq.Pair(k, v); } } PlainValue._defineProperty(Schema, "defaultPrefix", PlainValue.defaultTagPrefix); PlainValue._defineProperty(Schema, "defaultTags", PlainValue.defaultTags); exports.Schema = Schema; /***/ }), /***/ 93419: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var parseCst = __webpack_require__(39720); var Document$1 = __webpack_require__(53966); var Schema = __webpack_require__(5533); var PlainValue = __webpack_require__(51937); var warnings = __webpack_require__(1758); __webpack_require__(63970); function createNode(value, wrapScalars = true, tag) { if (tag === undefined && typeof wrapScalars === 'string') { tag = wrapScalars; wrapScalars = true; } const options = Object.assign({}, Document$1.Document.defaults[Document$1.defaultOptions.version], Document$1.defaultOptions); const schema = new Schema.Schema(options); return schema.createNode(value, wrapScalars, tag); } class Document extends Document$1.Document { constructor(options) { super(Object.assign({}, Document$1.defaultOptions, options)); } } function parseAllDocuments(src, options) { const stream = []; let prev; for (const cstDoc of parseCst.parse(src)) { const doc = new Document(options); doc.parse(cstDoc, prev); stream.push(doc); prev = doc; } return stream; } function parseDocument(src, options) { const cst = parseCst.parse(src); const doc = new Document(options).parse(cst[0]); if (cst.length > 1) { const errMsg = 'Source contains multiple documents; please use YAML.parseAllDocuments()'; doc.errors.unshift(new PlainValue.YAMLSemanticError(cst[1], errMsg)); } return doc; } function parse(src, options) { const doc = parseDocument(src, options); doc.warnings.forEach(warning => warnings.warn(warning)); if (doc.errors.length > 0) throw doc.errors[0]; return doc.toJSON(); } function stringify(value, options) { const doc = new Document(options); doc.contents = value; return String(doc); } const YAML = { createNode, defaultOptions: Document$1.defaultOptions, Document, parse, parseAllDocuments, parseCST: parseCst.parse, parseDocument, scalarOptions: Document$1.scalarOptions, stringify }; exports.YAML = YAML; /***/ }), /***/ 39720: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var PlainValue = __webpack_require__(51937); class BlankLine extends PlainValue.Node { constructor() { super(PlainValue.Type.BLANK_LINE); } /* istanbul ignore next */ get includesTrailingLines() { // This is never called from anywhere, but if it were, // this is the value it should return. return true; } /** * Parses a blank line from the source * * @param {ParseContext} context * @param {number} start - Index of first \n character * @returns {number} - Index of the character after this */ parse(context, start) { this.context = context; this.range = new PlainValue.Range(start, start + 1); return start + 1; } } class CollectionItem extends PlainValue.Node { constructor(type, props) { super(type, props); this.node = null; } get includesTrailingLines() { return !!this.node && this.node.includesTrailingLines; } /** * @param {ParseContext} context * @param {number} start - Index of first character * @returns {number} - Index of the character after this */ parse(context, start) { this.context = context; const { parseNode, src } = context; let { atLineStart, lineStart } = context; if (!atLineStart && this.type === PlainValue.Type.SEQ_ITEM) this.error = new PlainValue.YAMLSemanticError(this, 'Sequence items must not have preceding content on the same line'); const indent = atLineStart ? start - lineStart : context.indent; let offset = PlainValue.Node.endOfWhiteSpace(src, start + 1); let ch = src[offset]; const inlineComment = ch === '#'; const comments = []; let blankLine = null; while (ch === '\n' || ch === '#') { if (ch === '#') { const end = PlainValue.Node.endOfLine(src, offset + 1); comments.push(new PlainValue.Range(offset, end)); offset = end; } else { atLineStart = true; lineStart = offset + 1; const wsEnd = PlainValue.Node.endOfWhiteSpace(src, lineStart); if (src[wsEnd] === '\n' && comments.length === 0) { blankLine = new BlankLine(); lineStart = blankLine.parse({ src }, lineStart); } offset = PlainValue.Node.endOfIndent(src, lineStart); } ch = src[offset]; } if (PlainValue.Node.nextNodeIsIndented(ch, offset - (lineStart + indent), this.type !== PlainValue.Type.SEQ_ITEM)) { this.node = parseNode({ atLineStart, inCollection: false, indent, lineStart, parent: this }, offset); } else if (ch && lineStart > start + 1) { offset = lineStart - 1; } if (this.node) { if (blankLine) { // Only blank lines preceding non-empty nodes are captured. Note that // this means that collection item range start indices do not always // increase monotonically. -- eemeli/yaml#126 const items = context.parent.items || context.parent.contents; if (items) items.push(blankLine); } if (comments.length) Array.prototype.push.apply(this.props, comments); offset = this.node.range.end; } else { if (inlineComment) { const c = comments[0]; this.props.push(c); offset = c.end; } else { offset = PlainValue.Node.endOfLine(src, start + 1); } } const end = this.node ? this.node.valueRange.end : offset; this.valueRange = new PlainValue.Range(start, end); return offset; } setOrigRanges(cr, offset) { offset = super.setOrigRanges(cr, offset); return this.node ? this.node.setOrigRanges(cr, offset) : offset; } toString() { const { context: { src }, node, range, value } = this; if (value != null) return value; const str = node ? src.slice(range.start, node.range.start) + String(node) : src.slice(range.start, range.end); return PlainValue.Node.addStringTerminator(src, range.end, str); } } class Comment extends PlainValue.Node { constructor() { super(PlainValue.Type.COMMENT); } /** * Parses a comment line from the source * * @param {ParseContext} context * @param {number} start - Index of first character * @returns {number} - Index of the character after this scalar */ parse(context, start) { this.context = context; const offset = this.parseComment(start); this.range = new PlainValue.Range(start, offset); return offset; } } function grabCollectionEndComments(node) { let cnode = node; while (cnode instanceof CollectionItem) cnode = cnode.node; if (!(cnode instanceof Collection)) return null; const len = cnode.items.length; let ci = -1; for (let i = len - 1; i >= 0; --i) { const n = cnode.items[i]; if (n.type === PlainValue.Type.COMMENT) { // Keep sufficiently indented comments with preceding node const { indent, lineStart } = n.context; if (indent > 0 && n.range.start >= lineStart + indent) break; ci = i; } else if (n.type === PlainValue.Type.BLANK_LINE) ci = i;else break; } if (ci === -1) return null; const ca = cnode.items.splice(ci, len - ci); const prevEnd = ca[0].range.start; while (true) { cnode.range.end = prevEnd; if (cnode.valueRange && cnode.valueRange.end > prevEnd) cnode.valueRange.end = prevEnd; if (cnode === node) break; cnode = cnode.context.parent; } return ca; } class Collection extends PlainValue.Node { static nextContentHasIndent(src, offset, indent) { const lineStart = PlainValue.Node.endOfLine(src, offset) + 1; offset = PlainValue.Node.endOfWhiteSpace(src, lineStart); const ch = src[offset]; if (!ch) return false; if (offset >= lineStart + indent) return true; if (ch !== '#' && ch !== '\n') return false; return Collection.nextContentHasIndent(src, offset, indent); } constructor(firstItem) { super(firstItem.type === PlainValue.Type.SEQ_ITEM ? PlainValue.Type.SEQ : PlainValue.Type.MAP); for (let i = firstItem.props.length - 1; i >= 0; --i) { if (firstItem.props[i].start < firstItem.context.lineStart) { // props on previous line are assumed by the collection this.props = firstItem.props.slice(0, i + 1); firstItem.props = firstItem.props.slice(i + 1); const itemRange = firstItem.props[0] || firstItem.valueRange; firstItem.range.start = itemRange.start; break; } } this.items = [firstItem]; const ec = grabCollectionEndComments(firstItem); if (ec) Array.prototype.push.apply(this.items, ec); } get includesTrailingLines() { return this.items.length > 0; } /** * @param {ParseContext} context * @param {number} start - Index of first character * @returns {number} - Index of the character after this */ parse(context, start) { this.context = context; const { parseNode, src } = context; // It's easier to recalculate lineStart here rather than tracking down the // last context from which to read it -- eemeli/yaml#2 let lineStart = PlainValue.Node.startOfLine(src, start); const firstItem = this.items[0]; // First-item context needs to be correct for later comment handling // -- eemeli/yaml#17 firstItem.context.parent = this; this.valueRange = PlainValue.Range.copy(firstItem.valueRange); const indent = firstItem.range.start - firstItem.context.lineStart; let offset = start; offset = PlainValue.Node.normalizeOffset(src, offset); let ch = src[offset]; let atLineStart = PlainValue.Node.endOfWhiteSpace(src, lineStart) === offset; let prevIncludesTrailingLines = false; while (ch) { while (ch === '\n' || ch === '#') { if (atLineStart && ch === '\n' && !prevIncludesTrailingLines) { const blankLine = new BlankLine(); offset = blankLine.parse({ src }, offset); this.valueRange.end = offset; if (offset >= src.length) { ch = null; break; } this.items.push(blankLine); offset -= 1; // blankLine.parse() consumes terminal newline } else if (ch === '#') { if (offset < lineStart + indent && !Collection.nextContentHasIndent(src, offset, indent)) { return offset; } const comment = new Comment(); offset = comment.parse({ indent, lineStart, src }, offset); this.items.push(comment); this.valueRange.end = offset; if (offset >= src.length) { ch = null; break; } } lineStart = offset + 1; offset = PlainValue.Node.endOfIndent(src, lineStart); if (PlainValue.Node.atBlank(src, offset)) { const wsEnd = PlainValue.Node.endOfWhiteSpace(src, offset); const next = src[wsEnd]; if (!next || next === '\n' || next === '#') { offset = wsEnd; } } ch = src[offset]; atLineStart = true; } if (!ch) { break; } if (offset !== lineStart + indent && (atLineStart || ch !== ':')) { if (offset < lineStart + indent) { if (lineStart > start) offset = lineStart; break; } else if (!this.error) { const msg = 'All collection items must start at the same column'; this.error = new PlainValue.YAMLSyntaxError(this, msg); } } if (firstItem.type === PlainValue.Type.SEQ_ITEM) { if (ch !== '-') { if (lineStart > start) offset = lineStart; break; } } else if (ch === '-' && !this.error) { // map key may start with -, as long as it's followed by a non-whitespace char const next = src[offset + 1]; if (!next || next === '\n' || next === '\t' || next === ' ') { const msg = 'A collection cannot be both a mapping and a sequence'; this.error = new PlainValue.YAMLSyntaxError(this, msg); } } const node = parseNode({ atLineStart, inCollection: true, indent, lineStart, parent: this }, offset); if (!node) return offset; // at next document start this.items.push(node); this.valueRange.end = node.valueRange.end; offset = PlainValue.Node.normalizeOffset(src, node.range.end); ch = src[offset]; atLineStart = false; prevIncludesTrailingLines = node.includesTrailingLines; // Need to reset lineStart and atLineStart here if preceding node's range // has advanced to check the current line's indentation level // -- eemeli/yaml#10 & eemeli/yaml#38 if (ch) { let ls = offset - 1; let prev = src[ls]; while (prev === ' ' || prev === '\t') prev = src[--ls]; if (prev === '\n') { lineStart = ls + 1; atLineStart = true; } } const ec = grabCollectionEndComments(node); if (ec) Array.prototype.push.apply(this.items, ec); } return offset; } setOrigRanges(cr, offset) { offset = super.setOrigRanges(cr, offset); this.items.forEach(node => { offset = node.setOrigRanges(cr, offset); }); return offset; } toString() { const { context: { src }, items, range, value } = this; if (value != null) return value; let str = src.slice(range.start, items[0].range.start) + String(items[0]); for (let i = 1; i < items.length; ++i) { const item = items[i]; const { atLineStart, indent } = item.context; if (atLineStart) for (let i = 0; i < indent; ++i) str += ' '; str += String(item); } return PlainValue.Node.addStringTerminator(src, range.end, str); } } class Directive extends PlainValue.Node { constructor() { super(PlainValue.Type.DIRECTIVE); this.name = null; } get parameters() { const raw = this.rawValue; return raw ? raw.trim().split(/[ \t]+/) : []; } parseName(start) { const { src } = this.context; let offset = start; let ch = src[offset]; while (ch && ch !== '\n' && ch !== '\t' && ch !== ' ') ch = src[offset += 1]; this.name = src.slice(start, offset); return offset; } parseParameters(start) { const { src } = this.context; let offset = start; let ch = src[offset]; while (ch && ch !== '\n' && ch !== '#') ch = src[offset += 1]; this.valueRange = new PlainValue.Range(start, offset); return offset; } parse(context, start) { this.context = context; let offset = this.parseName(start + 1); offset = this.parseParameters(offset); offset = this.parseComment(offset); this.range = new PlainValue.Range(start, offset); return offset; } } class Document extends PlainValue.Node { static startCommentOrEndBlankLine(src, start) { const offset = PlainValue.Node.endOfWhiteSpace(src, start); const ch = src[offset]; return ch === '#' || ch === '\n' ? offset : start; } constructor() { super(PlainValue.Type.DOCUMENT); this.directives = null; this.contents = null; this.directivesEndMarker = null; this.documentEndMarker = null; } parseDirectives(start) { const { src } = this.context; this.directives = []; let atLineStart = true; let hasDirectives = false; let offset = start; while (!PlainValue.Node.atDocumentBoundary(src, offset, PlainValue.Char.DIRECTIVES_END)) { offset = Document.startCommentOrEndBlankLine(src, offset); switch (src[offset]) { case '\n': if (atLineStart) { const blankLine = new BlankLine(); offset = blankLine.parse({ src }, offset); if (offset < src.length) { this.directives.push(blankLine); } } else { offset += 1; atLineStart = true; } break; case '#': { const comment = new Comment(); offset = comment.parse({ src }, offset); this.directives.push(comment); atLineStart = false; } break; case '%': { const directive = new Directive(); offset = directive.parse({ parent: this, src }, offset); this.directives.push(directive); hasDirectives = true; atLineStart = false; } break; default: if (hasDirectives) { this.error = new PlainValue.YAMLSemanticError(this, 'Missing directives-end indicator line'); } else if (this.directives.length > 0) { this.contents = this.directives; this.directives = []; } return offset; } } if (src[offset]) { this.directivesEndMarker = new PlainValue.Range(offset, offset + 3); return offset + 3; } if (hasDirectives) { this.error = new PlainValue.YAMLSemanticError(this, 'Missing directives-end indicator line'); } else if (this.directives.length > 0) { this.contents = this.directives; this.directives = []; } return offset; } parseContents(start) { const { parseNode, src } = this.context; if (!this.contents) this.contents = []; let lineStart = start; while (src[lineStart - 1] === '-') lineStart -= 1; let offset = PlainValue.Node.endOfWhiteSpace(src, start); let atLineStart = lineStart === start; this.valueRange = new PlainValue.Range(offset); while (!PlainValue.Node.atDocumentBoundary(src, offset, PlainValue.Char.DOCUMENT_END)) { switch (src[offset]) { case '\n': if (atLineStart) { const blankLine = new BlankLine(); offset = blankLine.parse({ src }, offset); if (offset < src.length) { this.contents.push(blankLine); } } else { offset += 1; atLineStart = true; } lineStart = offset; break; case '#': { const comment = new Comment(); offset = comment.parse({ src }, offset); this.contents.push(comment); atLineStart = false; } break; default: { const iEnd = PlainValue.Node.endOfIndent(src, offset); const context = { atLineStart, indent: -1, inFlow: false, inCollection: false, lineStart, parent: this }; const node = parseNode(context, iEnd); if (!node) return this.valueRange.end = iEnd; // at next document start this.contents.push(node); offset = node.range.end; atLineStart = false; const ec = grabCollectionEndComments(node); if (ec) Array.prototype.push.apply(this.contents, ec); } } offset = Document.startCommentOrEndBlankLine(src, offset); } this.valueRange.end = offset; if (src[offset]) { this.documentEndMarker = new PlainValue.Range(offset, offset + 3); offset += 3; if (src[offset]) { offset = PlainValue.Node.endOfWhiteSpace(src, offset); if (src[offset] === '#') { const comment = new Comment(); offset = comment.parse({ src }, offset); this.contents.push(comment); } switch (src[offset]) { case '\n': offset += 1; break; case undefined: break; default: this.error = new PlainValue.YAMLSyntaxError(this, 'Document end marker line cannot have a non-comment suffix'); } } } return offset; } /** * @param {ParseContext} context * @param {number} start - Index of first character * @returns {number} - Index of the character after this */ parse(context, start) { context.root = this; this.context = context; const { src } = context; let offset = src.charCodeAt(start) === 0xfeff ? start + 1 : start; // skip BOM offset = this.parseDirectives(offset); offset = this.parseContents(offset); return offset; } setOrigRanges(cr, offset) { offset = super.setOrigRanges(cr, offset); this.directives.forEach(node => { offset = node.setOrigRanges(cr, offset); }); if (this.directivesEndMarker) offset = this.directivesEndMarker.setOrigRange(cr, offset); this.contents.forEach(node => { offset = node.setOrigRanges(cr, offset); }); if (this.documentEndMarker) offset = this.documentEndMarker.setOrigRange(cr, offset); return offset; } toString() { const { contents, directives, value } = this; if (value != null) return value; let str = directives.join(''); if (contents.length > 0) { if (directives.length > 0 || contents[0].type === PlainValue.Type.COMMENT) str += '---\n'; str += contents.join(''); } if (str[str.length - 1] !== '\n') str += '\n'; return str; } } class Alias extends PlainValue.Node { /** * Parses an *alias from the source * * @param {ParseContext} context * @param {number} start - Index of first character * @returns {number} - Index of the character after this scalar */ parse(context, start) { this.context = context; const { src } = context; let offset = PlainValue.Node.endOfIdentifier(src, start + 1); this.valueRange = new PlainValue.Range(start + 1, offset); offset = PlainValue.Node.endOfWhiteSpace(src, offset); offset = this.parseComment(offset); return offset; } } const Chomp = { CLIP: 'CLIP', KEEP: 'KEEP', STRIP: 'STRIP' }; class BlockValue extends PlainValue.Node { constructor(type, props) { super(type, props); this.blockIndent = null; this.chomping = Chomp.CLIP; this.header = null; } get includesTrailingLines() { return this.chomping === Chomp.KEEP; } get strValue() { if (!this.valueRange || !this.context) return null; let { start, end } = this.valueRange; const { indent, src } = this.context; if (this.valueRange.isEmpty()) return ''; let lastNewLine = null; let ch = src[end - 1]; while (ch === '\n' || ch === '\t' || ch === ' ') { end -= 1; if (end <= start) { if (this.chomping === Chomp.KEEP) break;else return ''; // probably never happens } if (ch === '\n') lastNewLine = end; ch = src[end - 1]; } let keepStart = end + 1; if (lastNewLine) { if (this.chomping === Chomp.KEEP) { keepStart = lastNewLine; end = this.valueRange.end; } else { end = lastNewLine; } } const bi = indent + this.blockIndent; const folded = this.type === PlainValue.Type.BLOCK_FOLDED; let atStart = true; let str = ''; let sep = ''; let prevMoreIndented = false; for (let i = start; i < end; ++i) { for (let j = 0; j < bi; ++j) { if (src[i] !== ' ') break; i += 1; } const ch = src[i]; if (ch === '\n') { if (sep === '\n') str += '\n';else sep = '\n'; } else { const lineEnd = PlainValue.Node.endOfLine(src, i); const line = src.slice(i, lineEnd); i = lineEnd; if (folded && (ch === ' ' || ch === '\t') && i < keepStart) { if (sep === ' ') sep = '\n';else if (!prevMoreIndented && !atStart && sep === '\n') sep = '\n\n'; str += sep + line; //+ ((lineEnd < end && src[lineEnd]) || '') sep = lineEnd < end && src[lineEnd] || ''; prevMoreIndented = true; } else { str += sep + line; sep = folded && i < keepStart ? ' ' : '\n'; prevMoreIndented = false; } if (atStart && line !== '') atStart = false; } } return this.chomping === Chomp.STRIP ? str : str + '\n'; } parseBlockHeader(start) { const { src } = this.context; let offset = start + 1; let bi = ''; while (true) { const ch = src[offset]; switch (ch) { case '-': this.chomping = Chomp.STRIP; break; case '+': this.chomping = Chomp.KEEP; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': bi += ch; break; default: this.blockIndent = Number(bi) || null; this.header = new PlainValue.Range(start, offset); return offset; } offset += 1; } } parseBlockValue(start) { const { indent, src } = this.context; const explicit = !!this.blockIndent; let offset = start; let valueEnd = start; let minBlockIndent = 1; for (let ch = src[offset]; ch === '\n'; ch = src[offset]) { offset += 1; if (PlainValue.Node.atDocumentBoundary(src, offset)) break; const end = PlainValue.Node.endOfBlockIndent(src, indent, offset); // should not include tab? if (end === null) break; const ch = src[end]; const lineIndent = end - (offset + indent); if (!this.blockIndent) { // no explicit block indent, none yet detected if (src[end] !== '\n') { // first line with non-whitespace content if (lineIndent < minBlockIndent) { const msg = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator'; this.error = new PlainValue.YAMLSemanticError(this, msg); } this.blockIndent = lineIndent; } else if (lineIndent > minBlockIndent) { // empty line with more whitespace minBlockIndent = lineIndent; } } else if (ch && ch !== '\n' && lineIndent < this.blockIndent) { if (src[end] === '#') break; if (!this.error) { const src = explicit ? 'explicit indentation indicator' : 'first line'; const msg = `Block scalars must not be less indented than their ${src}`; this.error = new PlainValue.YAMLSemanticError(this, msg); } } if (src[end] === '\n') { offset = end; } else { offset = valueEnd = PlainValue.Node.endOfLine(src, end); } } if (this.chomping !== Chomp.KEEP) { offset = src[valueEnd] ? valueEnd + 1 : valueEnd; } this.valueRange = new PlainValue.Range(start + 1, offset); return offset; } /** * Parses a block value from the source * * Accepted forms are: * ``` * BS * block * lines * * BS #comment * block * lines * ``` * where the block style BS matches the regexp `[|>][-+1-9]*` and block lines * are empty or have an indent level greater than `indent`. * * @param {ParseContext} context * @param {number} start - Index of first character * @returns {number} - Index of the character after this block */ parse(context, start) { this.context = context; const { src } = context; let offset = this.parseBlockHeader(start); offset = PlainValue.Node.endOfWhiteSpace(src, offset); offset = this.parseComment(offset); offset = this.parseBlockValue(offset); return offset; } setOrigRanges(cr, offset) { offset = super.setOrigRanges(cr, offset); return this.header ? this.header.setOrigRange(cr, offset) : offset; } } class FlowCollection extends PlainValue.Node { constructor(type, props) { super(type, props); this.items = null; } prevNodeIsJsonLike(idx = this.items.length) { const node = this.items[idx - 1]; return !!node && (node.jsonLike || node.type === PlainValue.Type.COMMENT && this.prevNodeIsJsonLike(idx - 1)); } /** * @param {ParseContext} context * @param {number} start - Index of first character * @returns {number} - Index of the character after this */ parse(context, start) { this.context = context; const { parseNode, src } = context; let { indent, lineStart } = context; let char = src[start]; // { or [ this.items = [{ char, offset: start }]; let offset = PlainValue.Node.endOfWhiteSpace(src, start + 1); char = src[offset]; while (char && char !== ']' && char !== '}') { switch (char) { case '\n': { lineStart = offset + 1; const wsEnd = PlainValue.Node.endOfWhiteSpace(src, lineStart); if (src[wsEnd] === '\n') { const blankLine = new BlankLine(); lineStart = blankLine.parse({ src }, lineStart); this.items.push(blankLine); } offset = PlainValue.Node.endOfIndent(src, lineStart); if (offset <= lineStart + indent) { char = src[offset]; if (offset < lineStart + indent || char !== ']' && char !== '}') { const msg = 'Insufficient indentation in flow collection'; this.error = new PlainValue.YAMLSemanticError(this, msg); } } } break; case ',': { this.items.push({ char, offset }); offset += 1; } break; case '#': { const comment = new Comment(); offset = comment.parse({ src }, offset); this.items.push(comment); } break; case '?': case ':': { const next = src[offset + 1]; if (next === '\n' || next === '\t' || next === ' ' || next === ',' || // in-flow : after JSON-like key does not need to be followed by whitespace char === ':' && this.prevNodeIsJsonLike()) { this.items.push({ char, offset }); offset += 1; break; } } // fallthrough default: { const node = parseNode({ atLineStart: false, inCollection: false, inFlow: true, indent: -1, lineStart, parent: this }, offset); if (!node) { // at next document start this.valueRange = new PlainValue.Range(start, offset); return offset; } this.items.push(node); offset = PlainValue.Node.normalizeOffset(src, node.range.end); } } offset = PlainValue.Node.endOfWhiteSpace(src, offset); char = src[offset]; } this.valueRange = new PlainValue.Range(start, offset + 1); if (char) { this.items.push({ char, offset }); offset = PlainValue.Node.endOfWhiteSpace(src, offset + 1); offset = this.parseComment(offset); } return offset; } setOrigRanges(cr, offset) { offset = super.setOrigRanges(cr, offset); this.items.forEach(node => { if (node instanceof PlainValue.Node) { offset = node.setOrigRanges(cr, offset); } else if (cr.length === 0) { node.origOffset = node.offset; } else { let i = offset; while (i < cr.length) { if (cr[i] > node.offset) break;else ++i; } node.origOffset = node.offset + i; offset = i; } }); return offset; } toString() { const { context: { src }, items, range, value } = this; if (value != null) return value; const nodes = items.filter(item => item instanceof PlainValue.Node); let str = ''; let prevEnd = range.start; nodes.forEach(node => { const prefix = src.slice(prevEnd, node.range.start); prevEnd = node.range.end; str += prefix + String(node); if (str[str.length - 1] === '\n' && src[prevEnd - 1] !== '\n' && src[prevEnd] === '\n') { // Comment range does not include the terminal newline, but its // stringified value does. Without this fix, newlines at comment ends // get duplicated. prevEnd += 1; } }); str += src.slice(prevEnd, range.end); return PlainValue.Node.addStringTerminator(src, range.end, str); } } class QuoteDouble extends PlainValue.Node { static endOfQuote(src, offset) { let ch = src[offset]; while (ch && ch !== '"') { offset += ch === '\\' ? 2 : 1; ch = src[offset]; } return offset + 1; } /** * @returns {string | { str: string, errors: YAMLSyntaxError[] }} */ get strValue() { if (!this.valueRange || !this.context) return null; const errors = []; const { start, end } = this.valueRange; const { indent, src } = this.context; if (src[end - 1] !== '"') errors.push(new PlainValue.YAMLSyntaxError(this, 'Missing closing "quote')); // Using String#replace is too painful with escaped newlines preceded by // escaped backslashes; also, this should be faster. let str = ''; for (let i = start + 1; i < end - 1; ++i) { const ch = src[i]; if (ch === '\n') { if (PlainValue.Node.atDocumentBoundary(src, i + 1)) errors.push(new PlainValue.YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values')); const { fold, offset, error } = PlainValue.Node.foldNewline(src, i, indent); str += fold; i = offset; if (error) errors.push(new PlainValue.YAMLSemanticError(this, 'Multi-line double-quoted string needs to be sufficiently indented')); } else if (ch === '\\') { i += 1; switch (src[i]) { case '0': str += '\0'; break; // null character case 'a': str += '\x07'; break; // bell character case 'b': str += '\b'; break; // backspace case 'e': str += '\x1b'; break; // escape character case 'f': str += '\f'; break; // form feed case 'n': str += '\n'; break; // line feed case 'r': str += '\r'; break; // carriage return case 't': str += '\t'; break; // horizontal tab case 'v': str += '\v'; break; // vertical tab case 'N': str += '\u0085'; break; // Unicode next line case '_': str += '\u00a0'; break; // Unicode non-breaking space case 'L': str += '\u2028'; break; // Unicode line separator case 'P': str += '\u2029'; break; // Unicode paragraph separator case ' ': str += ' '; break; case '"': str += '"'; break; case '/': str += '/'; break; case '\\': str += '\\'; break; case '\t': str += '\t'; break; case 'x': str += this.parseCharCode(i + 1, 2, errors); i += 2; break; case 'u': str += this.parseCharCode(i + 1, 4, errors); i += 4; break; case 'U': str += this.parseCharCode(i + 1, 8, errors); i += 8; break; case '\n': // skip escaped newlines, but still trim the following line while (src[i + 1] === ' ' || src[i + 1] === '\t') i += 1; break; default: errors.push(new PlainValue.YAMLSyntaxError(this, `Invalid escape sequence ${src.substr(i - 1, 2)}`)); str += '\\' + src[i]; } } else if (ch === ' ' || ch === '\t') { // trim trailing whitespace const wsStart = i; let next = src[i + 1]; while (next === ' ' || next === '\t') { i += 1; next = src[i + 1]; } if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch; } else { str += ch; } } return errors.length > 0 ? { errors, str } : str; } parseCharCode(offset, length, errors) { const { src } = this.context; const cc = src.substr(offset, length); const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); const code = ok ? parseInt(cc, 16) : NaN; if (isNaN(code)) { errors.push(new PlainValue.YAMLSyntaxError(this, `Invalid escape sequence ${src.substr(offset - 2, length + 2)}`)); return src.substr(offset - 2, length + 2); } return String.fromCodePoint(code); } /** * Parses a "double quoted" value from the source * * @param {ParseContext} context * @param {number} start - Index of first character * @returns {number} - Index of the character after this scalar */ parse(context, start) { this.context = context; const { src } = context; let offset = QuoteDouble.endOfQuote(src, start + 1); this.valueRange = new PlainValue.Range(start, offset); offset = PlainValue.Node.endOfWhiteSpace(src, offset); offset = this.parseComment(offset); return offset; } } class QuoteSingle extends PlainValue.Node { static endOfQuote(src, offset) { let ch = src[offset]; while (ch) { if (ch === "'") { if (src[offset + 1] !== "'") break; ch = src[offset += 2]; } else { ch = src[offset += 1]; } } return offset + 1; } /** * @returns {string | { str: string, errors: YAMLSyntaxError[] }} */ get strValue() { if (!this.valueRange || !this.context) return null; const errors = []; const { start, end } = this.valueRange; const { indent, src } = this.context; if (src[end - 1] !== "'") errors.push(new PlainValue.YAMLSyntaxError(this, "Missing closing 'quote")); let str = ''; for (let i = start + 1; i < end - 1; ++i) { const ch = src[i]; if (ch === '\n') { if (PlainValue.Node.atDocumentBoundary(src, i + 1)) errors.push(new PlainValue.YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values')); const { fold, offset, error } = PlainValue.Node.foldNewline(src, i, indent); str += fold; i = offset; if (error) errors.push(new PlainValue.YAMLSemanticError(this, 'Multi-line single-quoted string needs to be sufficiently indented')); } else if (ch === "'") { str += ch; i += 1; if (src[i] !== "'") errors.push(new PlainValue.YAMLSyntaxError(this, 'Unescaped single quote? This should not happen.')); } else if (ch === ' ' || ch === '\t') { // trim trailing whitespace const wsStart = i; let next = src[i + 1]; while (next === ' ' || next === '\t') { i += 1; next = src[i + 1]; } if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch; } else { str += ch; } } return errors.length > 0 ? { errors, str } : str; } /** * Parses a 'single quoted' value from the source * * @param {ParseContext} context * @param {number} start - Index of first character * @returns {number} - Index of the character after this scalar */ parse(context, start) { this.context = context; const { src } = context; let offset = QuoteSingle.endOfQuote(src, start + 1); this.valueRange = new PlainValue.Range(start, offset); offset = PlainValue.Node.endOfWhiteSpace(src, offset); offset = this.parseComment(offset); return offset; } } function createNewNode(type, props) { switch (type) { case PlainValue.Type.ALIAS: return new Alias(type, props); case PlainValue.Type.BLOCK_FOLDED: case PlainValue.Type.BLOCK_LITERAL: return new BlockValue(type, props); case PlainValue.Type.FLOW_MAP: case PlainValue.Type.FLOW_SEQ: return new FlowCollection(type, props); case PlainValue.Type.MAP_KEY: case PlainValue.Type.MAP_VALUE: case PlainValue.Type.SEQ_ITEM: return new CollectionItem(type, props); case PlainValue.Type.COMMENT: case PlainValue.Type.PLAIN: return new PlainValue.PlainValue(type, props); case PlainValue.Type.QUOTE_DOUBLE: return new QuoteDouble(type, props); case PlainValue.Type.QUOTE_SINGLE: return new QuoteSingle(type, props); /* istanbul ignore next */ default: return null; // should never happen } } /** * @param {boolean} atLineStart - Node starts at beginning of line * @param {boolean} inFlow - true if currently in a flow context * @param {boolean} inCollection - true if currently in a collection context * @param {number} indent - Current level of indentation * @param {number} lineStart - Start of the current line * @param {Node} parent - The parent of the node * @param {string} src - Source of the YAML document */ class ParseContext { static parseType(src, offset, inFlow) { switch (src[offset]) { case '*': return PlainValue.Type.ALIAS; case '>': return PlainValue.Type.BLOCK_FOLDED; case '|': return PlainValue.Type.BLOCK_LITERAL; case '{': return PlainValue.Type.FLOW_MAP; case '[': return PlainValue.Type.FLOW_SEQ; case '?': return !inFlow && PlainValue.Node.atBlank(src, offset + 1, true) ? PlainValue.Type.MAP_KEY : PlainValue.Type.PLAIN; case ':': return !inFlow && PlainValue.Node.atBlank(src, offset + 1, true) ? PlainValue.Type.MAP_VALUE : PlainValue.Type.PLAIN; case '-': return !inFlow && PlainValue.Node.atBlank(src, offset + 1, true) ? PlainValue.Type.SEQ_ITEM : PlainValue.Type.PLAIN; case '"': return PlainValue.Type.QUOTE_DOUBLE; case "'": return PlainValue.Type.QUOTE_SINGLE; default: return PlainValue.Type.PLAIN; } } constructor(orig = {}, { atLineStart, inCollection, inFlow, indent, lineStart, parent } = {}) { PlainValue._defineProperty(this, "parseNode", (overlay, start) => { if (PlainValue.Node.atDocumentBoundary(this.src, start)) return null; const context = new ParseContext(this, overlay); const { props, type, valueStart } = context.parseProps(start); const node = createNewNode(type, props); let offset = node.parse(context, valueStart); node.range = new PlainValue.Range(start, offset); /* istanbul ignore if */ if (offset <= start) { // This should never happen, but if it does, let's make sure to at least // step one character forward to avoid a busy loop. node.error = new Error(`Node#parse consumed no characters`); node.error.parseEnd = offset; node.error.source = node; node.range.end = start + 1; } if (context.nodeStartsCollection(node)) { if (!node.error && !context.atLineStart && context.parent.type === PlainValue.Type.DOCUMENT) { node.error = new PlainValue.YAMLSyntaxError(node, 'Block collection must not have preceding content here (e.g. directives-end indicator)'); } const collection = new Collection(node); offset = collection.parse(new ParseContext(context), offset); collection.range = new PlainValue.Range(start, offset); return collection; } return node; }); this.atLineStart = atLineStart != null ? atLineStart : orig.atLineStart || false; this.inCollection = inCollection != null ? inCollection : orig.inCollection || false; this.inFlow = inFlow != null ? inFlow : orig.inFlow || false; this.indent = indent != null ? indent : orig.indent; this.lineStart = lineStart != null ? lineStart : orig.lineStart; this.parent = parent != null ? parent : orig.parent || {}; this.root = orig.root; this.src = orig.src; } nodeStartsCollection(node) { const { inCollection, inFlow, src } = this; if (inCollection || inFlow) return false; if (node instanceof CollectionItem) return true; // check for implicit key let offset = node.range.end; if (src[offset] === '\n' || src[offset - 1] === '\n') return false; offset = PlainValue.Node.endOfWhiteSpace(src, offset); return src[offset] === ':'; } // Anchor and tag are before type, which determines the node implementation // class; hence this intermediate step. parseProps(offset) { const { inFlow, parent, src } = this; const props = []; let lineHasProps = false; offset = this.atLineStart ? PlainValue.Node.endOfIndent(src, offset) : PlainValue.Node.endOfWhiteSpace(src, offset); let ch = src[offset]; while (ch === PlainValue.Char.ANCHOR || ch === PlainValue.Char.COMMENT || ch === PlainValue.Char.TAG || ch === '\n') { if (ch === '\n') { let inEnd = offset; let lineStart; do { lineStart = inEnd + 1; inEnd = PlainValue.Node.endOfIndent(src, lineStart); } while (src[inEnd] === '\n'); const indentDiff = inEnd - (lineStart + this.indent); const noIndicatorAsIndent = parent.type === PlainValue.Type.SEQ_ITEM && parent.context.atLineStart; if (src[inEnd] !== '#' && !PlainValue.Node.nextNodeIsIndented(src[inEnd], indentDiff, !noIndicatorAsIndent)) break; this.atLineStart = true; this.lineStart = lineStart; lineHasProps = false; offset = inEnd; } else if (ch === PlainValue.Char.COMMENT) { const end = PlainValue.Node.endOfLine(src, offset + 1); props.push(new PlainValue.Range(offset, end)); offset = end; } else { let end = PlainValue.Node.endOfIdentifier(src, offset + 1); if (ch === PlainValue.Char.TAG && src[end] === ',' && /^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+,\d\d\d\d(-\d\d){0,2}\/\S/.test(src.slice(offset + 1, end + 13))) { // Let's presume we're dealing with a YAML 1.0 domain tag here, rather // than an empty but 'foo.bar' private-tagged node in a flow collection // followed without whitespace by a plain string starting with a year // or date divided by something. end = PlainValue.Node.endOfIdentifier(src, end + 5); } props.push(new PlainValue.Range(offset, end)); lineHasProps = true; offset = PlainValue.Node.endOfWhiteSpace(src, end); } ch = src[offset]; } // '- &a : b' has an anchor on an empty node if (lineHasProps && ch === ':' && PlainValue.Node.atBlank(src, offset + 1, true)) offset -= 1; const type = ParseContext.parseType(src, offset, inFlow); return { props, type, valueStart: offset }; } /** * Parses a node from the source * @param {ParseContext} overlay * @param {number} start - Index of first non-whitespace character for the node * @returns {?Node} - null if at a document boundary */ } // Published as 'yaml/parse-cst' function parse(src) { const cr = []; if (src.indexOf('\r') !== -1) { src = src.replace(/\r\n?/g, (match, offset) => { if (match.length > 1) cr.push(offset); return '\n'; }); } const documents = []; let offset = 0; do { const doc = new Document(); const context = new ParseContext({ src }); offset = doc.parse(context, offset); documents.push(doc); } while (offset < src.length); documents.setOrigRanges = () => { if (cr.length === 0) return false; for (let i = 1; i < cr.length; ++i) cr[i] -= i; let crOffset = 0; for (let i = 0; i < documents.length; ++i) { crOffset = documents[i].setOrigRanges(cr, crOffset); } cr.splice(0, cr.length); return true; }; documents.toString = () => documents.join('...\n'); return documents; } exports.parse = parse; /***/ }), /***/ 63970: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var PlainValue = __webpack_require__(51937); function addCommentBefore(str, indent, comment) { if (!comment) return str; const cc = comment.replace(/[\s\S]^/gm, `$&${indent}#`); return `#${cc}\n${indent}${str}`; } function addComment(str, indent, comment) { return !comment ? str : comment.indexOf('\n') === -1 ? `${str} #${comment}` : `${str}\n` + comment.replace(/^/gm, `${indent || ''}#`); } class Node {} function toJSON(value, arg, ctx) { if (Array.isArray(value)) return value.map((v, i) => toJSON(v, String(i), ctx)); if (value && typeof value.toJSON === 'function') { const anchor = ctx && ctx.anchors && ctx.anchors.get(value); if (anchor) ctx.onCreate = res => { anchor.res = res; delete ctx.onCreate; }; const res = value.toJSON(arg, ctx); if (anchor && ctx.onCreate) ctx.onCreate(res); return res; } if ((!ctx || !ctx.keep) && typeof value === 'bigint') return Number(value); return value; } class Scalar extends Node { constructor(value) { super(); this.value = value; } toJSON(arg, ctx) { return ctx && ctx.keep ? this.value : toJSON(this.value, arg, ctx); } toString() { return String(this.value); } } function collectionFromPath(schema, path, value) { let v = value; for (let i = path.length - 1; i >= 0; --i) { const k = path[i]; if (Number.isInteger(k) && k >= 0) { const a = []; a[k] = v; v = a; } else { const o = {}; Object.defineProperty(o, k, { value: v, writable: true, enumerable: true, configurable: true }); v = o; } } return schema.createNode(v, false); } // null, undefined, or an empty non-string iterable (e.g. []) const isEmptyPath = path => path == null || typeof path === 'object' && path[Symbol.iterator]().next().done; class Collection extends Node { constructor(schema) { super(); PlainValue._defineProperty(this, "items", []); this.schema = schema; } addIn(path, value) { if (isEmptyPath(path)) this.add(value);else { const [key, ...rest] = path; const node = this.get(key, true); if (node instanceof Collection) node.addIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); } } deleteIn([key, ...rest]) { if (rest.length === 0) return this.delete(key); const node = this.get(key, true); if (node instanceof Collection) return node.deleteIn(rest);else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); } getIn([key, ...rest], keepScalar) { const node = this.get(key, true); if (rest.length === 0) return !keepScalar && node instanceof Scalar ? node.value : node;else return node instanceof Collection ? node.getIn(rest, keepScalar) : undefined; } hasAllNullValues() { return this.items.every(node => { if (!node || node.type !== 'PAIR') return false; const n = node.value; return n == null || n instanceof Scalar && n.value == null && !n.commentBefore && !n.comment && !n.tag; }); } hasIn([key, ...rest]) { if (rest.length === 0) return this.has(key); const node = this.get(key, true); return node instanceof Collection ? node.hasIn(rest) : false; } setIn([key, ...rest], value) { if (rest.length === 0) { this.set(key, value); } else { const node = this.get(key, true); if (node instanceof Collection) node.setIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); } } // overridden in implementations /* istanbul ignore next */ toJSON() { return null; } toString(ctx, { blockItem, flowChars, isMap, itemIndent }, onComment, onChompKeep) { const { indent, indentStep, stringify } = ctx; const inFlow = this.type === PlainValue.Type.FLOW_MAP || this.type === PlainValue.Type.FLOW_SEQ || ctx.inFlow; if (inFlow) itemIndent += indentStep; const allNullValues = isMap && this.hasAllNullValues(); ctx = Object.assign({}, ctx, { allNullValues, indent: itemIndent, inFlow, type: null }); let chompKeep = false; let hasItemWithNewLine = false; const nodes = this.items.reduce((nodes, item, i) => { let comment; if (item) { if (!chompKeep && item.spaceBefore) nodes.push({ type: 'comment', str: '' }); if (item.commentBefore) item.commentBefore.match(/^.*$/gm).forEach(line => { nodes.push({ type: 'comment', str: `#${line}` }); }); if (item.comment) comment = item.comment; if (inFlow && (!chompKeep && item.spaceBefore || item.commentBefore || item.comment || item.key && (item.key.commentBefore || item.key.comment) || item.value && (item.value.commentBefore || item.value.comment))) hasItemWithNewLine = true; } chompKeep = false; let str = stringify(item, ctx, () => comment = null, () => chompKeep = true); if (inFlow && !hasItemWithNewLine && str.includes('\n')) hasItemWithNewLine = true; if (inFlow && i < this.items.length - 1) str += ','; str = addComment(str, itemIndent, comment); if (chompKeep && (comment || inFlow)) chompKeep = false; nodes.push({ type: 'item', str }); return nodes; }, []); let str; if (nodes.length === 0) { str = flowChars.start + flowChars.end; } else if (inFlow) { const { start, end } = flowChars; const strings = nodes.map(n => n.str); if (hasItemWithNewLine || strings.reduce((sum, str) => sum + str.length + 2, 2) > Collection.maxFlowStringSingleLineLength) { str = start; for (const s of strings) { str += s ? `\n${indentStep}${indent}${s}` : '\n'; } str += `\n${indent}${end}`; } else { str = `${start} ${strings.join(' ')} ${end}`; } } else { const strings = nodes.map(blockItem); str = strings.shift(); for (const s of strings) str += s ? `\n${indent}${s}` : '\n'; } if (this.comment) { str += '\n' + this.comment.replace(/^/gm, `${indent}#`); if (onComment) onComment(); } else if (chompKeep && onChompKeep) onChompKeep(); return str; } } PlainValue._defineProperty(Collection, "maxFlowStringSingleLineLength", 60); function asItemIndex(key) { let idx = key instanceof Scalar ? key.value : key; if (idx && typeof idx === 'string') idx = Number(idx); return Number.isInteger(idx) && idx >= 0 ? idx : null; } class YAMLSeq extends Collection { add(value) { this.items.push(value); } delete(key) { const idx = asItemIndex(key); if (typeof idx !== 'number') return false; const del = this.items.splice(idx, 1); return del.length > 0; } get(key, keepScalar) { const idx = asItemIndex(key); if (typeof idx !== 'number') return undefined; const it = this.items[idx]; return !keepScalar && it instanceof Scalar ? it.value : it; } has(key) { const idx = asItemIndex(key); return typeof idx === 'number' && idx < this.items.length; } set(key, value) { const idx = asItemIndex(key); if (typeof idx !== 'number') throw new Error(`Expected a valid index, not ${key}.`); this.items[idx] = value; } toJSON(_, ctx) { const seq = []; if (ctx && ctx.onCreate) ctx.onCreate(seq); let i = 0; for (const item of this.items) seq.push(toJSON(item, String(i++), ctx)); return seq; } toString(ctx, onComment, onChompKeep) { if (!ctx) return JSON.stringify(this); return super.toString(ctx, { blockItem: n => n.type === 'comment' ? n.str : `- ${n.str}`, flowChars: { start: '[', end: ']' }, isMap: false, itemIndent: (ctx.indent || '') + ' ' }, onComment, onChompKeep); } } const stringifyKey = (key, jsKey, ctx) => { if (jsKey === null) return ''; if (typeof jsKey !== 'object') return String(jsKey); if (key instanceof Node && ctx && ctx.doc) return key.toString({ anchors: Object.create(null), doc: ctx.doc, indent: '', indentStep: ctx.indentStep, inFlow: true, inStringifyKey: true, stringify: ctx.stringify }); return JSON.stringify(jsKey); }; class Pair extends Node { constructor(key, value = null) { super(); this.key = key; this.value = value; this.type = Pair.Type.PAIR; } get commentBefore() { return this.key instanceof Node ? this.key.commentBefore : undefined; } set commentBefore(cb) { if (this.key == null) this.key = new Scalar(null); if (this.key instanceof Node) this.key.commentBefore = cb;else { const msg = 'Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node.'; throw new Error(msg); } } addToJSMap(ctx, map) { const key = toJSON(this.key, '', ctx); if (map instanceof Map) { const value = toJSON(this.value, key, ctx); map.set(key, value); } else if (map instanceof Set) { map.add(key); } else { const stringKey = stringifyKey(this.key, key, ctx); const value = toJSON(this.value, stringKey, ctx); if (stringKey in map) Object.defineProperty(map, stringKey, { value, writable: true, enumerable: true, configurable: true });else map[stringKey] = value; } return map; } toJSON(_, ctx) { const pair = ctx && ctx.mapAsMap ? new Map() : {}; return this.addToJSMap(ctx, pair); } toString(ctx, onComment, onChompKeep) { if (!ctx || !ctx.doc) return JSON.stringify(this); const { indent: indentSize, indentSeq, simpleKeys } = ctx.doc.options; let { key, value } = this; let keyComment = key instanceof Node && key.comment; if (simpleKeys) { if (keyComment) { throw new Error('With simple keys, key nodes cannot have comments'); } if (key instanceof Collection) { const msg = 'With simple keys, collection cannot be used as a key value'; throw new Error(msg); } } let explicitKey = !simpleKeys && (!key || keyComment || (key instanceof Node ? key instanceof Collection || key.type === PlainValue.Type.BLOCK_FOLDED || key.type === PlainValue.Type.BLOCK_LITERAL : typeof key === 'object')); const { doc, indent, indentStep, stringify } = ctx; ctx = Object.assign({}, ctx, { implicitKey: !explicitKey, indent: indent + indentStep }); let chompKeep = false; let str = stringify(key, ctx, () => keyComment = null, () => chompKeep = true); str = addComment(str, ctx.indent, keyComment); if (!explicitKey && str.length > 1024) { if (simpleKeys) throw new Error('With simple keys, single line scalar must not span more than 1024 characters'); explicitKey = true; } if (ctx.allNullValues && !simpleKeys) { if (this.comment) { str = addComment(str, ctx.indent, this.comment); if (onComment) onComment(); } else if (chompKeep && !keyComment && onChompKeep) onChompKeep(); return ctx.inFlow && !explicitKey ? str : `? ${str}`; } str = explicitKey ? `? ${str}\n${indent}:` : `${str}:`; if (this.comment) { // expected (but not strictly required) to be a single-line comment str = addComment(str, ctx.indent, this.comment); if (onComment) onComment(); } let vcb = ''; let valueComment = null; if (value instanceof Node) { if (value.spaceBefore) vcb = '\n'; if (value.commentBefore) { const cs = value.commentBefore.replace(/^/gm, `${ctx.indent}#`); vcb += `\n${cs}`; } valueComment = value.comment; } else if (value && typeof value === 'object') { value = doc.schema.createNode(value, true); } ctx.implicitKey = false; if (!explicitKey && !this.comment && value instanceof Scalar) ctx.indentAtStart = str.length + 1; chompKeep = false; if (!indentSeq && indentSize >= 2 && !ctx.inFlow && !explicitKey && value instanceof YAMLSeq && value.type !== PlainValue.Type.FLOW_SEQ && !value.tag && !doc.anchors.getName(value)) { // If indentSeq === false, consider '- ' as part of indentation where possible ctx.indent = ctx.indent.substr(2); } const valueStr = stringify(value, ctx, () => valueComment = null, () => chompKeep = true); let ws = ' '; if (vcb || this.comment) { ws = `${vcb}\n${ctx.indent}`; } else if (!explicitKey && value instanceof Collection) { const flow = valueStr[0] === '[' || valueStr[0] === '{'; if (!flow || valueStr.includes('\n')) ws = `\n${ctx.indent}`; } else if (valueStr[0] === '\n') ws = ''; if (chompKeep && !valueComment && onChompKeep) onChompKeep(); return addComment(str + ws + valueStr, ctx.indent, valueComment); } } PlainValue._defineProperty(Pair, "Type", { PAIR: 'PAIR', MERGE_PAIR: 'MERGE_PAIR' }); const getAliasCount = (node, anchors) => { if (node instanceof Alias) { const anchor = anchors.get(node.source); return anchor.count * anchor.aliasCount; } else if (node instanceof Collection) { let count = 0; for (const item of node.items) { const c = getAliasCount(item, anchors); if (c > count) count = c; } return count; } else if (node instanceof Pair) { const kc = getAliasCount(node.key, anchors); const vc = getAliasCount(node.value, anchors); return Math.max(kc, vc); } return 1; }; class Alias extends Node { static stringify({ range, source }, { anchors, doc, implicitKey, inStringifyKey }) { let anchor = Object.keys(anchors).find(a => anchors[a] === source); if (!anchor && inStringifyKey) anchor = doc.anchors.getName(source) || doc.anchors.newName(); if (anchor) return `*${anchor}${implicitKey ? ' ' : ''}`; const msg = doc.anchors.getName(source) ? 'Alias node must be after source node' : 'Source node not found for alias node'; throw new Error(`${msg} [${range}]`); } constructor(source) { super(); this.source = source; this.type = PlainValue.Type.ALIAS; } set tag(t) { throw new Error('Alias nodes cannot have tags'); } toJSON(arg, ctx) { if (!ctx) return toJSON(this.source, arg, ctx); const { anchors, maxAliasCount } = ctx; const anchor = anchors.get(this.source); /* istanbul ignore if */ if (!anchor || anchor.res === undefined) { const msg = 'This should not happen: Alias anchor was not resolved?'; if (this.cstNode) throw new PlainValue.YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg); } if (maxAliasCount >= 0) { anchor.count += 1; if (anchor.aliasCount === 0) anchor.aliasCount = getAliasCount(this.source, anchors); if (anchor.count * anchor.aliasCount > maxAliasCount) { const msg = 'Excessive alias count indicates a resource exhaustion attack'; if (this.cstNode) throw new PlainValue.YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg); } } return anchor.res; } // Only called when stringifying an alias mapping key while constructing // Object output. toString(ctx) { return Alias.stringify(this, ctx); } } PlainValue._defineProperty(Alias, "default", true); function findPair(items, key) { const k = key instanceof Scalar ? key.value : key; for (const it of items) { if (it instanceof Pair) { if (it.key === key || it.key === k) return it; if (it.key && it.key.value === k) return it; } } return undefined; } class YAMLMap extends Collection { add(pair, overwrite) { if (!pair) pair = new Pair(pair);else if (!(pair instanceof Pair)) pair = new Pair(pair.key || pair, pair.value); const prev = findPair(this.items, pair.key); const sortEntries = this.schema && this.schema.sortMapEntries; if (prev) { if (overwrite) prev.value = pair.value;else throw new Error(`Key ${pair.key} already set`); } else if (sortEntries) { const i = this.items.findIndex(item => sortEntries(pair, item) < 0); if (i === -1) this.items.push(pair);else this.items.splice(i, 0, pair); } else { this.items.push(pair); } } delete(key) { const it = findPair(this.items, key); if (!it) return false; const del = this.items.splice(this.items.indexOf(it), 1); return del.length > 0; } get(key, keepScalar) { const it = findPair(this.items, key); const node = it && it.value; return !keepScalar && node instanceof Scalar ? node.value : node; } has(key) { return !!findPair(this.items, key); } set(key, value) { this.add(new Pair(key, value), true); } /** * @param {*} arg ignored * @param {*} ctx Conversion context, originally set in Document#toJSON() * @param {Class} Type If set, forces the returned collection type * @returns {*} Instance of Type, Map, or Object */ toJSON(_, ctx, Type) { const map = Type ? new Type() : ctx && ctx.mapAsMap ? new Map() : {}; if (ctx && ctx.onCreate) ctx.onCreate(map); for (const item of this.items) item.addToJSMap(ctx, map); return map; } toString(ctx, onComment, onChompKeep) { if (!ctx) return JSON.stringify(this); for (const item of this.items) { if (!(item instanceof Pair)) throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); } return super.toString(ctx, { blockItem: n => n.str, flowChars: { start: '{', end: '}' }, isMap: true, itemIndent: ctx.indent || '' }, onComment, onChompKeep); } } const MERGE_KEY = '<<'; class Merge extends Pair { constructor(pair) { if (pair instanceof Pair) { let seq = pair.value; if (!(seq instanceof YAMLSeq)) { seq = new YAMLSeq(); seq.items.push(pair.value); seq.range = pair.value.range; } super(pair.key, seq); this.range = pair.range; } else { super(new Scalar(MERGE_KEY), new YAMLSeq()); } this.type = Pair.Type.MERGE_PAIR; } // If the value associated with a merge key is a single mapping node, each of // its key/value pairs is inserted into the current mapping, unless the key // already exists in it. If the value associated with the merge key is a // sequence, then this sequence is expected to contain mapping nodes and each // of these nodes is merged in turn according to its order in the sequence. // Keys in mapping nodes earlier in the sequence override keys specified in // later mapping nodes. -- http://yaml.org/type/merge.html addToJSMap(ctx, map) { for (const { source } of this.value.items) { if (!(source instanceof YAMLMap)) throw new Error('Merge sources must be maps'); const srcMap = source.toJSON(null, ctx, Map); for (const [key, value] of srcMap) { if (map instanceof Map) { if (!map.has(key)) map.set(key, value); } else if (map instanceof Set) { map.add(key); } else if (!Object.prototype.hasOwnProperty.call(map, key)) { Object.defineProperty(map, key, { value, writable: true, enumerable: true, configurable: true }); } } } return map; } toString(ctx, onComment) { const seq = this.value; if (seq.items.length > 1) return super.toString(ctx, onComment); this.value = seq.items[0]; const str = super.toString(ctx, onComment); this.value = seq; return str; } } const binaryOptions = { defaultType: PlainValue.Type.BLOCK_LITERAL, lineWidth: 76 }; const boolOptions = { trueStr: 'true', falseStr: 'false' }; const intOptions = { asBigInt: false }; const nullOptions = { nullStr: 'null' }; const strOptions = { defaultType: PlainValue.Type.PLAIN, doubleQuoted: { jsonEncoding: false, minMultiLineLength: 40 }, fold: { lineWidth: 80, minContentWidth: 20 } }; function resolveScalar(str, tags, scalarFallback) { for (const { format, test, resolve } of tags) { if (test) { const match = str.match(test); if (match) { let res = resolve.apply(null, match); if (!(res instanceof Scalar)) res = new Scalar(res); if (format) res.format = format; return res; } } } if (scalarFallback) str = scalarFallback(str); return new Scalar(str); } const FOLD_FLOW = 'flow'; const FOLD_BLOCK = 'block'; const FOLD_QUOTED = 'quoted'; // presumes i+1 is at the start of a line // returns index of last newline in more-indented block const consumeMoreIndentedLines = (text, i) => { let ch = text[i + 1]; while (ch === ' ' || ch === '\t') { do { ch = text[i += 1]; } while (ch && ch !== '\n'); ch = text[i + 1]; } return i; }; /** * Tries to keep input at up to `lineWidth` characters, splitting only on spaces * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are * terminated with `\n` and started with `indent`. * * @param {string} text * @param {string} indent * @param {string} [mode='flow'] `'block'` prevents more-indented lines * from being folded; `'quoted'` allows for `\` escapes, including escaped * newlines * @param {Object} options * @param {number} [options.indentAtStart] Accounts for leading contents on * the first line, defaulting to `indent.length` * @param {number} [options.lineWidth=80] * @param {number} [options.minContentWidth=20] Allow highly indented lines to * stretch the line width or indent content from the start * @param {function} options.onFold Called once if the text is folded * @param {function} options.onFold Called once if any line of text exceeds * lineWidth characters */ function foldFlowLines(text, indent, mode, { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow }) { if (!lineWidth || lineWidth < 0) return text; const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); if (text.length <= endStep) return text; const folds = []; const escapedFolds = {}; let end = lineWidth - indent.length; if (typeof indentAtStart === 'number') { if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) folds.push(0);else end = lineWidth - indentAtStart; } let split = undefined; let prev = undefined; let overflow = false; let i = -1; let escStart = -1; let escEnd = -1; if (mode === FOLD_BLOCK) { i = consumeMoreIndentedLines(text, i); if (i !== -1) end = i + endStep; } for (let ch; ch = text[i += 1];) { if (mode === FOLD_QUOTED && ch === '\\') { escStart = i; switch (text[i + 1]) { case 'x': i += 3; break; case 'u': i += 5; break; case 'U': i += 9; break; default: i += 1; } escEnd = i; } if (ch === '\n') { if (mode === FOLD_BLOCK) i = consumeMoreIndentedLines(text, i); end = i + endStep; split = undefined; } else { if (ch === ' ' && prev && prev !== ' ' && prev !== '\n' && prev !== '\t') { // space surrounded by non-space can be replaced with newline + indent const next = text[i + 1]; if (next && next !== ' ' && next !== '\n' && next !== '\t') split = i; } if (i >= end) { if (split) { folds.push(split); end = split + endStep; split = undefined; } else if (mode === FOLD_QUOTED) { // white-space collected at end may stretch past lineWidth while (prev === ' ' || prev === '\t') { prev = ch; ch = text[i += 1]; overflow = true; } // Account for newline escape, but don't break preceding escape const j = i > escEnd + 1 ? i - 2 : escStart - 1; // Bail out if lineWidth & minContentWidth are shorter than an escape string if (escapedFolds[j]) return text; folds.push(j); escapedFolds[j] = true; end = j + endStep; split = undefined; } else { overflow = true; } } } prev = ch; } if (overflow && onOverflow) onOverflow(); if (folds.length === 0) return text; if (onFold) onFold(); let res = text.slice(0, folds[0]); for (let i = 0; i < folds.length; ++i) { const fold = folds[i]; const end = folds[i + 1] || text.length; if (fold === 0) res = `\n${indent}${text.slice(0, end)}`;else { if (mode === FOLD_QUOTED && escapedFolds[fold]) res += `${text[fold]}\\`; res += `\n${indent}${text.slice(fold + 1, end)}`; } } return res; } const getFoldOptions = ({ indentAtStart }) => indentAtStart ? Object.assign({ indentAtStart }, strOptions.fold) : strOptions.fold; // Also checks for lines starting with %, as parsing the output as YAML 1.1 will // presume that's starting a new document. const containsDocumentMarker = str => /^(%|---|\.\.\.)/m.test(str); function lineLengthOverLimit(str, lineWidth, indentLength) { if (!lineWidth || lineWidth < 0) return false; const limit = lineWidth - indentLength; const strLen = str.length; if (strLen <= limit) return false; for (let i = 0, start = 0; i < strLen; ++i) { if (str[i] === '\n') { if (i - start > limit) return true; start = i + 1; if (strLen - start <= limit) return false; } } return true; } function doubleQuotedString(value, ctx) { const { implicitKey } = ctx; const { jsonEncoding, minMultiLineLength } = strOptions.doubleQuoted; const json = JSON.stringify(value); if (jsonEncoding) return json; const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : ''); let str = ''; let start = 0; for (let i = 0, ch = json[i]; ch; ch = json[++i]) { if (ch === ' ' && json[i + 1] === '\\' && json[i + 2] === 'n') { // space before newline needs to be escaped to not be folded str += json.slice(start, i) + '\\ '; i += 1; start = i; ch = '\\'; } if (ch === '\\') switch (json[i + 1]) { case 'u': { str += json.slice(start, i); const code = json.substr(i + 2, 4); switch (code) { case '0000': str += '\\0'; break; case '0007': str += '\\a'; break; case '000b': str += '\\v'; break; case '001b': str += '\\e'; break; case '0085': str += '\\N'; break; case '00a0': str += '\\_'; break; case '2028': str += '\\L'; break; case '2029': str += '\\P'; break; default: if (code.substr(0, 2) === '00') str += '\\x' + code.substr(2);else str += json.substr(i, 6); } i += 5; start = i + 1; } break; case 'n': if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { i += 1; } else { // folding will eat first newline str += json.slice(start, i) + '\n\n'; while (json[i + 2] === '\\' && json[i + 3] === 'n' && json[i + 4] !== '"') { str += '\n'; i += 2; } str += indent; // space after newline needs to be escaped to not be folded if (json[i + 2] === ' ') str += '\\'; i += 1; start = i + 1; } break; default: i += 1; } } str = start ? str + json.slice(start) : json; return implicitKey ? str : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx)); } function singleQuotedString(value, ctx) { if (ctx.implicitKey) { if (/\n/.test(value)) return doubleQuotedString(value, ctx); } else { // single quoted string can't have leading or trailing whitespace around newline if (/[ \t]\n|\n[ \t]/.test(value)) return doubleQuotedString(value, ctx); } const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : ''); const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&\n${indent}`) + "'"; return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx)); } function blockString({ comment, type, value }, ctx, onComment, onChompKeep) { // 1. Block can't end in whitespace unless the last line is non-empty. // 2. Strings consisting of only whitespace are best rendered explicitly. if (/\n[\t ]+$/.test(value) || /^\s*$/.test(value)) { return doubleQuotedString(value, ctx); } const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value) ? ' ' : ''); const indentSize = indent ? '2' : '1'; // root is at -1 const literal = type === PlainValue.Type.BLOCK_FOLDED ? false : type === PlainValue.Type.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, strOptions.fold.lineWidth, indent.length); let header = literal ? '|' : '>'; if (!value) return header + '\n'; let wsStart = ''; let wsEnd = ''; value = value.replace(/[\n\t ]*$/, ws => { const n = ws.indexOf('\n'); if (n === -1) { header += '-'; // strip } else if (value === ws || n !== ws.length - 1) { header += '+'; // keep if (onChompKeep) onChompKeep(); } wsEnd = ws.replace(/\n$/, ''); return ''; }).replace(/^[\n ]*/, ws => { if (ws.indexOf(' ') !== -1) header += indentSize; const m = ws.match(/ +$/); if (m) { wsStart = ws.slice(0, -m[0].length); return m[0]; } else { wsStart = ws; return ''; } }); if (wsEnd) wsEnd = wsEnd.replace(/\n+(?!\n|$)/g, `$&${indent}`); if (wsStart) wsStart = wsStart.replace(/\n+/g, `$&${indent}`); if (comment) { header += ' #' + comment.replace(/ ?[\r\n]+/g, ' '); if (onComment) onComment(); } if (!value) return `${header}${indentSize}\n${indent}${wsEnd}`; if (literal) { value = value.replace(/\n+/g, `$&${indent}`); return `${header}\n${indent}${wsStart}${value}${wsEnd}`; } value = value.replace(/\n+/g, '\n$&').replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded // ^ ind.line ^ empty ^ capture next empty lines only at end of indent .replace(/\n+/g, `$&${indent}`); const body = foldFlowLines(`${wsStart}${value}${wsEnd}`, indent, FOLD_BLOCK, strOptions.fold); return `${header}\n${indent}${body}`; } function plainString(item, ctx, onComment, onChompKeep) { const { comment, type, value } = item; const { actualString, implicitKey, indent, inFlow } = ctx; if (implicitKey && /[\n[\]{},]/.test(value) || inFlow && /[[\]{},]/.test(value)) { return doubleQuotedString(value, ctx); } if (!value || /^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) { // not allowed: // - empty string, '-' or '?' // - start with an indicator character (except [?:-]) or /[?-] / // - '\n ', ': ' or ' \n' anywhere // - '#' not preceded by a non-space char // - end with ' ' or ':' return implicitKey || inFlow || value.indexOf('\n') === -1 ? value.indexOf('"') !== -1 && value.indexOf("'") === -1 ? singleQuotedString(value, ctx) : doubleQuotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep); } if (!implicitKey && !inFlow && type !== PlainValue.Type.PLAIN && value.indexOf('\n') !== -1) { // Where allowed & type not set explicitly, prefer block style for multiline strings return blockString(item, ctx, onComment, onChompKeep); } if (indent === '' && containsDocumentMarker(value)) { ctx.forceBlockIndent = true; return blockString(item, ctx, onComment, onChompKeep); } const str = value.replace(/\n+/g, `$&\n${indent}`); // Verify that output will be parsed as a string, as e.g. plain numbers and // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'), // and others in v1.1. if (actualString) { const { tags } = ctx.doc.schema; const resolved = resolveScalar(str, tags, tags.scalarFallback).value; if (typeof resolved !== 'string') return doubleQuotedString(value, ctx); } const body = implicitKey ? str : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx)); if (comment && !inFlow && (body.indexOf('\n') !== -1 || comment.indexOf('\n') !== -1)) { if (onComment) onComment(); return addCommentBefore(body, indent, comment); } return body; } function stringifyString(item, ctx, onComment, onChompKeep) { const { defaultType } = strOptions; const { implicitKey, inFlow } = ctx; let { type, value } = item; if (typeof value !== 'string') { value = String(value); item = Object.assign({}, item, { value }); } const _stringify = _type => { switch (_type) { case PlainValue.Type.BLOCK_FOLDED: case PlainValue.Type.BLOCK_LITERAL: return blockString(item, ctx, onComment, onChompKeep); case PlainValue.Type.QUOTE_DOUBLE: return doubleQuotedString(value, ctx); case PlainValue.Type.QUOTE_SINGLE: return singleQuotedString(value, ctx); case PlainValue.Type.PLAIN: return plainString(item, ctx, onComment, onChompKeep); default: return null; } }; if (type !== PlainValue.Type.QUOTE_DOUBLE && /[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(value)) { // force double quotes on control characters type = PlainValue.Type.QUOTE_DOUBLE; } else if ((implicitKey || inFlow) && (type === PlainValue.Type.BLOCK_FOLDED || type === PlainValue.Type.BLOCK_LITERAL)) { // should not happen; blocks are not valid inside flow containers type = PlainValue.Type.QUOTE_DOUBLE; } let res = _stringify(type); if (res === null) { res = _stringify(defaultType); if (res === null) throw new Error(`Unsupported default string type ${defaultType}`); } return res; } function stringifyNumber({ format, minFractionDigits, tag, value }) { if (typeof value === 'bigint') return String(value); if (!isFinite(value)) return isNaN(value) ? '.nan' : value < 0 ? '-.inf' : '.inf'; let n = JSON.stringify(value); if (!format && minFractionDigits && (!tag || tag === 'tag:yaml.org,2002:float') && /^\d/.test(n)) { let i = n.indexOf('.'); if (i < 0) { i = n.length; n += '.'; } let d = minFractionDigits - (n.length - i - 1); while (d-- > 0) n += '0'; } return n; } function checkFlowCollectionEnd(errors, cst) { let char, name; switch (cst.type) { case PlainValue.Type.FLOW_MAP: char = '}'; name = 'flow map'; break; case PlainValue.Type.FLOW_SEQ: char = ']'; name = 'flow sequence'; break; default: errors.push(new PlainValue.YAMLSemanticError(cst, 'Not a flow collection!?')); return; } let lastItem; for (let i = cst.items.length - 1; i >= 0; --i) { const item = cst.items[i]; if (!item || item.type !== PlainValue.Type.COMMENT) { lastItem = item; break; } } if (lastItem && lastItem.char !== char) { const msg = `Expected ${name} to end with ${char}`; let err; if (typeof lastItem.offset === 'number') { err = new PlainValue.YAMLSemanticError(cst, msg); err.offset = lastItem.offset + 1; } else { err = new PlainValue.YAMLSemanticError(lastItem, msg); if (lastItem.range && lastItem.range.end) err.offset = lastItem.range.end - lastItem.range.start; } errors.push(err); } } function checkFlowCommentSpace(errors, comment) { const prev = comment.context.src[comment.range.start - 1]; if (prev !== '\n' && prev !== '\t' && prev !== ' ') { const msg = 'Comments must be separated from other tokens by white space characters'; errors.push(new PlainValue.YAMLSemanticError(comment, msg)); } } function getLongKeyError(source, key) { const sk = String(key); const k = sk.substr(0, 8) + '...' + sk.substr(-8); return new PlainValue.YAMLSemanticError(source, `The "${k}" key is too long`); } function resolveComments(collection, comments) { for (const { afterKey, before, comment } of comments) { let item = collection.items[before]; if (!item) { if (comment !== undefined) { if (collection.comment) collection.comment += '\n' + comment;else collection.comment = comment; } } else { if (afterKey && item.value) item = item.value; if (comment === undefined) { if (afterKey || !item.commentBefore) item.spaceBefore = true; } else { if (item.commentBefore) item.commentBefore += '\n' + comment;else item.commentBefore = comment; } } } } // on error, will return { str: string, errors: Error[] } function resolveString(doc, node) { const res = node.strValue; if (!res) return ''; if (typeof res === 'string') return res; res.errors.forEach(error => { if (!error.source) error.source = node; doc.errors.push(error); }); return res.str; } function resolveTagHandle(doc, node) { const { handle, suffix } = node.tag; let prefix = doc.tagPrefixes.find(p => p.handle === handle); if (!prefix) { const dtp = doc.getDefaults().tagPrefixes; if (dtp) prefix = dtp.find(p => p.handle === handle); if (!prefix) throw new PlainValue.YAMLSemanticError(node, `The ${handle} tag handle is non-default and was not declared.`); } if (!suffix) throw new PlainValue.YAMLSemanticError(node, `The ${handle} tag has no suffix.`); if (handle === '!' && (doc.version || doc.options.version) === '1.0') { if (suffix[0] === '^') { doc.warnings.push(new PlainValue.YAMLWarning(node, 'YAML 1.0 ^ tag expansion is not supported')); return suffix; } if (/[:/]/.test(suffix)) { // word/foo -> tag:word.yaml.org,2002:foo const vocab = suffix.match(/^([a-z0-9-]+)\/(.*)/i); return vocab ? `tag:${vocab[1]}.yaml.org,2002:${vocab[2]}` : `tag:${suffix}`; } } return prefix.prefix + decodeURIComponent(suffix); } function resolveTagName(doc, node) { const { tag, type } = node; let nonSpecific = false; if (tag) { const { handle, suffix, verbatim } = tag; if (verbatim) { if (verbatim !== '!' && verbatim !== '!!') return verbatim; const msg = `Verbatim tags aren't resolved, so ${verbatim} is invalid.`; doc.errors.push(new PlainValue.YAMLSemanticError(node, msg)); } else if (handle === '!' && !suffix) { nonSpecific = true; } else { try { return resolveTagHandle(doc, node); } catch (error) { doc.errors.push(error); } } } switch (type) { case PlainValue.Type.BLOCK_FOLDED: case PlainValue.Type.BLOCK_LITERAL: case PlainValue.Type.QUOTE_DOUBLE: case PlainValue.Type.QUOTE_SINGLE: return PlainValue.defaultTags.STR; case PlainValue.Type.FLOW_MAP: case PlainValue.Type.MAP: return PlainValue.defaultTags.MAP; case PlainValue.Type.FLOW_SEQ: case PlainValue.Type.SEQ: return PlainValue.defaultTags.SEQ; case PlainValue.Type.PLAIN: return nonSpecific ? PlainValue.defaultTags.STR : null; default: return null; } } function resolveByTagName(doc, node, tagName) { const { tags } = doc.schema; const matchWithTest = []; for (const tag of tags) { if (tag.tag === tagName) { if (tag.test) matchWithTest.push(tag);else { const res = tag.resolve(doc, node); return res instanceof Collection ? res : new Scalar(res); } } } const str = resolveString(doc, node); if (typeof str === 'string' && matchWithTest.length > 0) return resolveScalar(str, matchWithTest, tags.scalarFallback); return null; } function getFallbackTagName({ type }) { switch (type) { case PlainValue.Type.FLOW_MAP: case PlainValue.Type.MAP: return PlainValue.defaultTags.MAP; case PlainValue.Type.FLOW_SEQ: case PlainValue.Type.SEQ: return PlainValue.defaultTags.SEQ; default: return PlainValue.defaultTags.STR; } } function resolveTag(doc, node, tagName) { try { const res = resolveByTagName(doc, node, tagName); if (res) { if (tagName && node.tag) res.tag = tagName; return res; } } catch (error) { /* istanbul ignore if */ if (!error.source) error.source = node; doc.errors.push(error); return null; } try { const fallback = getFallbackTagName(node); if (!fallback) throw new Error(`The tag ${tagName} is unavailable`); const msg = `The tag ${tagName} is unavailable, falling back to ${fallback}`; doc.warnings.push(new PlainValue.YAMLWarning(node, msg)); const res = resolveByTagName(doc, node, fallback); res.tag = tagName; return res; } catch (error) { const refError = new PlainValue.YAMLReferenceError(node, error.message); refError.stack = error.stack; doc.errors.push(refError); return null; } } const isCollectionItem = node => { if (!node) return false; const { type } = node; return type === PlainValue.Type.MAP_KEY || type === PlainValue.Type.MAP_VALUE || type === PlainValue.Type.SEQ_ITEM; }; function resolveNodeProps(errors, node) { const comments = { before: [], after: [] }; let hasAnchor = false; let hasTag = false; const props = isCollectionItem(node.context.parent) ? node.context.parent.props.concat(node.props) : node.props; for (const { start, end } of props) { switch (node.context.src[start]) { case PlainValue.Char.COMMENT: { if (!node.commentHasRequiredWhitespace(start)) { const msg = 'Comments must be separated from other tokens by white space characters'; errors.push(new PlainValue.YAMLSemanticError(node, msg)); } const { header, valueRange } = node; const cc = valueRange && (start > valueRange.start || header && start > header.start) ? comments.after : comments.before; cc.push(node.context.src.slice(start + 1, end)); break; } // Actual anchor & tag resolution is handled by schema, here we just complain case PlainValue.Char.ANCHOR: if (hasAnchor) { const msg = 'A node can have at most one anchor'; errors.push(new PlainValue.YAMLSemanticError(node, msg)); } hasAnchor = true; break; case PlainValue.Char.TAG: if (hasTag) { const msg = 'A node can have at most one tag'; errors.push(new PlainValue.YAMLSemanticError(node, msg)); } hasTag = true; break; } } return { comments, hasAnchor, hasTag }; } function resolveNodeValue(doc, node) { const { anchors, errors, schema } = doc; if (node.type === PlainValue.Type.ALIAS) { const name = node.rawValue; const src = anchors.getNode(name); if (!src) { const msg = `Aliased anchor not found: ${name}`; errors.push(new PlainValue.YAMLReferenceError(node, msg)); return null; } // Lazy resolution for circular references const res = new Alias(src); anchors._cstAliases.push(res); return res; } const tagName = resolveTagName(doc, node); if (tagName) return resolveTag(doc, node, tagName); if (node.type !== PlainValue.Type.PLAIN) { const msg = `Failed to resolve ${node.type} node here`; errors.push(new PlainValue.YAMLSyntaxError(node, msg)); return null; } try { const str = resolveString(doc, node); return resolveScalar(str, schema.tags, schema.tags.scalarFallback); } catch (error) { if (!error.source) error.source = node; errors.push(error); return null; } } // sets node.resolved on success function resolveNode(doc, node) { if (!node) return null; if (node.error) doc.errors.push(node.error); const { comments, hasAnchor, hasTag } = resolveNodeProps(doc.errors, node); if (hasAnchor) { const { anchors } = doc; const name = node.anchor; const prev = anchors.getNode(name); // At this point, aliases for any preceding node with the same anchor // name have already been resolved, so it may safely be renamed. if (prev) anchors.map[anchors.newName(name)] = prev; // During parsing, we need to store the CST node in anchors.map as // anchors need to be available during resolution to allow for // circular references. anchors.map[name] = node; } if (node.type === PlainValue.Type.ALIAS && (hasAnchor || hasTag)) { const msg = 'An alias node must not specify any properties'; doc.errors.push(new PlainValue.YAMLSemanticError(node, msg)); } const res = resolveNodeValue(doc, node); if (res) { res.range = [node.range.start, node.range.end]; if (doc.options.keepCstNodes) res.cstNode = node; if (doc.options.keepNodeTypes) res.type = node.type; const cb = comments.before.join('\n'); if (cb) { res.commentBefore = res.commentBefore ? `${res.commentBefore}\n${cb}` : cb; } const ca = comments.after.join('\n'); if (ca) res.comment = res.comment ? `${res.comment}\n${ca}` : ca; } return node.resolved = res; } function resolveMap(doc, cst) { if (cst.type !== PlainValue.Type.MAP && cst.type !== PlainValue.Type.FLOW_MAP) { const msg = `A ${cst.type} node cannot be resolved as a mapping`; doc.errors.push(new PlainValue.YAMLSyntaxError(cst, msg)); return null; } const { comments, items } = cst.type === PlainValue.Type.FLOW_MAP ? resolveFlowMapItems(doc, cst) : resolveBlockMapItems(doc, cst); const map = new YAMLMap(); map.items = items; resolveComments(map, comments); let hasCollectionKey = false; for (let i = 0; i < items.length; ++i) { const { key: iKey } = items[i]; if (iKey instanceof Collection) hasCollectionKey = true; if (doc.schema.merge && iKey && iKey.value === MERGE_KEY) { items[i] = new Merge(items[i]); const sources = items[i].value.items; let error = null; sources.some(node => { if (node instanceof Alias) { // During parsing, alias sources are CST nodes; to account for // circular references their resolved values can't be used here. const { type } = node.source; if (type === PlainValue.Type.MAP || type === PlainValue.Type.FLOW_MAP) return false; return error = 'Merge nodes aliases can only point to maps'; } return error = 'Merge nodes can only have Alias nodes as values'; }); if (error) doc.errors.push(new PlainValue.YAMLSemanticError(cst, error)); } else { for (let j = i + 1; j < items.length; ++j) { const { key: jKey } = items[j]; if (iKey === jKey || iKey && jKey && Object.prototype.hasOwnProperty.call(iKey, 'value') && iKey.value === jKey.value) { const msg = `Map keys must be unique; "${iKey}" is repeated`; doc.errors.push(new PlainValue.YAMLSemanticError(cst, msg)); break; } } } } if (hasCollectionKey && !doc.options.mapAsMap) { const warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.'; doc.warnings.push(new PlainValue.YAMLWarning(cst, warn)); } cst.resolved = map; return map; } const valueHasPairComment = ({ context: { lineStart, node, src }, props }) => { if (props.length === 0) return false; const { start } = props[0]; if (node && start > node.valueRange.start) return false; if (src[start] !== PlainValue.Char.COMMENT) return false; for (let i = lineStart; i < start; ++i) if (src[i] === '\n') return false; return true; }; function resolvePairComment(item, pair) { if (!valueHasPairComment(item)) return; const comment = item.getPropValue(0, PlainValue.Char.COMMENT, true); let found = false; const cb = pair.value.commentBefore; if (cb && cb.startsWith(comment)) { pair.value.commentBefore = cb.substr(comment.length + 1); found = true; } else { const cc = pair.value.comment; if (!item.node && cc && cc.startsWith(comment)) { pair.value.comment = cc.substr(comment.length + 1); found = true; } } if (found) pair.comment = comment; } function resolveBlockMapItems(doc, cst) { const comments = []; const items = []; let key = undefined; let keyStart = null; for (let i = 0; i < cst.items.length; ++i) { const item = cst.items[i]; switch (item.type) { case PlainValue.Type.BLANK_LINE: comments.push({ afterKey: !!key, before: items.length }); break; case PlainValue.Type.COMMENT: comments.push({ afterKey: !!key, before: items.length, comment: item.comment }); break; case PlainValue.Type.MAP_KEY: if (key !== undefined) items.push(new Pair(key)); if (item.error) doc.errors.push(item.error); key = resolveNode(doc, item.node); keyStart = null; break; case PlainValue.Type.MAP_VALUE: { if (key === undefined) key = null; if (item.error) doc.errors.push(item.error); if (!item.context.atLineStart && item.node && item.node.type === PlainValue.Type.MAP && !item.node.context.atLineStart) { const msg = 'Nested mappings are not allowed in compact mappings'; doc.errors.push(new PlainValue.YAMLSemanticError(item.node, msg)); } let valueNode = item.node; if (!valueNode && item.props.length > 0) { // Comments on an empty mapping value need to be preserved, so we // need to construct a minimal empty node here to use instead of the // missing `item.node`. -- eemeli/yaml#19 valueNode = new PlainValue.PlainValue(PlainValue.Type.PLAIN, []); valueNode.context = { parent: item, src: item.context.src }; const pos = item.range.start + 1; valueNode.range = { start: pos, end: pos }; valueNode.valueRange = { start: pos, end: pos }; if (typeof item.range.origStart === 'number') { const origPos = item.range.origStart + 1; valueNode.range.origStart = valueNode.range.origEnd = origPos; valueNode.valueRange.origStart = valueNode.valueRange.origEnd = origPos; } } const pair = new Pair(key, resolveNode(doc, valueNode)); resolvePairComment(item, pair); items.push(pair); if (key && typeof keyStart === 'number') { if (item.range.start > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key)); } key = undefined; keyStart = null; } break; default: if (key !== undefined) items.push(new Pair(key)); key = resolveNode(doc, item); keyStart = item.range.start; if (item.error) doc.errors.push(item.error); next: for (let j = i + 1;; ++j) { const nextItem = cst.items[j]; switch (nextItem && nextItem.type) { case PlainValue.Type.BLANK_LINE: case PlainValue.Type.COMMENT: continue next; case PlainValue.Type.MAP_VALUE: break next; default: { const msg = 'Implicit map keys need to be followed by map values'; doc.errors.push(new PlainValue.YAMLSemanticError(item, msg)); break next; } } } if (item.valueRangeContainsNewline) { const msg = 'Implicit map keys need to be on a single line'; doc.errors.push(new PlainValue.YAMLSemanticError(item, msg)); } } } if (key !== undefined) items.push(new Pair(key)); return { comments, items }; } function resolveFlowMapItems(doc, cst) { const comments = []; const items = []; let key = undefined; let explicitKey = false; let next = '{'; for (let i = 0; i < cst.items.length; ++i) { const item = cst.items[i]; if (typeof item.char === 'string') { const { char, offset } = item; if (char === '?' && key === undefined && !explicitKey) { explicitKey = true; next = ':'; continue; } if (char === ':') { if (key === undefined) key = null; if (next === ':') { next = ','; continue; } } else { if (explicitKey) { if (key === undefined && char !== ',') key = null; explicitKey = false; } if (key !== undefined) { items.push(new Pair(key)); key = undefined; if (char === ',') { next = ':'; continue; } } } if (char === '}') { if (i === cst.items.length - 1) continue; } else if (char === next) { next = ':'; continue; } const msg = `Flow map contains an unexpected ${char}`; const err = new PlainValue.YAMLSyntaxError(cst, msg); err.offset = offset; doc.errors.push(err); } else if (item.type === PlainValue.Type.BLANK_LINE) { comments.push({ afterKey: !!key, before: items.length }); } else if (item.type === PlainValue.Type.COMMENT) { checkFlowCommentSpace(doc.errors, item); comments.push({ afterKey: !!key, before: items.length, comment: item.comment }); } else if (key === undefined) { if (next === ',') doc.errors.push(new PlainValue.YAMLSemanticError(item, 'Separator , missing in flow map')); key = resolveNode(doc, item); } else { if (next !== ',') doc.errors.push(new PlainValue.YAMLSemanticError(item, 'Indicator : missing in flow map entry')); items.push(new Pair(key, resolveNode(doc, item))); key = undefined; explicitKey = false; } } checkFlowCollectionEnd(doc.errors, cst); if (key !== undefined) items.push(new Pair(key)); return { comments, items }; } function resolveSeq(doc, cst) { if (cst.type !== PlainValue.Type.SEQ && cst.type !== PlainValue.Type.FLOW_SEQ) { const msg = `A ${cst.type} node cannot be resolved as a sequence`; doc.errors.push(new PlainValue.YAMLSyntaxError(cst, msg)); return null; } const { comments, items } = cst.type === PlainValue.Type.FLOW_SEQ ? resolveFlowSeqItems(doc, cst) : resolveBlockSeqItems(doc, cst); const seq = new YAMLSeq(); seq.items = items; resolveComments(seq, comments); if (!doc.options.mapAsMap && items.some(it => it instanceof Pair && it.key instanceof Collection)) { const warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.'; doc.warnings.push(new PlainValue.YAMLWarning(cst, warn)); } cst.resolved = seq; return seq; } function resolveBlockSeqItems(doc, cst) { const comments = []; const items = []; for (let i = 0; i < cst.items.length; ++i) { const item = cst.items[i]; switch (item.type) { case PlainValue.Type.BLANK_LINE: comments.push({ before: items.length }); break; case PlainValue.Type.COMMENT: comments.push({ comment: item.comment, before: items.length }); break; case PlainValue.Type.SEQ_ITEM: if (item.error) doc.errors.push(item.error); items.push(resolveNode(doc, item.node)); if (item.hasProps) { const msg = 'Sequence items cannot have tags or anchors before the - indicator'; doc.errors.push(new PlainValue.YAMLSemanticError(item, msg)); } break; default: if (item.error) doc.errors.push(item.error); doc.errors.push(new PlainValue.YAMLSyntaxError(item, `Unexpected ${item.type} node in sequence`)); } } return { comments, items }; } function resolveFlowSeqItems(doc, cst) { const comments = []; const items = []; let explicitKey = false; let key = undefined; let keyStart = null; let next = '['; let prevItem = null; for (let i = 0; i < cst.items.length; ++i) { const item = cst.items[i]; if (typeof item.char === 'string') { const { char, offset } = item; if (char !== ':' && (explicitKey || key !== undefined)) { if (explicitKey && key === undefined) key = next ? items.pop() : null; items.push(new Pair(key)); explicitKey = false; key = undefined; keyStart = null; } if (char === next) { next = null; } else if (!next && char === '?') { explicitKey = true; } else if (next !== '[' && char === ':' && key === undefined) { if (next === ',') { key = items.pop(); if (key instanceof Pair) { const msg = 'Chaining flow sequence pairs is invalid'; const err = new PlainValue.YAMLSemanticError(cst, msg); err.offset = offset; doc.errors.push(err); } if (!explicitKey && typeof keyStart === 'number') { const keyEnd = item.range ? item.range.start : item.offset; if (keyEnd > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key)); const { src } = prevItem.context; for (let i = keyStart; i < keyEnd; ++i) if (src[i] === '\n') { const msg = 'Implicit keys of flow sequence pairs need to be on a single line'; doc.errors.push(new PlainValue.YAMLSemanticError(prevItem, msg)); break; } } } else { key = null; } keyStart = null; explicitKey = false; next = null; } else if (next === '[' || char !== ']' || i < cst.items.length - 1) { const msg = `Flow sequence contains an unexpected ${char}`; const err = new PlainValue.YAMLSyntaxError(cst, msg); err.offset = offset; doc.errors.push(err); } } else if (item.type === PlainValue.Type.BLANK_LINE) { comments.push({ before: items.length }); } else if (item.type === PlainValue.Type.COMMENT) { checkFlowCommentSpace(doc.errors, item); comments.push({ comment: item.comment, before: items.length }); } else { if (next) { const msg = `Expected a ${next} in flow sequence`; doc.errors.push(new PlainValue.YAMLSemanticError(item, msg)); } const value = resolveNode(doc, item); if (key === undefined) { items.push(value); prevItem = item; } else { items.push(new Pair(key, value)); key = undefined; } keyStart = item.range.start; next = ','; } } checkFlowCollectionEnd(doc.errors, cst); if (key !== undefined) items.push(new Pair(key)); return { comments, items }; } exports.Alias = Alias; exports.Collection = Collection; exports.Merge = Merge; exports.Node = Node; exports.Pair = Pair; exports.Scalar = Scalar; exports.YAMLMap = YAMLMap; exports.YAMLSeq = YAMLSeq; exports.addComment = addComment; exports.binaryOptions = binaryOptions; exports.boolOptions = boolOptions; exports.findPair = findPair; exports.intOptions = intOptions; exports.isEmptyPath = isEmptyPath; exports.nullOptions = nullOptions; exports.resolveMap = resolveMap; exports.resolveNode = resolveNode; exports.resolveSeq = resolveSeq; exports.resolveString = resolveString; exports.strOptions = strOptions; exports.stringifyNumber = stringifyNumber; exports.stringifyString = stringifyString; exports.toJSON = toJSON; /***/ }), /***/ 1758: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var PlainValue = __webpack_require__(51937); var resolveSeq = __webpack_require__(63970); /* global atob, btoa, Buffer */ const binary = { identify: value => value instanceof Uint8Array, // Buffer inherits from Uint8Array default: false, tag: 'tag:yaml.org,2002:binary', /** * Returns a Buffer in node and an Uint8Array in browsers * * To use the resulting buffer as an image, you'll want to do something like: * * const blob = new Blob([buffer], { type: 'image/jpeg' }) * document.querySelector('#photo').src = URL.createObjectURL(blob) */ resolve: (doc, node) => { const src = resolveSeq.resolveString(doc, node); if (typeof Buffer === 'function') { return Buffer.from(src, 'base64'); } else if (typeof atob === 'function') { // On IE 11, atob() can't handle newlines const str = atob(src.replace(/[\n\r]/g, '')); const buffer = new Uint8Array(str.length); for (let i = 0; i < str.length; ++i) buffer[i] = str.charCodeAt(i); return buffer; } else { const msg = 'This environment does not support reading binary tags; either Buffer or atob is required'; doc.errors.push(new PlainValue.YAMLReferenceError(node, msg)); return null; } }, options: resolveSeq.binaryOptions, stringify: ({ comment, type, value }, ctx, onComment, onChompKeep) => { let src; if (typeof Buffer === 'function') { src = value instanceof Buffer ? value.toString('base64') : Buffer.from(value.buffer).toString('base64'); } else if (typeof btoa === 'function') { let s = ''; for (let i = 0; i < value.length; ++i) s += String.fromCharCode(value[i]); src = btoa(s); } else { throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required'); } if (!type) type = resolveSeq.binaryOptions.defaultType; if (type === PlainValue.Type.QUOTE_DOUBLE) { value = src; } else { const { lineWidth } = resolveSeq.binaryOptions; const n = Math.ceil(src.length / lineWidth); const lines = new Array(n); for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { lines[i] = src.substr(o, lineWidth); } value = lines.join(type === PlainValue.Type.BLOCK_LITERAL ? '\n' : ' '); } return resolveSeq.stringifyString({ comment, type, value }, ctx, onComment, onChompKeep); } }; function parsePairs(doc, cst) { const seq = resolveSeq.resolveSeq(doc, cst); for (let i = 0; i < seq.items.length; ++i) { let item = seq.items[i]; if (item instanceof resolveSeq.Pair) continue;else if (item instanceof resolveSeq.YAMLMap) { if (item.items.length > 1) { const msg = 'Each pair must have its own sequence indicator'; throw new PlainValue.YAMLSemanticError(cst, msg); } const pair = item.items[0] || new resolveSeq.Pair(); if (item.commentBefore) pair.commentBefore = pair.commentBefore ? `${item.commentBefore}\n${pair.commentBefore}` : item.commentBefore; if (item.comment) pair.comment = pair.comment ? `${item.comment}\n${pair.comment}` : item.comment; item = pair; } seq.items[i] = item instanceof resolveSeq.Pair ? item : new resolveSeq.Pair(item); } return seq; } function createPairs(schema, iterable, ctx) { const pairs = new resolveSeq.YAMLSeq(schema); pairs.tag = 'tag:yaml.org,2002:pairs'; for (const it of iterable) { let key, value; if (Array.isArray(it)) { if (it.length === 2) { key = it[0]; value = it[1]; } else throw new TypeError(`Expected [key, value] tuple: ${it}`); } else if (it && it instanceof Object) { const keys = Object.keys(it); if (keys.length === 1) { key = keys[0]; value = it[key]; } else throw new TypeError(`Expected { key: value } tuple: ${it}`); } else { key = it; } const pair = schema.createPair(key, value, ctx); pairs.items.push(pair); } return pairs; } const pairs = { default: false, tag: 'tag:yaml.org,2002:pairs', resolve: parsePairs, createNode: createPairs }; class YAMLOMap extends resolveSeq.YAMLSeq { constructor() { super(); PlainValue._defineProperty(this, "add", resolveSeq.YAMLMap.prototype.add.bind(this)); PlainValue._defineProperty(this, "delete", resolveSeq.YAMLMap.prototype.delete.bind(this)); PlainValue._defineProperty(this, "get", resolveSeq.YAMLMap.prototype.get.bind(this)); PlainValue._defineProperty(this, "has", resolveSeq.YAMLMap.prototype.has.bind(this)); PlainValue._defineProperty(this, "set", resolveSeq.YAMLMap.prototype.set.bind(this)); this.tag = YAMLOMap.tag; } toJSON(_, ctx) { const map = new Map(); if (ctx && ctx.onCreate) ctx.onCreate(map); for (const pair of this.items) { let key, value; if (pair instanceof resolveSeq.Pair) { key = resolveSeq.toJSON(pair.key, '', ctx); value = resolveSeq.toJSON(pair.value, key, ctx); } else { key = resolveSeq.toJSON(pair, '', ctx); } if (map.has(key)) throw new Error('Ordered maps must not include duplicate keys'); map.set(key, value); } return map; } } PlainValue._defineProperty(YAMLOMap, "tag", 'tag:yaml.org,2002:omap'); function parseOMap(doc, cst) { const pairs = parsePairs(doc, cst); const seenKeys = []; for (const { key } of pairs.items) { if (key instanceof resolveSeq.Scalar) { if (seenKeys.includes(key.value)) { const msg = 'Ordered maps must not include duplicate keys'; throw new PlainValue.YAMLSemanticError(cst, msg); } else { seenKeys.push(key.value); } } } return Object.assign(new YAMLOMap(), pairs); } function createOMap(schema, iterable, ctx) { const pairs = createPairs(schema, iterable, ctx); const omap = new YAMLOMap(); omap.items = pairs.items; return omap; } const omap = { identify: value => value instanceof Map, nodeClass: YAMLOMap, default: false, tag: 'tag:yaml.org,2002:omap', resolve: parseOMap, createNode: createOMap }; class YAMLSet extends resolveSeq.YAMLMap { constructor() { super(); this.tag = YAMLSet.tag; } add(key) { const pair = key instanceof resolveSeq.Pair ? key : new resolveSeq.Pair(key); const prev = resolveSeq.findPair(this.items, pair.key); if (!prev) this.items.push(pair); } get(key, keepPair) { const pair = resolveSeq.findPair(this.items, key); return !keepPair && pair instanceof resolveSeq.Pair ? pair.key instanceof resolveSeq.Scalar ? pair.key.value : pair.key : pair; } set(key, value) { if (typeof value !== 'boolean') throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`); const prev = resolveSeq.findPair(this.items, key); if (prev && !value) { this.items.splice(this.items.indexOf(prev), 1); } else if (!prev && value) { this.items.push(new resolveSeq.Pair(key)); } } toJSON(_, ctx) { return super.toJSON(_, ctx, Set); } toString(ctx, onComment, onChompKeep) { if (!ctx) return JSON.stringify(this); if (this.hasAllNullValues()) return super.toString(ctx, onComment, onChompKeep);else throw new Error('Set items must all have null values'); } } PlainValue._defineProperty(YAMLSet, "tag", 'tag:yaml.org,2002:set'); function parseSet(doc, cst) { const map = resolveSeq.resolveMap(doc, cst); if (!map.hasAllNullValues()) throw new PlainValue.YAMLSemanticError(cst, 'Set items must all have null values'); return Object.assign(new YAMLSet(), map); } function createSet(schema, iterable, ctx) { const set = new YAMLSet(); for (const value of iterable) set.items.push(schema.createPair(value, null, ctx)); return set; } const set = { identify: value => value instanceof Set, nodeClass: YAMLSet, default: false, tag: 'tag:yaml.org,2002:set', resolve: parseSet, createNode: createSet }; const parseSexagesimal = (sign, parts) => { const n = parts.split(':').reduce((n, p) => n * 60 + Number(p), 0); return sign === '-' ? -n : n; }; // hhhh:mm:ss.sss const stringifySexagesimal = ({ value }) => { if (isNaN(value) || !isFinite(value)) return resolveSeq.stringifyNumber(value); let sign = ''; if (value < 0) { sign = '-'; value = Math.abs(value); } const parts = [value % 60]; // seconds, including ms if (value < 60) { parts.unshift(0); // at least one : is required } else { value = Math.round((value - parts[0]) / 60); parts.unshift(value % 60); // minutes if (value >= 60) { value = Math.round((value - parts[0]) / 60); parts.unshift(value); // hours } } return sign + parts.map(n => n < 10 ? '0' + String(n) : String(n)).join(':').replace(/000000\d*$/, '') // % 60 may introduce error ; }; const intTime = { identify: value => typeof value === 'number', default: true, tag: 'tag:yaml.org,2002:int', format: 'TIME', test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/, resolve: (str, sign, parts) => parseSexagesimal(sign, parts.replace(/_/g, '')), stringify: stringifySexagesimal }; const floatTime = { identify: value => typeof value === 'number', default: true, tag: 'tag:yaml.org,2002:float', format: 'TIME', test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*)$/, resolve: (str, sign, parts) => parseSexagesimal(sign, parts.replace(/_/g, '')), stringify: stringifySexagesimal }; const timestamp = { identify: value => value instanceof Date, default: true, tag: 'tag:yaml.org,2002:timestamp', // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part // may be omitted altogether, resulting in a date format. In such a case, the time part is // assumed to be 00:00:00Z (start of day, UTC). test: RegExp('^(?:' + '([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd '(?:(?:t|T|[ \\t]+)' + // t | T | whitespace '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)? '(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30 ')?' + ')$'), resolve: (str, year, month, day, hour, minute, second, millisec, tz) => { if (millisec) millisec = (millisec + '00').substr(1, 3); let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec || 0); if (tz && tz !== 'Z') { let d = parseSexagesimal(tz[0], tz.slice(1)); if (Math.abs(d) < 30) d *= 60; date -= 60000 * d; } return new Date(date); }, stringify: ({ value }) => value.toISOString().replace(/((T00:00)?:00)?\.000Z$/, '') }; /* global console, process, YAML_SILENCE_DEPRECATION_WARNINGS, YAML_SILENCE_WARNINGS */ function shouldWarn(deprecation) { const env = typeof process !== 'undefined' && process.env || {}; if (deprecation) { if (typeof YAML_SILENCE_DEPRECATION_WARNINGS !== 'undefined') return !YAML_SILENCE_DEPRECATION_WARNINGS; return !env.YAML_SILENCE_DEPRECATION_WARNINGS; } if (typeof YAML_SILENCE_WARNINGS !== 'undefined') return !YAML_SILENCE_WARNINGS; return !env.YAML_SILENCE_WARNINGS; } function warn(warning, type) { if (shouldWarn(false)) { const emit = typeof process !== 'undefined' && process.emitWarning; // This will throw in Jest if `warning` is an Error instance due to // https://github.com/facebook/jest/issues/2549 if (emit) emit(warning, type);else { // eslint-disable-next-line no-console console.warn(type ? `${type}: ${warning}` : warning); } } } function warnFileDeprecation(filename) { if (shouldWarn(true)) { const path = filename.replace(/.*yaml[/\\]/i, '').replace(/\.js$/, '').replace(/\\/g, '/'); warn(`The endpoint 'yaml/${path}' will be removed in a future release.`, 'DeprecationWarning'); } } const warned = {}; function warnOptionDeprecation(name, alternative) { if (!warned[name] && shouldWarn(true)) { warned[name] = true; let msg = `The option '${name}' will be removed in a future release`; msg += alternative ? `, use '${alternative}' instead.` : '.'; warn(msg, 'DeprecationWarning'); } } exports.binary = binary; exports.floatTime = floatTime; exports.intTime = intTime; exports.omap = omap; exports.pairs = pairs; exports.set = set; exports.timestamp = timestamp; exports.warn = warn; exports.warnFileDeprecation = warnFileDeprecation; exports.warnOptionDeprecation = warnOptionDeprecation; /***/ }), /***/ 6792: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = __webpack_require__(93419).YAML /***/ }), /***/ 40737: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "__extends": () => (/* binding */ __extends), /* harmony export */ "__assign": () => (/* binding */ __assign), /* harmony export */ "__rest": () => (/* binding */ __rest), /* harmony export */ "__decorate": () => (/* binding */ __decorate), /* harmony export */ "__param": () => (/* binding */ __param), /* harmony export */ "__esDecorate": () => (/* binding */ __esDecorate), /* harmony export */ "__runInitializers": () => (/* binding */ __runInitializers), /* harmony export */ "__propKey": () => (/* binding */ __propKey), /* harmony export */ "__setFunctionName": () => (/* binding */ __setFunctionName), /* harmony export */ "__metadata": () => (/* binding */ __metadata), /* harmony export */ "__awaiter": () => (/* binding */ __awaiter), /* harmony export */ "__generator": () => (/* binding */ __generator), /* harmony export */ "__createBinding": () => (/* binding */ __createBinding), /* harmony export */ "__exportStar": () => (/* binding */ __exportStar), /* harmony export */ "__values": () => (/* binding */ __values), /* harmony export */ "__read": () => (/* binding */ __read), /* harmony export */ "__spread": () => (/* binding */ __spread), /* harmony export */ "__spreadArrays": () => (/* binding */ __spreadArrays), /* harmony export */ "__spreadArray": () => (/* binding */ __spreadArray), /* harmony export */ "__await": () => (/* binding */ __await), /* harmony export */ "__asyncGenerator": () => (/* binding */ __asyncGenerator), /* harmony export */ "__asyncDelegator": () => (/* binding */ __asyncDelegator), /* harmony export */ "__asyncValues": () => (/* binding */ __asyncValues), /* harmony export */ "__makeTemplateObject": () => (/* binding */ __makeTemplateObject), /* harmony export */ "__importStar": () => (/* binding */ __importStar), /* harmony export */ "__importDefault": () => (/* binding */ __importDefault), /* harmony export */ "__classPrivateFieldGet": () => (/* binding */ __classPrivateFieldGet), /* harmony export */ "__classPrivateFieldSet": () => (/* binding */ __classPrivateFieldSet), /* harmony export */ "__classPrivateFieldIn": () => (/* binding */ __classPrivateFieldIn), /* harmony export */ "__addDisposableResource": () => (/* binding */ __addDisposableResource), /* harmony export */ "__disposeResources": () => (/* binding */ __disposeResources), /* harmony export */ "__rewriteRelativeImportExtension": () => (/* binding */ __rewriteRelativeImportExtension), /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /****************************************************************************** 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, Iterator */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; } return __assign.apply(this, arguments); } 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; } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } } function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); var _, done = false; for (var i = decorators.length - 1; i >= 0; i--) { var context = {}; for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; for (var p in contextIn.access) context.access[p] = contextIn.access[p]; context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); if (kind === "accessor") { if (result === void 0) continue; if (result === null || typeof result !== "object") throw new TypeError("Object expected"); if (_ = accept(result.get)) descriptor.get = _; if (_ = accept(result.set)) descriptor.set = _; if (_ = accept(result.init)) initializers.unshift(_); } else if (_ = accept(result)) { if (kind === "field") initializers.unshift(_); else descriptor[key] = _; } } if (target) Object.defineProperty(target, contextIn.name, descriptor); done = true; }; function __runInitializers(thisArg, initializers, value) { var useValue = arguments.length > 2; for (var i = 0; i < initializers.length; i++) { value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); } return useValue ? value : void 0; }; function __propKey(x) { return typeof x === "symbol" ? x : "".concat(x); }; function __setFunctionName(f, name, prefix) { if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); }; function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var __createBinding = Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; }); function __exportStar(m, o) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } /** @deprecated */ function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } /** @deprecated */ function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; var __setModuleDefault = Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }; var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; } function __importDefault(mod) { return (mod && mod.__esModule) ? mod : { default: mod }; } function __classPrivateFieldGet(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); } function __classPrivateFieldSet(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; } function __classPrivateFieldIn(state, receiver) { if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); return typeof state === "function" ? receiver === state : state.has(receiver); } function __addDisposableResource(env, value, async) { if (value !== null && value !== void 0) { if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); var dispose, inner; if (async) { if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); dispose = value[Symbol.asyncDispose]; } if (dispose === void 0) { if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); dispose = value[Symbol.dispose]; if (async) inner = dispose; } if (typeof dispose !== "function") throw new TypeError("Object not disposable."); if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; env.stack.push({ value: value, dispose: dispose, async: async }); } else if (async) { env.stack.push({ async: true }); } return value; } var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; function __disposeResources(env) { function fail(e) { env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; env.hasError = true; } var r, s = 0; function next() { while (r = env.stack.pop()) { try { if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); if (r.dispose) { var result = r.dispose.call(r.value); if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); } else s |= 1; } catch (e) { fail(e); } } if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); if (env.hasError) throw env.error; } return next(); } function __rewriteRelativeImportExtension(path, preserveJsx) { if (typeof path === "string" && /^\.\.?\//.test(path)) { return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) { return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js"); }); } return path; } /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ __extends, __assign, __rest, __decorate, __param, __esDecorate, __runInitializers, __propKey, __setFunctionName, __metadata, __awaiter, __generator, __createBinding, __exportStar, __values, __read, __spread, __spreadArrays, __spreadArray, __await, __asyncGenerator, __asyncDelegator, __asyncValues, __makeTemplateObject, __importStar, __importDefault, __classPrivateFieldGet, __classPrivateFieldSet, __classPrivateFieldIn, __addDisposableResource, __disposeResources, __rewriteRelativeImportExtension, }); /***/ }), /***/ 2550: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "__extends": () => (/* binding */ __extends), /* harmony export */ "__assign": () => (/* binding */ __assign), /* harmony export */ "__rest": () => (/* binding */ __rest), /* harmony export */ "__decorate": () => (/* binding */ __decorate), /* harmony export */ "__param": () => (/* binding */ __param), /* harmony export */ "__esDecorate": () => (/* binding */ __esDecorate), /* harmony export */ "__runInitializers": () => (/* binding */ __runInitializers), /* harmony export */ "__propKey": () => (/* binding */ __propKey), /* harmony export */ "__setFunctionName": () => (/* binding */ __setFunctionName), /* harmony export */ "__metadata": () => (/* binding */ __metadata), /* harmony export */ "__awaiter": () => (/* binding */ __awaiter), /* harmony export */ "__generator": () => (/* binding */ __generator), /* harmony export */ "__createBinding": () => (/* binding */ __createBinding), /* harmony export */ "__exportStar": () => (/* binding */ __exportStar), /* harmony export */ "__values": () => (/* binding */ __values), /* harmony export */ "__read": () => (/* binding */ __read), /* harmony export */ "__spread": () => (/* binding */ __spread), /* harmony export */ "__spreadArrays": () => (/* binding */ __spreadArrays), /* harmony export */ "__spreadArray": () => (/* binding */ __spreadArray), /* harmony export */ "__await": () => (/* binding */ __await), /* harmony export */ "__asyncGenerator": () => (/* binding */ __asyncGenerator), /* harmony export */ "__asyncDelegator": () => (/* binding */ __asyncDelegator), /* harmony export */ "__asyncValues": () => (/* binding */ __asyncValues), /* harmony export */ "__makeTemplateObject": () => (/* binding */ __makeTemplateObject), /* harmony export */ "__importStar": () => (/* binding */ __importStar), /* harmony export */ "__importDefault": () => (/* binding */ __importDefault), /* harmony export */ "__classPrivateFieldGet": () => (/* binding */ __classPrivateFieldGet), /* harmony export */ "__classPrivateFieldSet": () => (/* binding */ __classPrivateFieldSet), /* harmony export */ "__classPrivateFieldIn": () => (/* binding */ __classPrivateFieldIn), /* harmony export */ "__addDisposableResource": () => (/* binding */ __addDisposableResource), /* harmony export */ "__disposeResources": () => (/* binding */ __disposeResources), /* harmony export */ "__rewriteRelativeImportExtension": () => (/* binding */ __rewriteRelativeImportExtension), /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /****************************************************************************** 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, Iterator */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; } return __assign.apply(this, arguments); } 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; } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } } function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); var _, done = false; for (var i = decorators.length - 1; i >= 0; i--) { var context = {}; for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; for (var p in contextIn.access) context.access[p] = contextIn.access[p]; context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); if (kind === "accessor") { if (result === void 0) continue; if (result === null || typeof result !== "object") throw new TypeError("Object expected"); if (_ = accept(result.get)) descriptor.get = _; if (_ = accept(result.set)) descriptor.set = _; if (_ = accept(result.init)) initializers.unshift(_); } else if (_ = accept(result)) { if (kind === "field") initializers.unshift(_); else descriptor[key] = _; } } if (target) Object.defineProperty(target, contextIn.name, descriptor); done = true; }; function __runInitializers(thisArg, initializers, value) { var useValue = arguments.length > 2; for (var i = 0; i < initializers.length; i++) { value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); } return useValue ? value : void 0; }; function __propKey(x) { return typeof x === "symbol" ? x : "".concat(x); }; function __setFunctionName(f, name, prefix) { if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); }; function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var __createBinding = Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; }); function __exportStar(m, o) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } /** @deprecated */ function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } /** @deprecated */ function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; var __setModuleDefault = Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }; var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; } function __importDefault(mod) { return (mod && mod.__esModule) ? mod : { default: mod }; } function __classPrivateFieldGet(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); } function __classPrivateFieldSet(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; } function __classPrivateFieldIn(state, receiver) { if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); return typeof state === "function" ? receiver === state : state.has(receiver); } function __addDisposableResource(env, value, async) { if (value !== null && value !== void 0) { if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); var dispose, inner; if (async) { if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); dispose = value[Symbol.asyncDispose]; } if (dispose === void 0) { if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); dispose = value[Symbol.dispose]; if (async) inner = dispose; } if (typeof dispose !== "function") throw new TypeError("Object not disposable."); if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; env.stack.push({ value: value, dispose: dispose, async: async }); } else if (async) { env.stack.push({ async: true }); } return value; } var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; function __disposeResources(env) { function fail(e) { env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; env.hasError = true; } var r, s = 0; function next() { while (r = env.stack.pop()) { try { if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); if (r.dispose) { var result = r.dispose.call(r.value); if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); } else s |= 1; } catch (e) { fail(e); } } if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); if (env.hasError) throw env.error; } return next(); } function __rewriteRelativeImportExtension(path, preserveJsx) { if (typeof path === "string" && /^\.\.?\//.test(path)) { return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) { return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js"); }); } return path; } /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ __extends, __assign, __rest, __decorate, __param, __esDecorate, __runInitializers, __propKey, __setFunctionName, __metadata, __awaiter, __generator, __createBinding, __exportStar, __values, __read, __spread, __spreadArrays, __spreadArray, __await, __asyncGenerator, __asyncDelegator, __asyncValues, __makeTemplateObject, __importStar, __importDefault, __classPrivateFieldGet, __classPrivateFieldSet, __classPrivateFieldIn, __addDisposableResource, __disposeResources, __rewriteRelativeImportExtension, }); /***/ }), /***/ 58243: /***/ ((module) => { "use strict"; module.exports = JSON.parse('[{"name":"AppVeyor","constant":"APPVEYOR","env":"APPVEYOR","pr":"APPVEYOR_PULL_REQUEST_NUMBER"},{"name":"Azure Pipelines","constant":"AZURE_PIPELINES","env":"SYSTEM_TEAMFOUNDATIONCOLLECTIONURI","pr":"SYSTEM_PULLREQUEST_PULLREQUESTID"},{"name":"Bamboo","constant":"BAMBOO","env":"bamboo_planKey"},{"name":"Bitbucket Pipelines","constant":"BITBUCKET","env":"BITBUCKET_COMMIT","pr":"BITBUCKET_PR_ID"},{"name":"Bitrise","constant":"BITRISE","env":"BITRISE_IO","pr":"BITRISE_PULL_REQUEST"},{"name":"Buddy","constant":"BUDDY","env":"BUDDY_WORKSPACE_ID","pr":"BUDDY_EXECUTION_PULL_REQUEST_ID"},{"name":"Buildkite","constant":"BUILDKITE","env":"BUILDKITE","pr":{"env":"BUILDKITE_PULL_REQUEST","ne":"false"}},{"name":"CircleCI","constant":"CIRCLE","env":"CIRCLECI","pr":"CIRCLE_PULL_REQUEST"},{"name":"Cirrus CI","constant":"CIRRUS","env":"CIRRUS_CI","pr":"CIRRUS_PR"},{"name":"AWS CodeBuild","constant":"CODEBUILD","env":"CODEBUILD_BUILD_ARN"},{"name":"Codeship","constant":"CODESHIP","env":{"CI_NAME":"codeship"}},{"name":"Drone","constant":"DRONE","env":"DRONE","pr":{"DRONE_BUILD_EVENT":"pull_request"}},{"name":"dsari","constant":"DSARI","env":"DSARI"},{"name":"GitLab CI","constant":"GITLAB","env":"GITLAB_CI"},{"name":"GoCD","constant":"GOCD","env":"GO_PIPELINE_LABEL"},{"name":"Hudson","constant":"HUDSON","env":"HUDSON_URL"},{"name":"Jenkins","constant":"JENKINS","env":["JENKINS_URL","BUILD_ID"],"pr":{"any":["ghprbPullId","CHANGE_ID"]}},{"name":"Magnum CI","constant":"MAGNUM","env":"MAGNUM"},{"name":"Netlify CI","constant":"NETLIFY","env":"NETLIFY_BUILD_BASE","pr":{"env":"PULL_REQUEST","ne":"false"}},{"name":"Sail CI","constant":"SAIL","env":"SAILCI","pr":"SAIL_PULL_REQUEST_NUMBER"},{"name":"Semaphore","constant":"SEMAPHORE","env":"SEMAPHORE","pr":"PULL_REQUEST_NUMBER"},{"name":"Shippable","constant":"SHIPPABLE","env":"SHIPPABLE","pr":{"IS_PULL_REQUEST":"true"}},{"name":"Solano CI","constant":"SOLANO","env":"TDDIUM","pr":"TDDIUM_PR_ID"},{"name":"Strider CD","constant":"STRIDER","env":"STRIDER"},{"name":"TaskCluster","constant":"TASKCLUSTER","env":["TASK_ID","RUN_ID"]},{"name":"TeamCity","constant":"TEAMCITY","env":"TEAMCITY_VERSION"},{"name":"Travis CI","constant":"TRAVIS","env":"TRAVIS","pr":{"env":"TRAVIS_PULL_REQUEST","ne":"false"}}]'); /***/ }), /***/ 66674: /***/ ((module) => { "use strict"; module.exports = {"i8":"1.14.0"}; /***/ }) }; ; //# sourceMappingURL=464.index.js.map